blob: ace4f55b570407cc23e7c9372b90f84840c43488 [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[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "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"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "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(
577 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100578 int char_len,
579 int compl_char_len,
580 int min_len,
581 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582{
583 int *wca; // Wide character array.
584 char_u *p;
585 int i, c;
586 int has_lower = FALSE;
587 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100588 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000589
590 IObuff[0] = NUL;
591
592 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100593 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000594 if (wca == NULL)
595 return IObuff;
596
597 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100598 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100599 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000600 if (has_mbyte)
601 wca[i] = mb_ptr2char_adv(&p);
602 else
603 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100604 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000605
606 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100607 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000608 for (i = 0; i < min_len; ++i)
609 {
glepnir6e199932024-12-14 21:13:27 +0100610 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000611 if (MB_ISLOWER(c))
612 {
613 has_lower = TRUE;
614 if (MB_ISUPPER(wca[i]))
615 {
616 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100617 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000618 wca[i] = MB_TOLOWER(wca[i]);
619 break;
620 }
621 }
622 }
623
624 // Rule 2: No lower case, 2nd consecutive letter converted to
625 // upper case.
626 if (!has_lower)
627 {
John Marriott5e6ea922024-11-23 14:01:57 +0100628 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000629 for (i = 0; i < min_len; ++i)
630 {
glepnir6e199932024-12-14 21:13:27 +0100631 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000632 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
633 {
634 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100635 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000636 wca[i] = MB_TOUPPER(wca[i]);
637 break;
638 }
639 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
640 }
641 }
642
643 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100644 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000645 for (i = 0; i < min_len; ++i)
646 {
glepnir6e199932024-12-14 21:13:27 +0100647 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000648 if (MB_ISLOWER(c))
649 wca[i] = MB_TOLOWER(wca[i]);
650 else if (MB_ISUPPER(c))
651 wca[i] = MB_TOUPPER(wca[i]);
652 }
653
654 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000655 p = IObuff;
656 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100657 ga_init2(&gap, 1, 500);
658 while (i < char_len)
659 {
660 if (gap.ga_data != NULL)
661 {
662 if (ga_grow(&gap, 10) == FAIL)
663 {
664 ga_clear(&gap);
665 return (char_u *)"[failed]";
666 }
667 p = (char_u *)gap.ga_data + gap.ga_len;
668 if (has_mbyte)
669 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
670 else
671 {
672 *p = wca[i++];
673 ++gap.ga_len;
674 }
675 }
676 else if ((p - IObuff) + 6 >= IOSIZE)
677 {
678 // Multi-byte characters can occupy up to five bytes more than
679 // ASCII characters, and we also need one byte for NUL, so when
680 // getting to six bytes from the edge of IObuff switch to using a
681 // growarray. Add the character in the next round.
682 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100683 {
684 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100685 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100686 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100687 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100688 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100689 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100690 }
691 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000692 p += (*mb_char2bytes)(wca[i++], p);
693 else
694 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000696 vim_free(wca);
697
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 if (gap.ga_data != NULL)
699 {
700 *tofree = gap.ga_data;
701 return gap.ga_data;
702 }
703
704 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000705 return IObuff;
706}
707
708/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100709 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
710 * case of the originally typed text is used, and the case of the completed
711 * text is inferred, ie this tries to work out what case you probably wanted
712 * the rest of the word to be in -- webb
713 */
714 int
715ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200716 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100717 int len,
718 int icase,
719 char_u *fname,
720 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100721 int cont_s_ipos, // next ^X<> will set initial_pos
722 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100723{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200724 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100726 int char_len; // count multi-byte characters
727 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100728 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200729 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100730 int res;
731 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100732
733 if (p_ic && curbuf->b_p_inf && len > 0)
734 {
735 // Infer case of completed part.
736
737 // Find actual length of completion.
738 if (has_mbyte)
739 {
740 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100741 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742 while (*p != NUL)
743 {
744 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100745 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100746 }
747 }
748 else
glepnir6e199932024-12-14 21:13:27 +0100749 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100750 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100751 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752
753 // Find actual length of original text.
754 if (has_mbyte)
755 {
John Marriott5e6ea922024-11-23 14:01:57 +0100756 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100757 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100758 while (*p != NUL)
759 {
760 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100761 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762 }
763 }
764 else
glepnir6e199932024-12-14 21:13:27 +0100765 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100766 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100767 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100768
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100769 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100770 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100771 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100772
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100773 str = ins_compl_infercase_gettext(str, char_len,
774 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100775 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200776 if (cont_s_ipos)
777 flags |= CP_CONT_S_IPOS;
778 if (icase)
779 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200780
glepnirf31cfa22025-03-06 21:59:13 +0100781 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100782 vim_free(tofree);
783 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784}
785
786/*
glepnirf31cfa22025-03-06 21:59:13 +0100787 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
788 */
789 static int
790cfc_has_mode(void)
791{
glepnir58760162025-03-13 21:39:51 +0100792 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
793 return (cfc_flags & CFC_KEYWORD) != 0;
794 else if (ctrl_x_mode_files())
795 return (cfc_flags & CFC_FILES) != 0;
796 else if (ctrl_x_mode_whole_line())
797 return (cfc_flags & CFC_WHOLELINE) != 0;
798 else
799 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100800}
801
802/*
Girish Palyab1565882025-04-15 20:16:00 +0200803 * Returns TRUE if matches should be sorted based on proximity to the cursor.
804 */
805 static int
806is_nearest_active(void)
807{
808 unsigned int flags = get_cot_flags();
809
810 return (flags & COT_NEAREST) && !(flags & COT_FUZZY);
811}
812
813/*
814 * Repositions a match in the completion list based on its proximity score.
815 * If the match is at the head and has a higher score than the next node,
816 * or if it's in the middle/tail and has a lower score than the previous node,
817 * it is moved to the correct position while maintaining ascending order.
818 */
819 static void
820reposition_match(compl_T *match)
821{
822 compl_T *insert_before = NULL;
823 compl_T *insert_after = NULL;
824
825 // Node is at head and score is too big
826 if (!match->cp_prev)
827 {
828 if (match->cp_next && match->cp_next->cp_score > 0 &&
829 match->cp_next->cp_score < match->cp_score)
830 {
831 // <c-p>: compl_first_match is at head and newly inserted node
832 compl_first_match = compl_curr_match = match->cp_next;
833 // Find the correct position in ascending order
834 insert_before = match->cp_next;
835 do
836 {
837 insert_after = insert_before;
838 insert_before = insert_before->cp_next;
839 } while (insert_before && insert_before->cp_score > 0 &&
840 insert_before->cp_score < match->cp_score);
841 }
842 else
843 return;
844 }
845 // Node is at tail or in the middle but score is too small
846 else
847 {
848 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
849 {
850 // <c-n>: compl_curr_match (and newly inserted match) is at tail
851 if (!match->cp_next)
852 compl_curr_match = compl_curr_match->cp_prev;
853 // Find the correct position in ascending order
854 insert_after = match->cp_prev;
855 do
856 {
857 insert_before = insert_after;
858 insert_after = insert_after->cp_prev;
859 } while (insert_after && insert_after->cp_score > 0 &&
860 insert_after->cp_score > match->cp_score);
861 }
862 else
863 return;
864 }
865
866 if (insert_after)
867 {
868 // Remove the match from its current position
869 if (match->cp_prev)
870 match->cp_prev->cp_next = match->cp_next;
871 else
872 compl_first_match = match->cp_next;
873 if (match->cp_next)
874 match->cp_next->cp_prev = match->cp_prev;
875
876 // Insert the match at the correct position
877 match->cp_next = insert_before;
878 match->cp_prev = insert_after;
879 insert_after->cp_next = match;
880 insert_before->cp_prev = match;
881 }
882}
883
884/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000885 * Add a match to the list of matches. The arguments are:
886 * str - text of the match to add
887 * len - length of "str". If -1, then the length of "str" is
888 * computed.
889 * fname - file name to associate with this match.
890 * cptext - list of strings to use with this match (for abbr, menu, info
891 * and kind)
892 * user_data - user supplied data (any vim type) for this match
893 * cdir - match direction. If 0, use "compl_direction".
894 * flags_arg - match flags (cp_flags)
895 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100896 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000897 * If "cdir" is FORWARD, then the match is added after the current match.
898 * Otherwise, it is added before the current match.
899 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100900 * If the given string is already in the list of completions, then return
901 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
902 * maybe because alloc() returns NULL, then FAIL is returned.
903 */
904 static int
905ins_compl_add(
906 char_u *str,
907 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100908 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100909 char_u **cptext, // extra text for popup menu or NULL
910 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100911 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200912 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200913 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100914 int *user_hl, // user abbr/kind hlattr
915 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100916{
glepnirf31cfa22025-03-06 21:59:13 +0100917 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100918 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200919 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100920 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100921
Bram Moolenaarceb06192021-04-04 15:05:22 +0200922 if (flags & CP_FAST)
923 fast_breakcheck();
924 else
925 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 if (got_int)
927 return FAIL;
928 if (len < 0)
929 len = (int)STRLEN(str);
930
931 // If the same match is already present, don't add it.
932 if (compl_first_match != NULL && !adup)
933 {
934 match = compl_first_match;
935 do
936 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000937 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100938 && STRNCMP(match->cp_str.string, str, len) == 0
939 && ((int)match->cp_str.length <= len
940 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200941 {
942 if (is_nearest_active() && score > 0 && score < match->cp_score)
943 {
944 match->cp_score = score;
945 reposition_match(match);
946 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100947 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200948 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100949 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000950 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100951 }
952
953 // Remove any popup menu before changing the list of matches.
954 ins_compl_del_pum();
955
956 // Allocate a new match structure.
957 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200958 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100959 if (match == NULL)
960 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100961 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100962 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100963 {
964 vim_free(match);
965 return FAIL;
966 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100967
John Marriott5e6ea922024-11-23 14:01:57 +0100968 match->cp_str.length = len;
969
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100970 // match-fname is:
971 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200972 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100973 // - NULL otherwise. --Acevedo
974 if (fname != NULL
975 && compl_curr_match != NULL
976 && compl_curr_match->cp_fname != NULL
977 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
978 match->cp_fname = compl_curr_match->cp_fname;
979 else if (fname != NULL)
980 {
981 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200982 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100983 }
984 else
985 match->cp_fname = NULL;
986 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100987 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
988 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100989 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200990 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100991
992 if (cptext != NULL)
993 {
994 int i;
995
996 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100997 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100998 if (cptext[i] != NULL && *cptext[i] != NUL)
999 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +01001000 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001001 }
Bram Moolenaarab782c52020-01-04 19:00:11 +01001002#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001003 if (user_data != NULL)
1004 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +01001005#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001006
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001007 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1008 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001009 if (compl_first_match == NULL)
1010 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001011 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1012 {
1013 current = compl_first_match->cp_next;
1014 prev = compl_first_match;
1015 inserted = FALSE;
1016 // The direction is ignored when using longest and
1017 // completefuzzycollect, because matches are inserted
1018 // and sorted by score.
1019 while (current != NULL && current != compl_first_match)
1020 {
1021 if (current->cp_score < score)
1022 {
1023 match->cp_next = current;
1024 match->cp_prev = current->cp_prev;
1025 if (current->cp_prev)
1026 current->cp_prev->cp_next = match;
1027 current->cp_prev = match;
1028 inserted = TRUE;
1029 break;
1030 }
1031 prev = current;
1032 current = current->cp_next;
1033 }
1034 if (!inserted)
1035 {
1036 prev->cp_next = match;
1037 match->cp_prev = prev;
1038 match->cp_next = compl_first_match;
1039 compl_first_match->cp_prev = match;
1040 }
1041 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001042 else if (dir == FORWARD)
1043 {
1044 match->cp_next = compl_curr_match->cp_next;
1045 match->cp_prev = compl_curr_match;
1046 }
1047 else // BACKWARD
1048 {
1049 match->cp_next = compl_curr_match;
1050 match->cp_prev = compl_curr_match->cp_prev;
1051 }
1052 if (match->cp_next)
1053 match->cp_next->cp_prev = match;
1054 if (match->cp_prev)
1055 match->cp_prev->cp_next = match;
1056 else // if there's nothing before, it is the first match
1057 compl_first_match = match;
1058 compl_curr_match = match;
1059
Girish Palyab1565882025-04-15 20:16:00 +02001060 if (is_nearest_active() && score > 0)
1061 reposition_match(match);
1062
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001063 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001064 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001065 ins_compl_longest_match(match);
1066
1067 return OK;
1068}
1069
1070/*
1071 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001072 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001073 */
1074 static int
1075ins_compl_equal(compl_T *match, char_u *str, int len)
1076{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001077 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001078 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001079 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001080 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1081 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001082}
1083
1084/*
glepnir6a38aff2024-12-16 21:56:16 +01001085 * when len is -1 mean use whole length of p otherwise part of p
1086 */
1087 static void
1088ins_compl_insert_bytes(char_u *p, int len)
1089{
1090 if (len == -1)
1091 len = (int)STRLEN(p);
1092 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001093 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001094}
1095
1096/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001097 * Checks if the column is within the currently inserted completion text
1098 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001099 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001100 */
1101 int
glepnir76bdb822025-02-08 19:04:51 +01001102ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001103{
glepnir76bdb822025-02-08 19:04:51 +01001104 int start_col;
1105 int attr;
1106
1107 if ((get_cot_flags() & COT_FUZZY)
1108 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001109 return -1;
1110
glepnir76bdb822025-02-08 19:04:51 +01001111 start_col = compl_col + (int)ins_compl_leader_len();
1112 if (!ins_compl_has_multiple())
1113 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1114
1115 // Multiple lines
1116 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1117 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1118 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1119 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001120
1121 return -1;
1122}
1123
1124/*
glepnir76bdb822025-02-08 19:04:51 +01001125 * Returns TRUE if the current completion string contains newline characters,
1126 * indicating it's a multi-line completion.
1127 */
1128 static int
1129ins_compl_has_multiple(void)
1130{
1131 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1132}
1133
1134/*
1135 * Returns TRUE if the given line number falls within the range of a multi-line
1136 * completion, i.e. between the starting line (compl_lnum) and current cursor
1137 * line. Always returns FALSE for single-line completions.
1138 */
1139 int
1140ins_compl_lnum_in_range(linenr_T lnum)
1141{
1142 if (!ins_compl_has_multiple())
1143 return FALSE;
1144 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1145}
1146
1147/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001148 * Reduce the longest common string for match "match".
1149 */
1150 static void
1151ins_compl_longest_match(compl_T *match)
1152{
1153 char_u *p, *s;
1154 int c1, c2;
1155 int had_match;
1156
John Marriott5e6ea922024-11-23 14:01:57 +01001157 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001158 {
1159 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001160 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1161 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001162 return;
1163
John Marriott5e6ea922024-11-23 14:01:57 +01001164 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001165 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001166 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001167
1168 // When the match isn't there (to avoid matching itself) remove it
1169 // again after redrawing.
1170 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001171 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001172 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001173
1174 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001176
1177 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001178 p = compl_leader.string;
1179 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001180 while (*p != NUL)
1181 {
1182 if (has_mbyte)
1183 {
1184 c1 = mb_ptr2char(p);
1185 c2 = mb_ptr2char(s);
1186 }
1187 else
1188 {
1189 c1 = *p;
1190 c2 = *s;
1191 }
1192 if ((match->cp_flags & CP_ICASE)
1193 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1194 break;
1195 if (has_mbyte)
1196 {
1197 MB_PTR_ADV(p);
1198 MB_PTR_ADV(s);
1199 }
1200 else
1201 {
1202 ++p;
1203 ++s;
1204 }
1205 }
1206
1207 if (*p != NUL)
1208 {
1209 // Leader was shortened, need to change the inserted text.
1210 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001211 compl_leader.length = (size_t)(p - compl_leader.string);
1212
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001213 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001214 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001215
1216 // When the match isn't there (to avoid matching itself) remove it
1217 // again after redrawing.
1218 if (!had_match)
1219 ins_compl_delete();
1220 }
1221
1222 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001223}
1224
1225/*
1226 * Add an array of matches to the list of matches.
1227 * Frees matches[].
1228 */
1229 static void
1230ins_compl_add_matches(
1231 int num_matches,
1232 char_u **matches,
1233 int icase)
1234{
1235 int i;
1236 int add_r = OK;
1237 int dir = compl_direction;
1238
1239 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001240 {
1241 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001242 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001243 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001244 // if dir was BACKWARD then honor it just once
1245 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001246 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001247 FreeWild(num_matches, matches);
1248}
1249
1250/*
1251 * Make the completion list cyclic.
1252 * Return the number of matches (excluding the original).
1253 */
1254 static int
1255ins_compl_make_cyclic(void)
1256{
1257 compl_T *match;
1258 int count = 0;
1259
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001260 if (compl_first_match == NULL)
1261 return 0;
1262
1263 // Find the end of the list.
1264 match = compl_first_match;
1265 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001266 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001267 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001268 match = match->cp_next;
1269 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001270 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001271 match->cp_next = compl_first_match;
1272 compl_first_match->cp_prev = match;
1273
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001274 return count;
1275}
1276
1277/*
1278 * Return whether there currently is a shown match.
1279 */
1280 int
1281ins_compl_has_shown_match(void)
1282{
1283 return compl_shown_match == NULL
1284 || compl_shown_match != compl_shown_match->cp_next;
1285}
1286
1287/*
1288 * Return whether the shown match is long enough.
1289 */
1290 int
1291ins_compl_long_shown_match(void)
1292{
John Marriott5e6ea922024-11-23 14:01:57 +01001293 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001294 > curwin->w_cursor.col - compl_col;
1295}
1296
1297/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001298 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001300 unsigned int
1301get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001302{
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001304}
1305
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001306/*
1307 * Update the screen and when there is any scrolling remove the popup menu.
1308 */
1309 static void
1310ins_compl_upd_pum(void)
1311{
1312 int h;
1313
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001314 if (compl_match_array == NULL)
1315 return;
1316
1317 h = curwin->w_cline_height;
1318 // Update the screen later, before drawing the popup menu over it.
1319 pum_call_update_screen();
1320 if (h != curwin->w_cline_height)
1321 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001322}
1323
1324/*
1325 * Remove any popup menu.
1326 */
1327 static void
1328ins_compl_del_pum(void)
1329{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001330 if (compl_match_array == NULL)
1331 return;
1332
1333 pum_undisplay();
1334 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001335}
1336
1337/*
1338 * Return TRUE if the popup menu should be displayed.
1339 */
1340 int
1341pum_wanted(void)
1342{
1343 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001344 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001345 return FALSE;
1346
1347 // The display looks bad on a B&W display.
1348 if (t_colors < 8
1349#ifdef FEAT_GUI
1350 && !gui.in_use
1351#endif
1352 )
1353 return FALSE;
1354 return TRUE;
1355}
1356
1357/*
1358 * Return TRUE if there are two or more matches to be shown in the popup menu.
1359 * One if 'completopt' contains "menuone".
1360 */
1361 static int
1362pum_enough_matches(void)
1363{
1364 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001365 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001366
1367 // Don't display the popup menu if there are no matches or there is only
1368 // one (ignoring the original text).
1369 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001370 do
1371 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001372 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001373 break;
1374 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001375 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001376
zeertzjq529b9ad2024-06-05 20:27:06 +02001377 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001378 return (i >= 1);
1379 return (i >= 2);
1380}
1381
Bram Moolenaar3075a452021-11-17 15:51:52 +00001382#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001383/*
1384 * Allocate Dict for the completed item.
1385 * { word, abbr, menu, kind, info }
1386 */
1387 static dict_T *
1388ins_compl_dict_alloc(compl_T *match)
1389{
1390 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1391
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001392 if (dict == NULL)
1393 return NULL;
1394
John Marriott5e6ea922024-11-23 14:01:57 +01001395 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001396 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1397 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1398 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1399 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1400 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1401 dict_add_string(dict, "user_data", (char_u *)"");
1402 else
1403 dict_add_tv(dict, "user_data", &match->cp_user_data);
1404
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001405 return dict;
1406}
1407
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001408/*
1409 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1410 * completion menu is changed.
1411 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001412 static void
1413trigger_complete_changed_event(int cur)
1414{
1415 dict_T *v_event;
1416 dict_T *item;
1417 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001418 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001419
1420 if (recursive)
1421 return;
1422
glepnir40891ba2025-02-10 22:18:00 +01001423 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001424 if (item == NULL)
1425 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001426 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001427 dict_add_dict(v_event, "completed_item", item);
1428 pum_set_event_info(v_event);
1429 dict_set_items_ro(v_event);
1430
1431 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001432 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001433 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001434 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001435 recursive = FALSE;
1436
Bram Moolenaar3075a452021-11-17 15:51:52 +00001437 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001438}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001439#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001440
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001441/*
glepnira218cc62024-06-03 19:32:39 +02001442 * pumitem qsort compare func
1443 */
1444 static int
zeertzjq8e567472024-06-14 20:04:42 +02001445ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001446{
1447 const int sa = (*(pumitem_T *)a).pum_score;
1448 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001449 const int ia = (*(pumitem_T *)a).pum_idx;
1450 const int ib = (*(pumitem_T *)b).pum_idx;
1451 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001452}
1453
1454/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001455 * Build a popup menu to show the completion matches.
1456 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1457 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001458 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001459 static int
1460ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001461{
1462 compl_T *compl;
1463 compl_T *shown_compl = NULL;
1464 int did_find_shown_match = FALSE;
1465 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001466 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001467 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001468 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001469 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001470 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001471 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1472 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001473 compl_T *match_head = NULL;
1474 compl_T *match_tail = NULL;
1475 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001476 int update_shown_match = fuzzy_filter;
Christian Brabandtb53d4fb2025-04-16 21:12:30 +02001477 int match_count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001478 int cur_source = -1;
1479 int max_matches_found = FALSE;
1480 int is_forward = compl_shows_dir_forward() && !fuzzy_filter;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001481
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001482 // Need to build the popup menu list.
1483 compl_match_arraysize = 0;
1484 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001485
glepnira49c0772024-11-30 10:56:30 +01001486 // If the current match is the original text don't find the first
1487 // match after it, don't highlight anything.
1488 if (match_at_original_text(compl_shown_match))
1489 shown_match_ok = TRUE;
1490
glepnire4e4d1c2025-04-02 20:18:25 +02001491 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1492 && compl_shown_match->cp_score > 0)
1493 update_shown_match = FALSE;
1494
glepnira49c0772024-11-30 10:56:30 +01001495 if (compl_leader.string != NULL
1496 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1497 && shown_match_ok == FALSE)
1498 compl_shown_match = compl_no_select ? compl_first_match
1499 : compl_first_match->cp_next;
1500
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001501 do
1502 {
glepnird4088ed2024-12-31 10:55:22 +01001503 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001504 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1505 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001506 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001507 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001508
Girish Palya0ac1eb32025-04-16 20:18:33 +02001509 if (is_forward && compl->cp_cpt_source_idx != -1)
1510 {
1511 if (cur_source != compl->cp_cpt_source_idx)
1512 {
1513 cur_source = compl->cp_cpt_source_idx;
1514 match_count = 1;
1515 max_matches_found = FALSE;
1516 }
1517 else if (cpt_sources_array && !max_matches_found)
1518 {
1519 int max_matches = cpt_sources_array[cur_source].max_matches;
1520 if (max_matches > 0 && match_count > max_matches)
1521 max_matches_found = TRUE;
1522 }
1523 }
1524
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001525 if (!match_at_original_text(compl)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001526 && !max_matches_found
John Marriott5e6ea922024-11-23 14:01:57 +01001527 && (compl_leader.string == NULL
1528 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001529 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001530 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001531 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001532 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001533 if (match_head == NULL)
1534 match_head = compl;
1535 else
glepnira49c0772024-11-30 10:56:30 +01001536 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001537 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001538
glepnirf400a0c2025-01-23 19:55:14 +01001539 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001540 {
1541 if (compl == compl_shown_match || did_find_shown_match)
1542 {
1543 // This item is the shown match or this is the
1544 // first displayed item after the shown match.
1545 compl_shown_match = compl;
1546 did_find_shown_match = TRUE;
1547 shown_match_ok = TRUE;
1548 }
1549 else
1550 // Remember this displayed match for when the
1551 // shown match is just below it.
1552 shown_compl = compl;
1553 cur = i;
1554 }
glepnirf400a0c2025-01-23 19:55:14 +01001555 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001556 {
1557 if (i == 0)
1558 shown_compl = compl;
1559 // Update the maximum fuzzy score and the shown match
1560 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001561 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1562 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001563 {
1564 did_find_shown_match = TRUE;
1565 max_fuzzy_score = compl->cp_score;
1566 if (!compl_no_select)
1567 compl_shown_match = compl;
1568 }
1569
glepnir3af0a8d2025-02-20 22:06:16 +01001570 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001571 {
1572 cur = i;
1573 shown_match_ok = TRUE;
1574 }
1575 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02001576 if (is_forward && compl->cp_cpt_source_idx != -1)
1577 match_count++;
glepnira49c0772024-11-30 10:56:30 +01001578 i++;
glepnir80b66202024-11-27 21:53:53 +01001579 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001580
glepnirf400a0c2025-01-23 19:55:14 +01001581 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001582 {
1583 did_find_shown_match = TRUE;
1584
1585 // When the original text is the shown match don't set
1586 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001587 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001588 shown_match_ok = TRUE;
1589
1590 if (!shown_match_ok && shown_compl != NULL)
1591 {
1592 // The shown match isn't displayed, set it to the
1593 // previously displayed match.
1594 compl_shown_match = shown_compl;
1595 shown_match_ok = TRUE;
1596 }
1597 }
glepnira49c0772024-11-30 10:56:30 +01001598 compl = compl->cp_next;
1599 } while (compl != NULL && !is_first_match(compl));
1600
1601 if (compl_match_arraysize == 0)
1602 return -1;
1603
glepnirc0b7ca42025-02-13 20:27:44 +01001604 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1605 {
1606 compl_shown_match = shown_compl;
1607 shown_match_ok = TRUE;
1608 cur = 0;
1609 }
1610
glepnira49c0772024-11-30 10:56:30 +01001611 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1612 if (compl_match_array == NULL)
1613 return -1;
1614
1615 compl = match_head;
1616 i = 0;
1617 while (compl != NULL)
1618 {
glepnir6e199932024-12-14 21:13:27 +01001619 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1620 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001621 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1622 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1623 compl_match_array[i].pum_score = compl->cp_score;
1624 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1625 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001626 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1627 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001628 match_next = compl->cp_match_next;
1629 compl->cp_match_next = NULL;
1630 compl = match_next;
1631 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001632
zeertzjqd65aa1b2025-01-25 15:29:03 +01001633 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001634 {
1635 for (i = 0; i < compl_match_arraysize; i++)
1636 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001637 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001638 qsort(compl_match_array, (size_t)compl_match_arraysize,
1639 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001640 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001641 }
glepnira218cc62024-06-03 19:32:39 +02001642
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001643 if (!shown_match_ok) // no displayed match at all
1644 cur = -1;
1645
1646 return cur;
1647}
1648
1649/*
1650 * Show the popup menu for the list of matches.
1651 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1652 */
1653 void
1654ins_compl_show_pum(void)
1655{
1656 int i;
1657 int cur = -1;
1658 colnr_T col;
1659
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001660 if (!pum_wanted() || !pum_enough_matches())
1661 return;
1662
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001663 // Update the screen later, before drawing the popup menu over it.
1664 pum_call_update_screen();
1665
1666 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001667 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001668 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001669 else
1670 {
1671 // popup menu already exists, only need to find the current item.
1672 for (i = 0; i < compl_match_arraysize; ++i)
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 }
1680 }
1681
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001682 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001683 {
1684#ifdef FEAT_EVAL
1685 if (compl_started && has_completechanged())
1686 trigger_complete_changed_event(cur);
1687#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001688 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001689 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001690
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001691 // In Replace mode when a $ is displayed at the end of the line only
1692 // part of the screen would be updated. We do need to redraw here.
1693 dollar_vcol = -1;
1694
1695 // Compute the screen column of the start of the completed text.
1696 // Use the cursor to get all wrapping and other settings right.
1697 col = curwin->w_cursor.col;
1698 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001699 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001700 pum_display(compl_match_array, compl_match_arraysize, cur);
1701 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001702
glepnircbb46b42024-02-03 18:11:13 +01001703 // After adding leader, set the current match to shown match.
1704 if (compl_started && compl_curr_match != compl_shown_match)
1705 compl_curr_match = compl_shown_match;
1706
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001707#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001708 if (has_completechanged())
1709 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001710#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001711}
1712
1713#define DICT_FIRST (1) // use just first element in "dict"
1714#define DICT_EXACT (2) // "dict" is the exact name of a file
1715
1716/*
glepnir40c1c332024-06-11 19:37:04 +02001717 * Get current completion leader
1718 */
1719 char_u *
1720ins_compl_leader(void)
1721{
John Marriott5e6ea922024-11-23 14:01:57 +01001722 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1723}
1724
1725/*
1726 * Get current completion leader length
1727 */
1728 size_t
1729ins_compl_leader_len(void)
1730{
1731 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001732}
1733
1734/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001735 * Add any identifiers that match the given pattern "pat" in the list of
1736 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001737 */
1738 static void
1739ins_compl_dictionaries(
1740 char_u *dict_start,
1741 char_u *pat,
1742 int flags, // DICT_FIRST and/or DICT_EXACT
1743 int thesaurus) // Thesaurus completion
1744{
1745 char_u *dict = dict_start;
1746 char_u *ptr;
1747 char_u *buf;
1748 regmatch_T regmatch;
1749 char_u **files;
1750 int count;
1751 int save_p_scs;
1752 int dir = compl_direction;
1753
1754 if (*dict == NUL)
1755 {
1756#ifdef FEAT_SPELL
1757 // When 'dictionary' is empty and spell checking is enabled use
1758 // "spell".
1759 if (!thesaurus && curwin->w_p_spell)
1760 dict = (char_u *)"spell";
1761 else
1762#endif
1763 return;
1764 }
1765
1766 buf = alloc(LSIZE);
1767 if (buf == NULL)
1768 return;
1769 regmatch.regprog = NULL; // so that we can goto theend
1770
1771 // If 'infercase' is set, don't use 'smartcase' here
1772 save_p_scs = p_scs;
1773 if (curbuf->b_p_inf)
1774 p_scs = FALSE;
1775
1776 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1777 // to only match at the start of a line. Otherwise just match the
1778 // pattern. Also need to double backslashes.
1779 if (ctrl_x_mode_line_or_eval())
1780 {
1781 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1782 size_t len;
1783
1784 if (pat_esc == NULL)
1785 goto theend;
1786 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(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001868 char_u *fname,
1869 char_u **buf_arg,
1870 int dir,
1871 char_u *skip_word)
1872{
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)
2032 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2033 ptr += (*mb_ptr2len)(ptr);
2034 else
2035 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2036 ++ptr;
2037 return ptr;
2038}
2039
2040/*
2041 * Find the end of the word. Assumes it starts inside a word.
2042 * Returns a pointer to just after the word.
2043 */
2044 char_u *
2045find_word_end(char_u *ptr)
2046{
2047 int start_class;
2048
2049 if (has_mbyte)
2050 {
2051 start_class = mb_get_class(ptr);
2052 if (start_class > 1)
2053 while (*ptr != NUL)
2054 {
2055 ptr += (*mb_ptr2len)(ptr);
2056 if (mb_get_class(ptr) != start_class)
2057 break;
2058 }
2059 }
2060 else
2061 while (vim_iswordc(*ptr))
2062 ++ptr;
2063 return ptr;
2064}
2065
2066/*
2067 * Find the end of the line, omitting CR and NL at the end.
2068 * Returns a pointer to just after the line.
2069 */
glepnirdd42b052025-03-08 16:52:55 +01002070 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002071find_line_end(char_u *ptr)
2072{
2073 char_u *s;
2074
2075 s = ptr + STRLEN(ptr);
2076 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{
2087 int i;
2088
2089 VIM_CLEAR_STRING(match->cp_str);
2090 // several entries may use the same fname, free it just once.
2091 if (match->cp_flags & CP_FREE_FNAME)
2092 vim_free(match->cp_fname);
2093 for (i = 0; i < CPT_COUNT; ++i)
2094 vim_free(match->cp_text[i]);
2095#ifdef FEAT_EVAL
2096 clear_tv(&match->cp_user_data);
2097#endif
2098 vim_free(match);
2099}
2100
2101/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002102 * Free the list of completions
2103 */
2104 static void
2105ins_compl_free(void)
2106{
2107 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002108
John Marriott5e6ea922024-11-23 14:01:57 +01002109 VIM_CLEAR_STRING(compl_pattern);
2110 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002111
2112 if (compl_first_match == NULL)
2113 return;
2114
2115 ins_compl_del_pum();
2116 pum_clear();
2117
2118 compl_curr_match = compl_first_match;
2119 do
2120 {
2121 match = compl_curr_match;
2122 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002123 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002124 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002125 compl_first_match = compl_curr_match = NULL;
2126 compl_shown_match = NULL;
2127 compl_old_match = NULL;
2128}
2129
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002130/*
2131 * Reset/clear the completion state.
2132 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133 void
2134ins_compl_clear(void)
2135{
2136 compl_cont_status = 0;
2137 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002138 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002139 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002140 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002141 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002142 compl_curr_win = NULL;
2143 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002144 VIM_CLEAR_STRING(compl_pattern);
2145 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002146 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002147 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002148 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002149 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002150#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002151 // clear v:completed_item
2152 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002153#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002154}
2155
2156/*
2157 * Return TRUE when Insert completion is active.
2158 */
2159 int
2160ins_compl_active(void)
2161{
2162 return compl_started;
2163}
2164
2165/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002166 * Return True when wp is the actual completion window
2167 */
2168 int
glepnircf7f0122025-04-15 19:02:00 +02002169ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002170{
glepnircf7f0122025-04-15 19:02:00 +02002171 return ins_compl_active() && wp == compl_curr_win
2172 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002173}
2174
2175/*
Girish Palyacbe53192025-04-14 22:13:15 +02002176 * Selected one of the matches. When FALSE, the match was either edited or
2177 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002178 */
2179 int
2180ins_compl_used_match(void)
2181{
2182 return compl_used_match;
2183}
2184
2185/*
2186 * Initialize get longest common string.
2187 */
2188 void
2189ins_compl_init_get_longest(void)
2190{
2191 compl_get_longest = FALSE;
2192}
2193
2194/*
2195 * Returns TRUE when insert completion is interrupted.
2196 */
2197 int
2198ins_compl_interrupted(void)
2199{
2200 return compl_interrupted;
2201}
2202
2203/*
2204 * Returns TRUE if the <Enter> key selects a match in the completion popup
2205 * menu.
2206 */
2207 int
2208ins_compl_enter_selects(void)
2209{
2210 return compl_enter_selects;
2211}
2212
2213/*
2214 * Return the column where the text starts that is being completed
2215 */
2216 colnr_T
2217ins_compl_col(void)
2218{
2219 return compl_col;
2220}
2221
2222/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002223 * Return the length in bytes of the text being completed
2224 */
2225 int
2226ins_compl_len(void)
2227{
2228 return compl_length;
2229}
2230
2231/*
glepnir94a045e2025-03-01 16:12:23 +01002232 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2233 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002234 */
2235 static int
2236ins_compl_has_preinsert(void)
2237{
glepnira2c55592025-02-28 17:43:42 +01002238 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002239 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2240 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002241}
2242
2243/*
2244 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2245 * the `compl_ins_end_col` range.
2246 */
2247 int
2248ins_compl_preinsert_effect(void)
2249{
2250 if (!ins_compl_has_preinsert())
2251 return FALSE;
2252
2253 return curwin->w_cursor.col < compl_ins_end_col;
2254}
2255
2256/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002257 * Delete one character before the cursor and show the subset of the matches
2258 * that match the word that is now before the cursor.
2259 * Returns the character to be used, NUL if the work is done and another char
2260 * to be got from the user.
2261 */
2262 int
2263ins_compl_bs(void)
2264{
2265 char_u *line;
2266 char_u *p;
2267
glepniredd4ac32025-01-29 18:53:51 +01002268 if (ins_compl_preinsert_effect())
2269 ins_compl_delete();
2270
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002271 line = ml_get_curline();
2272 p = line + curwin->w_cursor.col;
2273 MB_PTR_BACK(line, p);
2274
2275 // Stop completion when the whole word was deleted. For Omni completion
2276 // allow the word to be deleted, we won't match everything.
2277 // Respect the 'backspace' option.
2278 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002279 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2280 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002281 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2282 - compl_length < 0))
2283 return K_BS;
2284
2285 // Deleted more than what was used to find matches or didn't finish
2286 // finding all matches: need to look for matches all over again.
2287 if (curwin->w_cursor.col <= compl_col + compl_length
2288 || ins_compl_need_restart())
2289 ins_compl_restart();
2290
John Marriott5e6ea922024-11-23 14:01:57 +01002291 VIM_CLEAR_STRING(compl_leader);
2292 compl_leader.length = (size_t)((p - line) - compl_col);
2293 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2294 if (compl_leader.string == NULL)
2295 {
2296 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002297 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002298 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002299
2300 ins_compl_new_leader();
2301 if (compl_shown_match != NULL)
2302 // Make sure current match is not a hidden item.
2303 compl_curr_match = compl_shown_match;
2304 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002305}
2306
2307/*
2308 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2309 * be called.
2310 */
2311 static int
2312ins_compl_need_restart(void)
2313{
2314 // Return TRUE if we didn't complete finding matches or when the
2315 // 'completefunc' returned "always" in the "refresh" dictionary item.
2316 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002317 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002318 && compl_opt_refresh_always);
2319}
2320
2321/*
2322 * Called after changing "compl_leader".
2323 * Show the popup menu with a different set of matches.
2324 * May also search for matches again if the previous search was interrupted.
2325 */
2326 static void
2327ins_compl_new_leader(void)
2328{
2329 ins_compl_del_pum();
2330 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002331 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002332 compl_used_match = FALSE;
2333
2334 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002335 {
John Marriott5e6ea922024-11-23 14:01:57 +01002336 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002337 if (is_cpt_func_refresh_always())
2338 cpt_compl_refresh();
2339 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002340 else
2341 {
2342#ifdef FEAT_SPELL
2343 spell_bad_len = 0; // need to redetect bad word
2344#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002345 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002346 // the popup menu display the changed text before the cursor. Set
2347 // "compl_restarting" to avoid that the first match is inserted.
2348 pum_call_update_screen();
2349#ifdef FEAT_GUI
2350 if (gui.in_use)
2351 {
2352 // Show the cursor after the match, not after the redrawn text.
2353 setcursor();
2354 out_flush_cursor(FALSE, FALSE);
2355 }
2356#endif
2357 compl_restarting = TRUE;
2358 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2359 compl_cont_status = 0;
2360 compl_restarting = FALSE;
2361 }
2362
glepnir44180412025-02-20 22:09:48 +01002363 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002364
2365 // Show the popup menu with a different set of matches.
2366 ins_compl_show_pum();
2367
2368 // Don't let Enter select the original text when there is no popup menu.
2369 if (compl_match_array == NULL)
2370 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002371 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2372 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002373}
2374
2375/*
2376 * Return the length of the completion, from the completion start column to
2377 * the cursor column. Making sure it never goes below zero.
2378 */
2379 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002380get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002381{
2382 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002383 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002384}
2385
2386/*
2387 * Append one character to the match leader. May reduce the number of
2388 * matches.
2389 */
2390 void
2391ins_compl_addleader(int c)
2392{
2393 int cc;
2394
glepniredd4ac32025-01-29 18:53:51 +01002395 if (ins_compl_preinsert_effect())
2396 ins_compl_delete();
2397
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002398 if (stop_arrow() == FAIL)
2399 return;
2400 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2401 {
2402 char_u buf[MB_MAXBYTES + 1];
2403
2404 (*mb_char2bytes)(c, buf);
2405 buf[cc] = NUL;
2406 ins_char_bytes(buf, cc);
2407 if (compl_opt_refresh_always)
2408 AppendToRedobuff(buf);
2409 }
2410 else
2411 {
2412 ins_char(c);
2413 if (compl_opt_refresh_always)
2414 AppendCharToRedobuff(c);
2415 }
2416
2417 // If we didn't complete finding matches we must search again.
2418 if (ins_compl_need_restart())
2419 ins_compl_restart();
2420
2421 // When 'always' is set, don't reset compl_leader. While completing,
2422 // cursor doesn't point original position, changing compl_leader would
2423 // break redo.
2424 if (!compl_opt_refresh_always)
2425 {
John Marriott5e6ea922024-11-23 14:01:57 +01002426 VIM_CLEAR_STRING(compl_leader);
2427 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2428 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2429 compl_leader.length);
2430 if (compl_leader.string == NULL)
2431 {
2432 compl_leader.length = 0;
2433 return;
2434 }
2435
2436 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002437 }
2438}
2439
2440/*
2441 * Setup for finding completions again without leaving CTRL-X mode. Used when
2442 * BS or a key was typed while still searching for matches.
2443 */
2444 static void
2445ins_compl_restart(void)
2446{
2447 ins_compl_free();
2448 compl_started = FALSE;
2449 compl_matches = 0;
2450 compl_cont_status = 0;
2451 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002452 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002453}
2454
2455/*
2456 * Set the first match, the original text.
2457 */
2458 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002459ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002460{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002461 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002462 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2463 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002464 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002465 {
John Marriott5e6ea922024-11-23 14:01:57 +01002466 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002467 if (p != NULL)
2468 {
John Marriott5e6ea922024-11-23 14:01:57 +01002469 VIM_CLEAR_STRING(compl_first_match->cp_str);
2470 compl_first_match->cp_str.string = p;
2471 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002472 }
2473 }
2474 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002475 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002476 {
John Marriott5e6ea922024-11-23 14:01:57 +01002477 char_u *p = vim_strnsave(str, len);
2478 if (p != NULL)
2479 {
2480 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2481 compl_first_match->cp_prev->cp_str.string = p;
2482 compl_first_match->cp_prev->cp_str.length = len;
2483 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002484 }
2485}
2486
2487/*
2488 * Append one character to the match leader. May reduce the number of
2489 * matches.
2490 */
2491 void
2492ins_compl_addfrommatch(void)
2493{
2494 char_u *p;
2495 int len = (int)curwin->w_cursor.col - (int)compl_col;
2496 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002497
John Marriott5e6ea922024-11-23 14:01:57 +01002498 p = compl_shown_match->cp_str.string;
2499 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002500 {
John Marriott5e6ea922024-11-23 14:01:57 +01002501 size_t plen;
2502 compl_T *cp;
2503
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002504 // When still at the original match use the first entry that matches
2505 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002506 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002507 return;
2508
2509 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002510 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002511 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002512 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002513 {
John Marriott5e6ea922024-11-23 14:01:57 +01002514 if (compl_leader.string == NULL
2515 || ins_compl_equal(cp, compl_leader.string,
2516 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002517 {
John Marriott5e6ea922024-11-23 14:01:57 +01002518 p = cp->cp_str.string;
2519 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002520 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002521 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002522 }
John Marriott5e6ea922024-11-23 14:01:57 +01002523 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002524 return;
2525 }
2526 p += len;
2527 c = PTR2CHAR(p);
2528 ins_compl_addleader(c);
2529}
2530
2531/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002532 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002533 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2534 * compl_cont_mode and compl_cont_status.
2535 * Returns TRUE when the character is not to be inserted.
2536 */
2537 static int
2538set_ctrl_x_mode(int c)
2539{
2540 int retval = FALSE;
2541
2542 switch (c)
2543 {
2544 case Ctrl_E:
2545 case Ctrl_Y:
2546 // scroll the window one line up or down
2547 ctrl_x_mode = CTRL_X_SCROLL;
2548 if (!(State & REPLACE_FLAG))
2549 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2550 else
2551 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2552 edit_submode_pre = NULL;
2553 showmode();
2554 break;
2555 case Ctrl_L:
2556 // complete whole line
2557 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2558 break;
2559 case Ctrl_F:
2560 // complete filenames
2561 ctrl_x_mode = CTRL_X_FILES;
2562 break;
2563 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002564 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002565 ctrl_x_mode = CTRL_X_DICTIONARY;
2566 break;
2567 case Ctrl_R:
2568 // Register insertion without exiting CTRL-X mode
2569 // Simply allow ^R to happen without affecting ^X mode
2570 break;
2571 case Ctrl_T:
2572 // complete words from a thesaurus
2573 ctrl_x_mode = CTRL_X_THESAURUS;
2574 break;
2575#ifdef FEAT_COMPL_FUNC
2576 case Ctrl_U:
2577 // user defined completion
2578 ctrl_x_mode = CTRL_X_FUNCTION;
2579 break;
2580 case Ctrl_O:
2581 // omni completion
2582 ctrl_x_mode = CTRL_X_OMNI;
2583 break;
2584#endif
2585 case 's':
2586 case Ctrl_S:
2587 // complete spelling suggestions
2588 ctrl_x_mode = CTRL_X_SPELL;
2589#ifdef FEAT_SPELL
2590 ++emsg_off; // Avoid getting the E756 error twice.
2591 spell_back_to_badword();
2592 --emsg_off;
2593#endif
2594 break;
2595 case Ctrl_RSB:
2596 // complete tag names
2597 ctrl_x_mode = CTRL_X_TAGS;
2598 break;
2599#ifdef FEAT_FIND_ID
2600 case Ctrl_I:
2601 case K_S_TAB:
2602 // complete keywords from included files
2603 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2604 break;
2605 case Ctrl_D:
2606 // complete definitions from included files
2607 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2608 break;
2609#endif
2610 case Ctrl_V:
2611 case Ctrl_Q:
2612 // complete vim commands
2613 ctrl_x_mode = CTRL_X_CMDLINE;
2614 break;
2615 case Ctrl_Z:
2616 // stop completion
2617 ctrl_x_mode = CTRL_X_NORMAL;
2618 edit_submode = NULL;
2619 showmode();
2620 retval = TRUE;
2621 break;
2622 case Ctrl_P:
2623 case Ctrl_N:
2624 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2625 // just started ^X mode, or there were enough ^X's to cancel
2626 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2627 // do normal expansion when interrupting a different mode (say
2628 // ^X^F^X^P or ^P^X^X^P, see below)
2629 // nothing changes if interrupting mode 0, (eg, the flag
2630 // doesn't change when going to ADDING mode -- Acevedo
2631 if (!(compl_cont_status & CONT_INTRPT))
2632 compl_cont_status |= CONT_LOCAL;
2633 else if (compl_cont_mode != 0)
2634 compl_cont_status &= ~CONT_LOCAL;
2635 // FALLTHROUGH
2636 default:
2637 // If we have typed at least 2 ^X's... for modes != 0, we set
2638 // compl_cont_status = 0 (eg, as if we had just started ^X
2639 // mode).
2640 // For mode 0, we set "compl_cont_mode" to an impossible
2641 // value, in both cases ^X^X can be used to restart the same
2642 // mode (avoiding ADDING mode).
2643 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2644 // 'complete' and local ^P expansions respectively.
2645 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2646 // mode -- Acevedo
2647 if (c == Ctrl_X)
2648 {
2649 if (compl_cont_mode != 0)
2650 compl_cont_status = 0;
2651 else
2652 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2653 }
2654 ctrl_x_mode = CTRL_X_NORMAL;
2655 edit_submode = NULL;
2656 showmode();
2657 break;
2658 }
2659
2660 return retval;
2661}
2662
2663/*
glepnir1c5a1202024-12-04 20:27:34 +01002664 * Trigger CompleteDone event and adds relevant information to v:event
2665 */
2666 static void
2667trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2668{
2669#if defined(FEAT_EVAL)
2670 save_v_event_T save_v_event;
2671 dict_T *v_event = get_v_event(&save_v_event);
2672 char_u *mode_str = NULL;
2673
2674 mode = mode & ~CTRL_X_WANT_IDENT;
2675 if (ctrl_x_mode_names[mode])
2676 mode_str = (char_u *)ctrl_x_mode_names[mode];
2677
2678 (void)dict_add_string(v_event, "complete_word",
2679 word == NULL ? (char_u *)"" : word);
2680 (void)dict_add_string(v_event, "complete_type",
2681 mode_str != NULL ? mode_str : (char_u *)"");
2682
2683 dict_set_items_ro(v_event);
2684#endif
2685 ins_apply_autocmds(EVENT_COMPLETEDONE);
2686
2687#if defined(FEAT_EVAL)
2688 restore_v_event(v_event, &save_v_event);
2689#endif
2690}
2691
2692/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002693 * Stop insert completion mode
2694 */
2695 static int
2696ins_compl_stop(int c, int prev_mode, int retval)
2697{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002698 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002699 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002700
glepnir84a75032025-03-15 09:59:22 +01002701 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002702 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002703 ins_compl_delete();
2704
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002705 // Get here when we have finished typing a sequence of ^N and
2706 // ^P or other completion characters in CTRL-X mode. Free up
2707 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002708 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002709 {
glepnir40891ba2025-02-10 22:18:00 +01002710 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002711
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002712 // If any of the original typed text has been changed, eg when
2713 // ignorecase is set, we must add back-spaces to the redo
2714 // buffer. We add as few as necessary to delete just the part
2715 // of the original text that has changed.
2716 // When using the longest match, edited the match or used
2717 // CTRL-E then don't use the current match.
2718 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002719 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002720 ins_compl_fixRedoBufForLeader(ptr);
2721 }
2722
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002723 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002724
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002725 // When completing whole lines: fix indent for 'cindent'.
2726 // Otherwise, break line if it's too long.
2727 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2728 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002729 // re-indent the current line
2730 if (want_cindent)
2731 {
2732 do_c_expr_indent();
2733 want_cindent = FALSE; // don't do it again
2734 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002735 }
2736 else
2737 {
2738 int prev_col = curwin->w_cursor.col;
2739
2740 // put the cursor on the last char, for 'tw' formatting
2741 if (prev_col > 0)
2742 dec_cursor();
2743 // only format when something was inserted
2744 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2745 insertchar(NUL, 0, -1);
2746 if (prev_col > 0
2747 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2748 inc_cursor();
2749 }
2750
2751 // If the popup menu is displayed pressing CTRL-Y means accepting
2752 // the selection without inserting anything. When
2753 // compl_enter_selects is set the Enter key does the same.
2754 if ((c == Ctrl_Y || (compl_enter_selects
2755 && (c == CAR || c == K_KENTER || c == NL)))
2756 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002757 {
2758 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002759 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002760 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002761
2762 // CTRL-E means completion is Ended, go back to the typed text.
2763 // but only do this, if the Popup is still visible
2764 if (c == Ctrl_E)
2765 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002766 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002767 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002768
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002769 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002770 if (compl_leader.string != NULL)
2771 {
2772 p = compl_leader.string;
2773 plen = compl_leader.length;
2774 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002775 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002776 {
2777 p = compl_orig_text.string;
2778 plen = compl_orig_text.length;
2779 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002780 if (p != NULL)
2781 {
2782 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002783
John Marriott5e6ea922024-11-23 14:01:57 +01002784 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002785 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002786 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002787 retval = TRUE;
2788 }
2789
2790 auto_format(FALSE, TRUE);
2791
2792 // Trigger the CompleteDonePre event to give scripts a chance to
2793 // act upon the completion before clearing the info, and restore
2794 // ctrl_x_mode, so that complete_info() can be used.
2795 ctrl_x_mode = prev_mode;
2796 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2797
2798 ins_compl_free();
2799 compl_started = FALSE;
2800 compl_matches = 0;
2801 if (!shortmess(SHM_COMPLETIONMENU))
2802 msg_clr_cmdline(); // necessary for "noshowmode"
2803 ctrl_x_mode = CTRL_X_NORMAL;
2804 compl_enter_selects = FALSE;
2805 if (edit_submode != NULL)
2806 {
2807 edit_submode = NULL;
2808 showmode();
2809 }
2810
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002811 if (c == Ctrl_C && cmdwin_type != 0)
2812 // Avoid the popup menu remains displayed when leaving the
2813 // command line window.
2814 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002815 // Indent now if a key was typed that is in 'cinkeys'.
2816 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2817 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002818 // Trigger the CompleteDone event to give scripts a chance to act
2819 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002820 trigger_complete_done_event(prev_mode, word);
2821 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002822
2823 return retval;
2824}
2825
2826/*
glepnircf7f0122025-04-15 19:02:00 +02002827 * Cancel completion.
2828 */
2829 int
2830ins_compl_cancel(void)
2831{
2832 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2833}
2834
2835/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002836 * Prepare for Insert mode completion, or stop it.
2837 * Called just after typing a character in Insert mode.
2838 * Returns TRUE when the character is not to be inserted;
2839 */
2840 int
2841ins_compl_prep(int c)
2842{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002843 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002844 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002845
2846 // Forget any previous 'special' messages if this is actually
2847 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2848 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2849 edit_submode_extra = NULL;
2850
zeertzjq440d4cb2023-03-02 17:51:32 +00002851 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002852 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002853 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002854 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002855 return retval;
2856
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002857#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002858 // Ignore mouse events in a popup window
2859 if (is_mouse_key(c))
2860 {
2861 // Ignore drag and release events, the position does not need to be in
2862 // the popup and it may have just closed.
2863 if (c == K_LEFTRELEASE
2864 || c == K_LEFTRELEASE_NM
2865 || c == K_MIDDLERELEASE
2866 || c == K_RIGHTRELEASE
2867 || c == K_X1RELEASE
2868 || c == K_X2RELEASE
2869 || c == K_LEFTDRAG
2870 || c == K_MIDDLEDRAG
2871 || c == K_RIGHTDRAG
2872 || c == K_X1DRAG
2873 || c == K_X2DRAG)
2874 return retval;
2875 if (popup_visible)
2876 {
2877 int row = mouse_row;
2878 int col = mouse_col;
2879 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2880
2881 if (wp != NULL && WIN_IS_POPUP(wp))
2882 return retval;
2883 }
2884 }
2885#endif
2886
zeertzjqdca29d92021-08-31 19:12:51 +02002887 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2888 {
2889 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2890 || !vim_is_ctrl_x_key(c))
2891 {
2892 // Not starting another completion mode.
2893 ctrl_x_mode = CTRL_X_CMDLINE;
2894
2895 // CTRL-X CTRL-Z should stop completion without inserting anything
2896 if (c == Ctrl_Z)
2897 retval = TRUE;
2898 }
2899 else
2900 {
2901 ctrl_x_mode = CTRL_X_CMDLINE;
2902
2903 // Other CTRL-X keys first stop completion, then start another
2904 // completion mode.
2905 ins_compl_prep(' ');
2906 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2907 }
2908 }
2909
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002910 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002911 if (ctrl_x_mode_not_defined_yet()
2912 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002913 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002914 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002915 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002916 }
2917
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002918 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002919 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2920 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002921 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002922 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002923 {
2924 // We're already in CTRL-X mode, do we stay in it?
2925 if (!vim_is_ctrl_x_key(c))
2926 {
glepnir40891ba2025-02-10 22:18:00 +01002927 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002928 edit_submode = NULL;
2929 }
2930 showmode();
2931 }
2932
2933 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2934 {
2935 // Show error message from attempted keyword completion (probably
2936 // 'Pattern not found') until another key is hit, then go back to
2937 // showing what mode we are in.
2938 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002939 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002940 && c != Ctrl_R && !ins_compl_pum_key(c))
2941 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002942 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002943 }
2944 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2945 // Trigger the CompleteDone event to give scripts a chance to act
2946 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002947 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002948
LemonBoy2bf52dd2022-04-09 18:17:34 +01002949 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002950
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002951 // reset continue_* if we left expansion-mode, if we stay they'll be
2952 // (re)set properly in ins_complete()
2953 if (!vim_is_ctrl_x_key(c))
2954 {
2955 compl_cont_status = 0;
2956 compl_cont_mode = 0;
2957 }
2958
2959 return retval;
2960}
2961
2962/*
2963 * Fix the redo buffer for the completion leader replacing some of the typed
2964 * text. This inserts backspaces and appends the changed text.
2965 * "ptr" is the known leader text or NUL.
2966 */
2967 static void
2968ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2969{
John Marriott5e6ea922024-11-23 14:01:57 +01002970 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002971 char_u *p;
2972 char_u *ptr = ptr_arg;
2973
2974 if (ptr == NULL)
2975 {
John Marriott5e6ea922024-11-23 14:01:57 +01002976 if (compl_leader.string != NULL)
2977 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002978 else
2979 return; // nothing to do
2980 }
John Marriott5e6ea922024-11-23 14:01:57 +01002981 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002982 {
John Marriott5e6ea922024-11-23 14:01:57 +01002983 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002984 // Find length of common prefix between original text and new completion
2985 while (p[len] != NUL && p[len] == ptr[len])
2986 len++;
2987 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002988 if (len > 0)
2989 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002990 // Add backspace characters for each remaining character in
2991 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002992 for (p += len; *p != NUL; MB_PTR_ADV(p))
2993 AppendCharToRedobuff(K_BS);
2994 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002995 if (ptr != NULL)
2996 AppendToRedobuffLit(ptr + len, -1);
2997}
2998
2999/*
3000 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3001 * (depending on flag) starting from buf and looking for a non-scanned
3002 * buffer (other than curbuf). curbuf is special, if it is called with
3003 * buf=curbuf then it has to be the first call for a given flag/expansion.
3004 *
3005 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3006 */
3007 static buf_T *
3008ins_compl_next_buf(buf_T *buf, int flag)
3009{
3010 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01003011 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003012
3013 if (flag == 'w') // just windows
3014 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003015 if (buf == curbuf || !win_valid(wp))
3016 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003017 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003018
3019 while (TRUE)
3020 {
3021 // Move to next window (wrap to first window if at the end)
3022 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3023 // Break if we're back at start or found an unscanned buffer
3024 if (wp == curwin || !wp->w_buffer->b_scanned)
3025 break;
3026 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003027 buf = wp->w_buffer;
3028 }
3029 else
glepnir40891ba2025-02-10 22:18:00 +01003030 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003031 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3032 // (unlisted buffers)
3033 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003034 while (TRUE)
3035 {
3036 // Move to next buffer (wrap to first buffer if at the end)
3037 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3038 // Break if we're back at start buffer
3039 if (buf == curbuf)
3040 break;
3041
3042 // Check buffer conditions based on flag
3043 if (flag == 'U')
3044 skip_buffer = buf->b_p_bl;
3045 else
3046 skip_buffer = !buf->b_p_bl ||
3047 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3048
3049 // Break if we found a buffer that matches our criteria
3050 if (!skip_buffer && !buf->b_scanned)
3051 break;
3052 }
3053 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003054 return buf;
3055}
3056
3057#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003058
3059# ifdef FEAT_EVAL
3060static callback_T cfu_cb; // 'completefunc' callback function
3061static callback_T ofu_cb; // 'omnifunc' callback function
3062static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3063# endif
3064
3065/*
3066 * Copy a global callback function to a buffer local callback.
3067 */
3068 static void
3069copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3070{
3071 free_callback(bufcb);
3072 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3073 copy_callback(bufcb, globcb);
3074}
3075
3076/*
3077 * Parse the 'completefunc' option value and set the callback function.
3078 * Invoked when the 'completefunc' option is set. The option value can be a
3079 * name of a function (string), or function(<name>) or funcref(<name>) or a
3080 * lambda expression.
3081 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003082 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003083did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003084{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003085 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3086 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003087
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003088 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003089
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003090 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003091}
3092
3093/*
3094 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003095 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003096 */
3097 void
3098set_buflocal_cfu_callback(buf_T *buf UNUSED)
3099{
3100# ifdef FEAT_EVAL
3101 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3102# endif
3103}
3104
3105/*
3106 * Parse the 'omnifunc' option value and set the callback function.
3107 * Invoked when the 'omnifunc' option is set. The option value can be a
3108 * name of a function (string), or function(<name>) or funcref(<name>) or a
3109 * lambda expression.
3110 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003111 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003112did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003113{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003114 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3115 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003116
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003117 set_buflocal_ofu_callback(curbuf);
3118 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003119}
3120
3121/*
3122 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003123 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003124 */
3125 void
3126set_buflocal_ofu_callback(buf_T *buf UNUSED)
3127{
3128# ifdef FEAT_EVAL
3129 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3130# endif
3131}
3132
3133/*
3134 * Parse the 'thesaurusfunc' option value and set the callback function.
3135 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3136 * name of a function (string), or function(<name>) or funcref(<name>) or a
3137 * lambda expression.
3138 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003139 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003140did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003141{
3142 int retval;
3143
zeertzjq6eda2692024-11-03 09:23:33 +01003144 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003145 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003146 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3147 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003148 else
3149 {
3150 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003151 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003152 // when using :set, free the local callback
3153 if (!(args->os_flags & OPT_GLOBAL))
3154 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003155 }
3156
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003157 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003158}
3159
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003160/*
3161 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003162 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003163 */
3164 int
3165set_ref_in_insexpand_funcs(int copyID)
3166{
3167 int abort = FALSE;
3168
3169 abort = set_ref_in_callback(&cfu_cb, copyID);
3170 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3171 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3172
3173 return abort;
3174}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003175
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003176/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003177 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003178 */
3179 static char_u *
3180get_complete_funcname(int type)
3181{
3182 switch (type)
3183 {
3184 case CTRL_X_FUNCTION:
3185 return curbuf->b_p_cfu;
3186 case CTRL_X_OMNI:
3187 return curbuf->b_p_ofu;
3188 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003189 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003190 default:
3191 return (char_u *)"";
3192 }
3193}
3194
3195/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003196 * Get the callback to use for insert mode completion.
3197 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003198 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003199get_insert_callback(int type)
3200{
3201 if (type == CTRL_X_FUNCTION)
3202 return &curbuf->b_cfu_cb;
3203 if (type == CTRL_X_OMNI)
3204 return &curbuf->b_ofu_cb;
3205 // CTRL_X_THESAURUS
3206 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3207}
3208
3209/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003210 * Execute user defined complete function 'completefunc', 'omnifunc' or
3211 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003212 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3213 * Callback function "cb" is set if triggered by a function in the 'cpt'
3214 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003215 */
3216 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003217expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003218{
3219 list_T *matchlist = NULL;
3220 dict_T *matchdict = NULL;
3221 typval_T args[3];
3222 char_u *funcname;
3223 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003224 typval_T rettv;
3225 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003226 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003227 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003228
Girish Palyacbe53192025-04-14 22:13:15 +02003229 if (!is_cpt_function)
3230 {
3231 funcname = get_complete_funcname(type);
3232 if (*funcname == NUL)
3233 return;
3234 cb = get_insert_callback(type);
3235 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003236
3237 // Call 'completefunc' to obtain the list of matches.
3238 args[0].v_type = VAR_NUMBER;
3239 args[0].vval.v_number = 0;
3240 args[1].v_type = VAR_STRING;
3241 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3242 args[2].v_type = VAR_UNKNOWN;
3243
3244 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003245 // Lock the text to avoid weird things from happening. Also disallow
3246 // switching to another window, it should not be needed and may end up in
3247 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003248 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003249
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003250 retval = call_callback(cb, 0, &rettv, 2, args);
3251
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003252 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003253 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003254 {
3255 switch (rettv.v_type)
3256 {
3257 case VAR_LIST:
3258 matchlist = rettv.vval.v_list;
3259 break;
3260 case VAR_DICT:
3261 matchdict = rettv.vval.v_dict;
3262 break;
3263 case VAR_SPECIAL:
3264 if (rettv.vval.v_number == VVAL_NONE)
3265 compl_opt_suppress_empty = TRUE;
3266 // FALLTHROUGH
3267 default:
3268 // TODO: Give error message?
3269 clear_tv(&rettv);
3270 break;
3271 }
3272 }
zeertzjqcfe45652022-05-27 17:26:55 +01003273 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003274
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003275 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003276 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003277 validate_cursor();
3278 if (!EQUAL_POS(curwin->w_cursor, pos))
3279 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003280 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003281 goto theend;
3282 }
3283
3284 if (matchlist != NULL)
3285 ins_compl_add_list(matchlist);
3286 else if (matchdict != NULL)
3287 ins_compl_add_dict(matchdict);
3288
3289theend:
3290 // Restore State, it might have been changed.
3291 State = save_State;
3292
3293 if (matchdict != NULL)
3294 dict_unref(matchdict);
3295 if (matchlist != NULL)
3296 list_unref(matchlist);
3297}
3298#endif // FEAT_COMPL_FUNC
3299
3300#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003301
3302 static inline int
3303get_user_highlight_attr(char_u *hlname)
3304{
3305 if (hlname != NULL && *hlname != NUL)
3306 return syn_name2attr(hlname);
3307 return -1;
3308}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003309/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003310 * Add a match to the list of matches from a typeval_T.
3311 * If the given string is already in the list of completions, then return
3312 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3313 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003314 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003315 */
3316 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003317ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003318{
3319 char_u *word;
3320 int dup = FALSE;
3321 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003322 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003323 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003324 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003325 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003326 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003327 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003328 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003329
Bram Moolenaar08928322020-01-04 14:32:48 +01003330 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003331 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3332 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003333 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3334 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3335 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3336 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3337 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003338
glepnir0fe17f82024-10-08 22:26:44 +02003339 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003340 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003341
3342 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003343 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003344
Bram Moolenaard61efa52022-07-23 09:52:04 +01003345 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3346 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3347 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003348 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003349 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3350 dup = dict_get_number(tv->vval.v_dict, "dup");
3351 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3352 empty = dict_get_number(tv->vval.v_dict, "empty");
3353 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3354 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003355 flags |= CP_EQUAL;
3356 }
3357 else
3358 {
3359 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003360 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003361 }
3362 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003363 {
3364 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003365 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003366 }
glepnir508e7852024-07-25 21:39:08 +02003367 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003368 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003369 if (status != OK)
3370 clear_tv(&user_data);
3371 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003372}
3373
3374/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003375 * Add completions from a list.
3376 */
3377 static void
3378ins_compl_add_list(list_T *list)
3379{
3380 listitem_T *li;
3381 int dir = compl_direction;
3382
3383 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003384 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003385 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003386 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003387 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003388 // if dir was BACKWARD then honor it just once
3389 dir = FORWARD;
3390 else if (did_emsg)
3391 break;
3392 }
3393}
3394
3395/*
3396 * Add completions from a dict.
3397 */
3398 static void
3399ins_compl_add_dict(dict_T *dict)
3400{
3401 dictitem_T *di_refresh;
3402 dictitem_T *di_words;
3403
3404 // Check for optional "refresh" item.
3405 compl_opt_refresh_always = FALSE;
3406 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3407 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3408 {
3409 char_u *v = di_refresh->di_tv.vval.v_string;
3410
3411 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3412 compl_opt_refresh_always = TRUE;
3413 }
3414
3415 // Add completions from a "words" list.
3416 di_words = dict_find(dict, (char_u *)"words", 5);
3417 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3418 ins_compl_add_list(di_words->di_tv.vval.v_list);
3419}
3420
3421/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003422 * Start completion for the complete() function.
3423 * "startcol" is where the matched text starts (1 is first column).
3424 * "list" is the list of matches.
3425 */
3426 static void
3427set_completion(colnr_T startcol, list_T *list)
3428{
3429 int save_w_wrow = curwin->w_wrow;
3430 int save_w_leftcol = curwin->w_leftcol;
3431 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003432 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003433 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3434 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3435 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003436
3437 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003438 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003439 ins_compl_prep(' ');
3440 ins_compl_clear();
3441 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003442 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003443
3444 compl_direction = FORWARD;
3445 if (startcol > curwin->w_cursor.col)
3446 startcol = curwin->w_cursor.col;
3447 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003448 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003449 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3450 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003451 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3452 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003453 if (p_ic)
3454 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003455 if (compl_orig_text.string == NULL)
3456 {
3457 compl_orig_text.length = 0;
3458 return;
3459 }
3460 compl_orig_text.length = (size_t)compl_length;
3461 if (ins_compl_add(compl_orig_text.string,
3462 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
glepnirf31cfa22025-03-06 21:59:13 +01003463 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003464 return;
3465
3466 ctrl_x_mode = CTRL_X_EVAL;
3467
3468 ins_compl_add_list(list);
3469 compl_matches = ins_compl_make_cyclic();
3470 compl_started = TRUE;
3471 compl_used_match = TRUE;
3472 compl_cont_status = 0;
3473
3474 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003475 int no_select = compl_no_select || compl_longest;
3476 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003477 {
3478 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003479 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003480 // Down/Up has no real effect.
3481 ins_complete(K_UP, FALSE);
3482 }
3483 else
3484 ins_complete(Ctrl_N, FALSE);
3485 compl_enter_selects = compl_no_insert;
3486
3487 // Lazily show the popup menu, unless we got interrupted.
3488 if (!compl_interrupted)
3489 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003490 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003491 out_flush();
3492}
3493
3494/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003495 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003496 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003497 void
3498f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003499{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003500 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003501
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003502 if (in_vim9script()
3503 && (check_for_number_arg(argvars, 0) == FAIL
3504 || check_for_list_arg(argvars, 1) == FAIL))
3505 return;
3506
Bram Moolenaar24959102022-05-07 20:01:16 +01003507 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003508 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003509 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003510 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003511 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003512
3513 // Check for undo allowed here, because if something was already inserted
3514 // the line was already saved for undo and this check isn't done.
3515 if (!undo_allowed())
3516 return;
3517
Bram Moolenaard83392a2022-09-01 12:22:46 +01003518 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003519 {
3520 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3521 if (startcol > 0)
3522 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003523 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003524}
3525
3526/*
3527 * "complete_add()" function
3528 */
3529 void
3530f_complete_add(typval_T *argvars, typval_T *rettv)
3531{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003532 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003533 return;
3534
Bram Moolenaar440cf092021-04-03 20:13:30 +02003535 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003536}
3537
3538/*
3539 * "complete_check()" function
3540 */
3541 void
3542f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3543{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003544 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003545 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003546
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003547 ins_compl_check_keys(0, TRUE);
3548 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003549
3550 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003551}
3552
3553/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003554 * Return Insert completion mode name string
3555 */
3556 static char_u *
3557ins_compl_mode(void)
3558{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003559 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003560 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3561
3562 return (char_u *)"";
3563}
3564
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003565/*
3566 * Assign the sequence number to all the completion matches which don't have
3567 * one assigned yet.
3568 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003569 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003570ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003571{
3572 int number = 0;
3573 compl_T *match;
3574
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003575 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003576 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003577 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003578 // This should normally succeed already at the first loop
3579 // cycle, so it's fast!
3580 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003581 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003582 if (match->cp_number != -1)
3583 {
3584 number = match->cp_number;
3585 break;
3586 }
3587 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003588 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003589 for (match = match->cp_next;
3590 match != NULL && match->cp_number == -1;
3591 match = match->cp_next)
3592 match->cp_number = ++number;
3593 }
3594 else // BACKWARD
3595 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003596 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003597 // number. This should normally succeed already at the
3598 // first loop cycle, so it's fast!
3599 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003600 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003601 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003602 if (match->cp_number != -1)
3603 {
3604 number = match->cp_number;
3605 break;
3606 }
glepnir40891ba2025-02-10 22:18:00 +01003607 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003608 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003609 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003610 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003611 for (match = match->cp_prev; match
3612 && match->cp_number == -1;
3613 match = match->cp_prev)
3614 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003615 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003616 }
3617}
3618
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003619/*
glepnir037b0282025-01-16 14:37:44 +01003620 * Fill the dict of complete_info
3621 */
3622 static void
3623fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3624{
3625 dict_add_string(di, "word", match->cp_str.string);
3626 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3627 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3628 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3629 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3630 if (add_match)
3631 dict_add_bool(di, "match", match->cp_in_match_array);
3632 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3633 // Add an empty string for backwards compatibility
3634 dict_add_string(di, "user_data", (char_u *)"");
3635 else
3636 dict_add_tv(di, "user_data", &match->cp_user_data);
3637}
3638
3639/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003640 * Get complete information
3641 */
3642 static void
3643get_complete_info(list_T *what_list, dict_T *retdict)
3644{
3645 int ret = OK;
3646 listitem_T *item;
3647#define CI_WHAT_MODE 0x01
3648#define CI_WHAT_PUM_VISIBLE 0x02
3649#define CI_WHAT_ITEMS 0x04
3650#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003651#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003652#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003653#define CI_WHAT_ALL 0xff
3654 int what_flag;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003655 int compl_fuzzy_match = (get_cot_flags() & COT_FUZZY) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003656
3657 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003658 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003659 else
3660 {
3661 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003662 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003663 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003664 {
3665 char_u *what = tv_get_string(&item->li_tv);
3666
3667 if (STRCMP(what, "mode") == 0)
3668 what_flag |= CI_WHAT_MODE;
3669 else if (STRCMP(what, "pum_visible") == 0)
3670 what_flag |= CI_WHAT_PUM_VISIBLE;
3671 else if (STRCMP(what, "items") == 0)
3672 what_flag |= CI_WHAT_ITEMS;
3673 else if (STRCMP(what, "selected") == 0)
3674 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003675 else if (STRCMP(what, "completed") == 0)
3676 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003677 else if (STRCMP(what, "matches") == 0)
3678 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003679 }
3680 }
3681
3682 if (ret == OK && (what_flag & CI_WHAT_MODE))
3683 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3684
3685 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3686 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3687
glepnir037b0282025-01-16 14:37:44 +01003688 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3689 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003690 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003691 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003692 dict_T *di;
3693 compl_T *match;
3694 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003695 int has_items = what_flag & CI_WHAT_ITEMS;
3696 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003697 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003698
glepnird4088ed2024-12-31 10:55:22 +01003699 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003700 {
3701 li = list_alloc();
3702 if (li == NULL)
3703 return;
glepnird4088ed2024-12-31 10:55:22 +01003704 ret = dict_add_list(retdict, (has_matches && !has_items)
3705 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003706 }
3707 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3708 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3709 ins_compl_update_sequence_numbers();
3710 if (ret == OK && compl_first_match != NULL)
3711 {
3712 int list_idx = 0;
3713 match = compl_first_match;
3714 do
3715 {
3716 if (!match_at_original_text(match))
3717 {
glepnird4088ed2024-12-31 10:55:22 +01003718 if (has_items
3719 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003720 {
3721 di = dict_alloc();
3722 if (di == NULL)
3723 return;
3724 ret = list_append_dict(li, di);
3725 if (ret != OK)
3726 return;
glepnir037b0282025-01-16 14:37:44 +01003727 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003728 }
glepnird4088ed2024-12-31 10:55:22 +01003729 if (compl_curr_match != NULL
3730 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003731 selected_idx = list_idx;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003732 if (compl_fuzzy_match || match->cp_in_match_array)
3733 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003734 }
3735 match = match->cp_next;
3736 }
3737 while (match != NULL && !is_first_match(match));
3738 }
3739 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3740 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003741
glepnir037b0282025-01-16 14:37:44 +01003742 if (ret == OK && selected_idx != -1 && has_completed)
3743 {
3744 di = dict_alloc();
3745 if (di == NULL)
3746 return;
3747 fill_complete_info_dict(di, compl_curr_match, FALSE);
3748 ret = dict_add_dict(retdict, "completed", di);
3749 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003750 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003751}
3752
3753/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003754 * "complete_info()" function
3755 */
3756 void
3757f_complete_info(typval_T *argvars, typval_T *rettv)
3758{
3759 list_T *what_list = NULL;
3760
Bram Moolenaar93a10962022-06-16 11:42:09 +01003761 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003762 return;
3763
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003764 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3765 return;
3766
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003767 if (argvars[0].v_type != VAR_UNKNOWN)
3768 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003769 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003770 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003771 what_list = argvars[0].vval.v_list;
3772 }
3773 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003774}
3775#endif
3776
3777/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003778 * Returns TRUE when using a user-defined function for thesaurus completion.
3779 */
3780 static int
3781thesaurus_func_complete(int type UNUSED)
3782{
3783#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003784 return type == CTRL_X_THESAURUS
3785 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003786#else
3787 return FALSE;
3788#endif
3789}
3790
3791/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003792 * Return value of process_next_cpt_value()
3793 */
3794enum
3795{
3796 INS_COMPL_CPT_OK = 1,
3797 INS_COMPL_CPT_CONT,
3798 INS_COMPL_CPT_END
3799};
3800
3801/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003802 * state information used for getting the next set of insert completion
3803 * matches.
3804 */
3805typedef struct
3806{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003807 char_u *e_cpt_copy; // copy of 'complete'
3808 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003809 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003810 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003811 pos_T prev_match_pos; // previous match position
3812 int set_match_pos; // save first_match_pos/last_match_pos
3813 pos_T first_match_pos; // first match position
3814 pos_T last_match_pos; // last match position
3815 int found_all; // found all matches of a certain type.
3816 char_u *dict; // dictionary file to search
3817 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003818 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003819} ins_compl_next_state_T;
3820
3821/*
3822 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003823 *
3824 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003825 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003826 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003827 * st->found_all - all matches of this type are found
3828 * st->ins_buf - search for completions in this buffer
3829 * st->first_match_pos - position of the first completion match
3830 * st->last_match_pos - position of the last completion match
3831 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003832 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003833 * st->dict - name of the dictionary or thesaurus file to search
3834 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003835 *
3836 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003837 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3838 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003839 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003840 */
3841 static int
3842process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003843 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003844 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003845 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003846 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003847{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003848 int compl_type = -1;
3849 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003850
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003851 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003852
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003853 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3854 st->e_cpt++;
3855
3856 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003857 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003858 st->ins_buf = curbuf;
3859 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003860 // Move the cursor back one character so that ^N can match the
3861 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003862 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003863 {
3864 // Move the cursor to after the last character in the
3865 // buffer, so that word at start of buffer is found
3866 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003867 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003868 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003869 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003870 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003871 compl_type = 0;
3872
3873 // Remember the first match so that the loop stops when we
3874 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003875 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003876 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003877 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003878 && (st->ins_buf = ins_compl_next_buf(
3879 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003880 {
3881 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003882 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003883 {
3884 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003885 st->first_match_pos.col = st->last_match_pos.col = 0;
3886 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3887 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003888 compl_type = 0;
3889 }
3890 else // unloaded buffer, scan like dictionary
3891 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003892 st->found_all = TRUE;
3893 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003894 {
3895 status = INS_COMPL_CPT_CONT;
3896 goto done;
3897 }
3898 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003899 st->dict = st->ins_buf->b_fname;
3900 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003901 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003902 if (!shortmess(SHM_COMPLETIONSCAN))
3903 {
3904 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3905 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3906 st->ins_buf->b_fname == NULL
3907 ? buf_spname(st->ins_buf)
3908 : st->ins_buf->b_sfname == NULL
3909 ? st->ins_buf->b_fname
3910 : st->ins_buf->b_sfname);
3911 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3912 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003913 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003914 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003915 status = INS_COMPL_CPT_END;
3916 else
3917 {
3918 if (ctrl_x_mode_line_or_eval())
3919 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003920 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003921 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003922 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003923 compl_type = CTRL_X_DICTIONARY;
3924 else
3925 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003926 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003927 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003928 st->dict = st->e_cpt;
3929 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003930 }
3931 }
Girish Palyacbe53192025-04-14 22:13:15 +02003932#ifdef FEAT_COMPL_FUNC
3933 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
3934 {
3935 compl_type = CTRL_X_FUNCTION;
3936 if (*st->e_cpt == 'o')
3937 st->func_cb = &curbuf->b_ofu_cb;
3938 else
3939 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
3940 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
3941 if (!st->func_cb)
3942 compl_type = -1;
3943 }
3944#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003945#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003946 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003947 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003948 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003949 compl_type = CTRL_X_PATH_DEFINES;
3950#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003951 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003952 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003953 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003954 if (!shortmess(SHM_COMPLETIONSCAN))
3955 {
3956 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3957 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3958 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3959 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003960 }
3961 else
3962 compl_type = -1;
3963
3964 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003965 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003966
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003967 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003968 if (compl_type == -1)
3969 status = INS_COMPL_CPT_CONT;
3970 }
3971
3972done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003973 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003974 return status;
3975}
3976
3977#ifdef FEAT_FIND_ID
3978/*
3979 * Get the next set of identifiers or defines matching "compl_pattern" in
3980 * included files.
3981 */
3982 static void
3983get_next_include_file_completion(int compl_type)
3984{
John Marriott5e6ea922024-11-23 14:01:57 +01003985 find_pattern_in_path(compl_pattern.string, compl_direction,
3986 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003987 (compl_type == CTRL_X_PATH_DEFINES
3988 && !(compl_cont_status & CONT_SOL))
3989 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003990 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003991}
3992#endif
3993
3994/*
3995 * Get the next set of words matching "compl_pattern" in dictionary or
3996 * thesaurus files.
3997 */
3998 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003999get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004000{
4001#ifdef FEAT_COMPL_FUNC
4002 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004003 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004004 else
4005#endif
4006 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004007 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004008 : (compl_type == CTRL_X_THESAURUS
4009 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4010 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004011 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004012 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004013 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004014}
4015
4016/*
4017 * Get the next set of tag names matching "compl_pattern".
4018 */
4019 static void
4020get_next_tag_completion(void)
4021{
4022 int save_p_ic;
4023 char_u **matches;
4024 int num_matches;
4025
4026 // set p_ic according to p_ic, p_scs and pat for find_tags().
4027 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004028 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004029
4030 // Find up to TAG_MANY matches. Avoids that an enormous number
4031 // of matches is found when compl_pattern is empty
4032 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004033 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004034 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004035 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004036 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4037 ins_compl_add_matches(num_matches, matches, p_ic);
4038 g_tag_at_cursor = FALSE;
4039 p_ic = save_p_ic;
4040}
4041
4042/*
glepnir8159fb12024-07-17 20:32:54 +02004043 * Compare function for qsort
4044 */
glepnirf31cfa22025-03-06 21:59:13 +01004045 static int
4046compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004047{
4048 int idx_a = *(const int *)a;
4049 int idx_b = *(const int *)b;
4050 int score_a = compl_fuzzy_scores[idx_a];
4051 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004052 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4053 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004054}
4055
4056/*
glepnirf31cfa22025-03-06 21:59:13 +01004057 * insert prefix with redraw
4058 */
4059 static void
4060ins_compl_longest_insert(char_u *prefix)
4061{
4062 ins_compl_delete();
4063 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4064 ins_redraw(FALSE);
4065}
4066
4067/*
4068 * Calculate the longest common prefix among the best fuzzy matches
4069 * stored in compl_best_matches, and insert it as the longest.
4070 */
4071 static void
4072fuzzy_longest_match(void)
4073{
4074 char_u *prefix = NULL;
4075 int prefix_len = 0;
4076 int i = 0;
4077 int j = 0;
4078 char_u *match_str = NULL;
4079 char_u *prefix_ptr = NULL;
4080 char_u *match_ptr = NULL;
4081 char_u *leader = NULL;
4082 size_t leader_len = 0;
4083 compl_T *compl = NULL;
4084 int more_candidates = FALSE;
4085 compl_T *nn_compl = NULL;
4086
4087 if (compl_num_bests == 0)
4088 return;
4089
4090 nn_compl = compl_first_match->cp_next->cp_next;
4091 if (nn_compl && nn_compl != compl_first_match)
4092 more_candidates = TRUE;
4093
4094 compl = ctrl_x_mode_whole_line() ? compl_first_match
4095 : compl_first_match->cp_next;
4096 if (compl_num_bests == 1)
4097 {
4098 // no more candidates insert the match str
4099 if (!more_candidates)
4100 {
4101 ins_compl_longest_insert(compl->cp_str.string);
4102 compl_num_bests = 0;
4103 }
4104 compl_num_bests = 0;
4105 return;
4106 }
4107
4108 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4109 if (compl_best_matches == NULL)
4110 return;
4111 while (compl != NULL && i < compl_num_bests)
4112 {
4113 compl_best_matches[i] = compl;
4114 compl = compl->cp_next;
4115 i++;
4116 }
4117
4118 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004119 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004120
4121 for (i = 1; i < compl_num_bests; i++)
4122 {
4123 match_str = compl_best_matches[i]->cp_str.string;
4124 prefix_ptr = prefix;
4125 match_ptr = match_str;
4126 j = 0;
4127
4128 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4129 {
4130 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4131 break;
4132
4133 MB_PTR_ADV(prefix_ptr);
4134 MB_PTR_ADV(match_ptr);
4135 j++;
4136 }
4137
4138 if (j > 0)
4139 prefix_len = j;
4140 }
4141
4142 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004143 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004144
4145 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004146 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004147 goto end;
4148
zeertzjq4422de62025-03-07 19:06:02 +01004149 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004150 if (prefix != NULL)
4151 {
4152 ins_compl_longest_insert(prefix);
4153 compl_cfc_longest_ins = TRUE;
4154 vim_free(prefix);
4155 }
4156
4157end:
4158 vim_free(compl_best_matches);
4159 compl_best_matches = NULL;
4160 compl_num_bests = 0;
4161}
4162
4163/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004164 * Get the next set of filename matching "compl_pattern".
4165 */
4166 static void
4167get_next_filename_completion(void)
4168{
4169 char_u **matches;
4170 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004171 char_u *ptr;
4172 garray_T fuzzy_indices;
4173 int i;
4174 int score;
4175 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004176 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004177 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004178 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004179 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004180 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4181 int max_score = 0;
4182 int current_score = 0;
4183 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004184
glepnirb9de1a02024-08-02 19:14:38 +02004185#ifdef BACKSLASH_IN_FILENAME
4186 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4187 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4188#else
4189 char pathsep = PATHSEP;
4190#endif
4191
glepnirf31cfa22025-03-06 21:59:13 +01004192 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004193 {
glepnirb9de1a02024-08-02 19:14:38 +02004194#ifdef BACKSLASH_IN_FILENAME
4195 if (curbuf->b_p_csl[0] == 's')
4196 {
John Marriott5e6ea922024-11-23 14:01:57 +01004197 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004198 {
4199 if (leader[i] == '\\')
4200 leader[i] = '/';
4201 }
4202 }
4203 else if (curbuf->b_p_csl[0] == 'b')
4204 {
John Marriott5e6ea922024-11-23 14:01:57 +01004205 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004206 {
4207 if (leader[i] == '/')
4208 leader[i] = '\\';
4209 }
4210 }
4211#endif
4212 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004213 if (last_sep == NULL)
4214 {
4215 // No path separator or separator is the last character,
4216 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004217 VIM_CLEAR_STRING(compl_pattern);
4218 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4219 if (compl_pattern.string == NULL)
4220 return;
4221 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004222 }
4223 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004224 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004225 else
4226 {
4227 // Split leader into path and file parts
4228 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004229 char_u *path_with_wildcard;
4230
4231 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004232 if (path_with_wildcard != NULL)
4233 {
John Marriott5e6ea922024-11-23 14:01:57 +01004234 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4235 VIM_CLEAR_STRING(compl_pattern);
4236 compl_pattern.string = path_with_wildcard;
4237 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004238
4239 // Move leader to the file part
4240 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004241 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004242 }
4243 }
glepnir8159fb12024-07-17 20:32:54 +02004244 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004245
John Marriott5e6ea922024-11-23 14:01:57 +01004246 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004247 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4248 return;
4249
4250 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004251 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004252#ifdef BACKSLASH_IN_FILENAME
4253 if (curbuf->b_p_csl[0] != NUL)
4254 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004255 for (i = 0; i < num_matches; ++i)
4256 {
glepnir8159fb12024-07-17 20:32:54 +02004257 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004258 while (*ptr != NUL)
4259 {
4260 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4261 *ptr = '/';
4262 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4263 *ptr = '\\';
4264 ptr += (*mb_ptr2len)(ptr);
4265 }
4266 }
4267 }
4268#endif
glepnir8159fb12024-07-17 20:32:54 +02004269
glepnirf31cfa22025-03-06 21:59:13 +01004270 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004271 {
4272 ga_init2(&fuzzy_indices, sizeof(int), 10);
4273 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4274
4275 for (i = 0; i < num_matches; i++)
4276 {
4277 ptr = matches[i];
4278 score = fuzzy_match_str(ptr, leader);
4279 if (score > 0)
4280 {
4281 if (ga_grow(&fuzzy_indices, 1) == OK)
4282 {
4283 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4284 compl_fuzzy_scores[i] = score;
4285 fuzzy_indices.ga_len++;
4286 }
4287 }
4288 }
4289
Christian Brabandt220474d2024-07-20 13:26:44 +02004290 // prevent qsort from deref NULL pointer
4291 if (fuzzy_indices.ga_len > 0)
4292 {
glepnirf31cfa22025-03-06 21:59:13 +01004293 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004294 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4295 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004296
Christian Brabandt220474d2024-07-20 13:26:44 +02004297 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004298 {
4299 match = matches[fuzzy_indices_data[i]];
4300 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4301 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
4302 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4303 FALSE, NULL, current_score) == OK)
4304 dir = FORWARD;
4305
4306 if (need_collect_bests)
4307 {
4308 if (i == 0 || current_score == max_score)
4309 {
4310 compl_num_bests++;
4311 max_score = current_score;
4312 }
4313 }
4314 }
glepnir8159fb12024-07-17 20:32:54 +02004315
Christian Brabandt220474d2024-07-20 13:26:44 +02004316 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004317 }
glepnir6b6280c2024-07-27 16:25:45 +02004318 else if (leader_len > 0)
4319 {
4320 FreeWild(num_matches, matches);
4321 num_matches = 0;
4322 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004323
glepnir8159fb12024-07-17 20:32:54 +02004324 vim_free(compl_fuzzy_scores);
4325 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004326
4327 if (compl_num_bests > 0 && compl_get_longest)
4328 fuzzy_longest_match();
4329 return;
glepnir8159fb12024-07-17 20:32:54 +02004330 }
4331
glepnir6b6280c2024-07-27 16:25:45 +02004332 if (num_matches > 0)
4333 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004334}
4335
4336/*
4337 * Get the next set of command-line completions matching "compl_pattern".
4338 */
4339 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004340get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004341{
4342 char_u **matches;
4343 int num_matches;
4344
John Marriott5e6ea922024-11-23 14:01:57 +01004345 if (expand_cmdline(&compl_xp, compl_pattern.string,
4346 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004347 ins_compl_add_matches(num_matches, matches, FALSE);
4348}
4349
4350/*
4351 * Get the next set of spell suggestions matching "compl_pattern".
4352 */
4353 static void
4354get_next_spell_completion(linenr_T lnum UNUSED)
4355{
4356#ifdef FEAT_SPELL
4357 char_u **matches;
4358 int num_matches;
4359
John Marriott5e6ea922024-11-23 14:01:57 +01004360 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004361 if (num_matches > 0)
4362 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004363 else
4364 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004365#endif
4366}
4367
4368/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004369 * Return the next word or line from buffer "ins_buf" at position
4370 * "cur_match_pos" for completion. The length of the match is set in "len".
4371 */
4372 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004373ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004374 buf_T *ins_buf, // buffer being scanned
4375 pos_T *cur_match_pos, // current match position
4376 int *match_len,
4377 int *cont_s_ipos) // next ^X<> will set initial_pos
4378{
4379 char_u *ptr;
4380 int len;
4381
4382 *match_len = 0;
4383 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4384 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004385 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004386 if (ctrl_x_mode_line_or_eval())
4387 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004388 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004389 {
4390 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4391 return NULL;
4392 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004393 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004394 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004395 {
4396 char_u *tmp_ptr = ptr;
4397
4398 ptr = skipwhite(tmp_ptr);
4399 len -= (int)(ptr - tmp_ptr);
4400 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004401 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004402 }
4403 else
4404 {
4405 char_u *tmp_ptr = ptr;
4406
John Marriott5e6ea922024-11-23 14:01:57 +01004407 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004408 {
4409 tmp_ptr += compl_length;
4410 // Skip if already inside a word.
4411 if (vim_iswordp(tmp_ptr))
4412 return NULL;
4413 // Find start of next word.
4414 tmp_ptr = find_word_start(tmp_ptr);
4415 }
4416 // Find end of this word.
4417 tmp_ptr = find_word_end(tmp_ptr);
4418 len = (int)(tmp_ptr - ptr);
4419
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004420 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004421 {
4422 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4423 {
4424 // Try next line, if any. the new word will be
4425 // "join" as if the normal command "J" was used.
4426 // IOSIZE is always greater than
4427 // compl_length, so the next STRNCPY always
4428 // works -- Acevedo
4429 STRNCPY(IObuff, ptr, len);
4430 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4431 tmp_ptr = ptr = skipwhite(ptr);
4432 // Find start of next word.
4433 tmp_ptr = find_word_start(tmp_ptr);
4434 // Find end of next word.
4435 tmp_ptr = find_word_end(tmp_ptr);
4436 if (tmp_ptr > ptr)
4437 {
4438 if (*ptr != ')' && IObuff[len - 1] != TAB)
4439 {
4440 if (IObuff[len - 1] != ' ')
4441 IObuff[len++] = ' ';
4442 // IObuf =~ "\k.* ", thus len >= 2
4443 if (p_js
4444 && (IObuff[len - 2] == '.'
4445 || (vim_strchr(p_cpo, CPO_JOINSP)
4446 == NULL
4447 && (IObuff[len - 2] == '?'
4448 || IObuff[len - 2] == '!'))))
4449 IObuff[len++] = ' ';
4450 }
4451 // copy as much as possible of the new word
4452 if (tmp_ptr - ptr >= IOSIZE - len)
4453 tmp_ptr = ptr + IOSIZE - len - 1;
4454 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4455 len += (int)(tmp_ptr - ptr);
4456 *cont_s_ipos = TRUE;
4457 }
4458 IObuff[len] = NUL;
4459 ptr = IObuff;
4460 }
4461 if (len == compl_length)
4462 return NULL;
4463 }
4464 }
4465
4466 *match_len = len;
4467 return ptr;
4468}
4469
4470/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004471 * Get the next set of words matching "compl_pattern" for default completion(s)
4472 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004473 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4474 * position "st->start_pos" in the "compl_direction" direction. If
4475 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4476 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004477 * Returns OK if a new next match is found, otherwise returns FAIL.
4478 */
4479 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004480get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004481{
4482 int found_new_match = FAIL;
4483 int save_p_scs;
4484 int save_p_ws;
4485 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004486 char_u *ptr = NULL;
4487 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004488 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004489 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004490 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004491 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004492
4493 // If 'infercase' is set, don't use 'smartcase' here
4494 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004495 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004496 p_scs = FALSE;
4497
4498 // Buffers other than curbuf are scanned from the beginning or the
4499 // end but never from the middle, thus setting nowrapscan in this
4500 // buffer is a good idea, on the other hand, we always set
4501 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4502 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004503 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004504 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004505 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004506 p_ws = TRUE;
4507 looped_around = FALSE;
4508 for (;;)
4509 {
4510 int cont_s_ipos = FALSE;
4511
4512 ++msg_silent; // Don't want messages for wrapscan.
4513
glepnirf31cfa22025-03-06 21:59:13 +01004514 if (in_collect)
4515 {
glepnir8159fb12024-07-17 20:32:54 +02004516 found_new_match = search_for_fuzzy_match(st->ins_buf,
4517 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004518 start_pos, &len, &ptr, &score);
4519 }
4520 // ctrl_x_mode_line_or_eval() || word-wise search that
4521 // has added a word that was at the beginning of the line
4522 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4523 found_new_match = search_for_exact_line(st->ins_buf,
4524 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004525 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004526 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004527 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004528 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004529 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004530 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004531 {
4532 // set "compl_started" even on fail
4533 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004534 st->first_match_pos = *st->cur_match_pos;
4535 st->last_match_pos = *st->cur_match_pos;
4536 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004537 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004538 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4539 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004540 {
4541 found_new_match = FAIL;
4542 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004543 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004544 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4545 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4546 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004547 {
4548 if (looped_around)
4549 found_new_match = FAIL;
4550 else
4551 looped_around = TRUE;
4552 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004553 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004554 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4555 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4556 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004557 {
4558 if (looped_around)
4559 found_new_match = FAIL;
4560 else
4561 looped_around = TRUE;
4562 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004563 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004564 if (found_new_match == FAIL)
4565 break;
4566
4567 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004568 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004569 && start_pos->lnum == st->cur_match_pos->lnum
4570 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004571 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004572
glepnirf31cfa22025-03-06 21:59:13 +01004573 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004574 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4575 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004576 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004577 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004578
Girish Palyab1565882025-04-15 20:16:00 +02004579 if (is_nearest_active() && in_curbuf)
4580 {
4581 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4582 if (score < 0)
4583 score = -score;
4584 score++;
4585 }
4586
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004587 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004588 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004589 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004590 {
glepnirf31cfa22025-03-06 21:59:13 +01004591 if (in_collect && score == compl_first_match->cp_next->cp_score)
4592 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004593 found_new_match = OK;
4594 break;
4595 }
4596 }
4597 p_scs = save_p_scs;
4598 p_ws = save_p_ws;
4599
4600 return found_new_match;
4601}
4602
4603/*
Girish Palyacbe53192025-04-14 22:13:15 +02004604 * Return the callback function associated with "funcname".
4605 */
4606#ifdef FEAT_COMPL_FUNC
4607 static callback_T *
4608get_cpt_func_callback(char_u *funcname)
4609{
4610 static callback_T cb;
4611 char_u buf[LSIZE];
4612 int slen;
4613
4614 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4615 if (slen > 0 && option_set_callback_func(buf, &cb))
4616 return &cb;
4617 return NULL;
4618}
4619
4620/*
4621 * Retrieve new completion matches by invoking callback "cb".
4622 */
4623 static void
4624expand_cpt_function(callback_T *cb)
4625{
4626 // Re-insert the text removed by ins_compl_delete().
4627 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4628 // Get matches
4629 get_cpt_func_completion_matches(cb);
4630 // Undo insertion
4631 ins_compl_delete();
4632}
4633#endif
4634
4635/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004636 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004637 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004638 */
4639 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004640get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004641{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004642 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004643
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004644 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004645 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004646 case -1:
4647 break;
4648#ifdef FEAT_FIND_ID
4649 case CTRL_X_PATH_PATTERNS:
4650 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004651 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004652 break;
4653#endif
4654
4655 case CTRL_X_DICTIONARY:
4656 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004657 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4658 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004659 break;
4660
4661 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004662 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004663 break;
4664
4665 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004666 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004667 break;
4668
4669 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004670 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004671 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004672 break;
4673
4674#ifdef FEAT_COMPL_FUNC
4675 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004676 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4677 expand_cpt_function(st->func_cb);
4678 else
4679 expand_by_function(type, compl_pattern.string, NULL);
4680 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004681 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004682 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004683 break;
4684#endif
4685
4686 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004687 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004688 break;
4689
4690 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004691 found_new_match = get_next_default_completion(st, ini);
4692 if (found_new_match == FAIL && st->ins_buf == curbuf)
4693 st->found_all = TRUE;
4694 }
4695
4696 // check if compl_curr_match has changed, (e.g. other type of
4697 // expansion added something)
4698 if (type != 0 && compl_curr_match != compl_old_match)
4699 found_new_match = OK;
4700
4701 return found_new_match;
4702}
4703
4704/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02004705 * Strips carets followed by numbers. This suffix typically represents the
4706 * max_matches setting.
4707 */
4708 static void
4709strip_caret_numbers_in_place(char_u *str)
4710{
4711 char_u *read = str, *write = str, *p;
4712
4713 if (str == NULL)
4714 return;
4715
4716 while (*read)
4717 {
4718 if (*read == '^')
4719 {
4720 p = read + 1;
4721 while (vim_isdigit(*p))
4722 p++;
4723 if ((*p == ',' || *p == '\0') && p != read + 1)
4724 {
4725 read = p;
4726 continue;
4727 }
4728 else
4729 *write++ = *read++;
4730 }
4731 else
4732 *write++ = *read++;
4733 }
4734 *write = '\0';
4735}
4736
4737/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004738 * Get the next expansion(s), using "compl_pattern".
4739 * The search starts at position "ini" in curbuf and in the direction
4740 * compl_direction.
4741 * When "compl_started" is FALSE start at that position, otherwise continue
4742 * where we stopped searching before.
4743 * This may return before finding all the matches.
4744 * Return the total number of matches or -1 if still unknown -- Acevedo
4745 */
4746 static int
4747ins_compl_get_exp(pos_T *ini)
4748{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004749 static ins_compl_next_state_T st;
4750 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004751 int i;
4752 int found_new_match;
4753 int type = ctrl_x_mode;
4754
4755 if (!compl_started)
4756 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004757 buf_T *buf;
4758
4759 FOR_ALL_BUFFERS(buf)
4760 buf->b_scanned = 0;
4761 if (!st_cleared)
4762 {
4763 CLEAR_FIELD(st);
4764 st_cleared = TRUE;
4765 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004766 st.found_all = FALSE;
4767 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004768 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004769 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004770 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4771 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02004772 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004773 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004774 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004775
4776 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Girish Palya0ac1eb32025-04-16 20:18:33 +02004777 && !cpt_sources_init())
Girish Palyacbe53192025-04-14 22:13:15 +02004778 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004779 }
4780 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4781 st.ins_buf = curbuf; // In case the buffer was wiped out.
4782
4783 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004784 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004785 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004786
4787 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya0ac1eb32025-04-16 20:18:33 +02004788 for (cpt_sources_index = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004789 {
4790 found_new_match = FAIL;
4791 st.set_match_pos = FALSE;
4792
4793 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4794 // or if found_all says this entry is done. For ^X^L only use the
4795 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004796 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004797 && (!compl_started || st.found_all))
4798 {
glepnir53b14572025-03-12 21:28:39 +01004799 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004800
4801 if (status == INS_COMPL_CPT_END)
4802 break;
4803 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004804 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02004805 cpt_sources_index++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004806 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004807 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004808 }
4809
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004810 // If complete() was called then compl_pattern has been reset. The
4811 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004812 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004813 break;
4814
4815 // get the next set of completion matches
4816 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004817
Girish Palyacbe53192025-04-14 22:13:15 +02004818 if (type > 0)
Girish Palya0ac1eb32025-04-16 20:18:33 +02004819 cpt_sources_index++;
Girish Palyacbe53192025-04-14 22:13:15 +02004820
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004821 // break the loop for specialized modes (use 'complete' just for the
4822 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4823 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004824 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4825 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004826 {
4827 if (got_int)
4828 break;
4829 // Fill the popup menu as soon as possible.
4830 if (type != -1)
4831 ins_compl_check_keys(0, FALSE);
4832
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004833 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004834 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4835 break;
4836 compl_started = TRUE;
4837 }
4838 else
4839 {
4840 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004841 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004842 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004843
4844 compl_started = FALSE;
4845 }
4846 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02004847 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004848 compl_started = TRUE;
4849
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004850 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004851 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004852 found_new_match = FAIL;
4853
4854 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004855 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004856 && !ctrl_x_mode_line_or_eval()))
4857 i = ins_compl_make_cyclic();
4858
glepnirf31cfa22025-03-06 21:59:13 +01004859 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4860 fuzzy_longest_match();
4861
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004862 if (compl_old_match != NULL)
4863 {
4864 // If several matches were added (FORWARD) or the search failed and has
4865 // just been made cyclic then we have to move compl_curr_match to the
4866 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004867 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004868 : compl_old_match->cp_prev;
4869 if (compl_curr_match == NULL)
4870 compl_curr_match = compl_old_match;
4871 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004872 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004873
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004874 return i;
4875}
4876
4877/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004878 * Update "compl_shown_match" to the actually shown match, it may differ when
4879 * "compl_leader" is used to omit some of the matches.
4880 */
4881 static void
4882ins_compl_update_shown_match(void)
4883{
4884 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004885 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004886 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004887 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004888 compl_shown_match = compl_shown_match->cp_next;
4889
4890 // If we didn't find it searching forward, and compl_shows_dir is
4891 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004892 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004893 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004894 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004895 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004896 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004897 {
4898 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004899 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004900 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004901 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004902 compl_shown_match = compl_shown_match->cp_prev;
4903 }
4904}
4905
4906/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004907 * Delete the old text being completed.
4908 */
4909 void
4910ins_compl_delete(void)
4911{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004912 // In insert mode: Delete the typed part.
4913 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004914 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01004915 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01004916 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004917 int has_preinsert = ins_compl_preinsert_effect();
4918 if (has_preinsert)
4919 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02004920 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004921 curwin->w_cursor.col = compl_ins_end_col;
4922 }
4923
glepnir76bdb822025-02-08 19:04:51 +01004924 if (curwin->w_cursor.lnum > compl_lnum)
4925 {
4926 if (curwin->w_cursor.col < ml_get_curline_len())
4927 {
John Marriottf4b36412025-02-23 09:09:59 +01004928 char_u *line = ml_get_cursor();
4929 remaining.length = ml_get_cursor_len();
4930 remaining.string = vim_strnsave(line, remaining.length);
4931 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01004932 return;
4933 }
4934 while (curwin->w_cursor.lnum > compl_lnum)
4935 {
4936 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4937 {
John Marriottf4b36412025-02-23 09:09:59 +01004938 if (remaining.string)
4939 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004940 return;
4941 }
zeertzjq060e6552025-02-21 20:06:26 +01004942 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01004943 curwin->w_cursor.lnum--;
4944 }
4945 // move cursor to end of line
4946 curwin->w_cursor.col = ml_get_curline_len();
4947 }
4948
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004949 if ((int)curwin->w_cursor.col > col)
4950 {
4951 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004952 {
John Marriottf4b36412025-02-23 09:09:59 +01004953 if (remaining.string)
4954 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004955 return;
glepnire3647c82025-02-10 21:16:32 +01004956 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004957 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004958 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004959 }
4960
John Marriottf4b36412025-02-23 09:09:59 +01004961 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01004962 {
4963 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01004964 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01004965 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01004966 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004967 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004968 // TODO: is this sufficient for redrawing? Redrawing everything causes
4969 // flicker, thus we can't do that.
4970 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004971#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004972 // clear v:completed_item
4973 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004974#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004975}
4976
4977/*
glepnir76bdb822025-02-08 19:04:51 +01004978 * Insert a completion string that contains newlines.
4979 * The string is split and inserted line by line.
4980 */
4981 static void
4982ins_compl_expand_multiple(char_u *str)
4983{
4984 char_u *start = str;
4985 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01004986 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01004987
4988 while (*curr != NUL)
4989 {
4990 if (*curr == '\n')
4991 {
4992 // Insert the text chunk before newline
4993 if (curr > start)
4994 ins_char_bytes(start, (int)(curr - start));
4995
4996 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01004997 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01004998 start = curr + 1;
4999 }
5000 curr++;
5001 }
5002
5003 // Handle remaining text after last newline (if any)
5004 if (curr > start)
5005 ins_char_bytes(start, (int)(curr - start));
5006
5007 compl_ins_end_col = curwin->w_cursor.col;
5008}
5009
5010/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005011 * Insert the new text being completed.
5012 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005013 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5014 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005015 */
5016 void
glepniredd4ac32025-01-29 18:53:51 +01005017ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005018{
glepnir76bdb822025-02-08 19:04:51 +01005019 int compl_len = get_compl_len();
5020 int preinsert = ins_compl_has_preinsert();
5021 char_u *cp_str = compl_shown_match->cp_str.string;
5022 size_t cp_str_len = compl_shown_match->cp_str.length;
5023 size_t leader_len = ins_compl_leader_len();
5024 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005025
5026 // Make sure we don't go over the end of the string, this can happen with
5027 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005028 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005029 {
glepnir76bdb822025-02-08 19:04:51 +01005030 if (has_multiple)
5031 ins_compl_expand_multiple(cp_str + compl_len);
5032 else
5033 {
5034 ins_compl_insert_bytes(cp_str + compl_len, -1);
5035 if (preinsert && move_cursor)
5036 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5037 }
glepniredd4ac32025-01-29 18:53:51 +01005038 }
5039 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005040 compl_used_match = FALSE;
5041 else
5042 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005043#ifdef FEAT_EVAL
5044 {
5045 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5046
5047 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5048 }
5049#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005050 if (!in_compl_func)
5051 compl_curr_match = compl_shown_match;
5052}
5053
5054/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005055 * show the file name for the completion match (if any). Truncate the file
5056 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005057 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005058 static void
5059ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005060{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005061 char *lead = _("match in file");
5062 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5063 char_u *s;
5064 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005065
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005066 if (space <= 0)
5067 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005068
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005069 // We need the tail that fits. With double-byte encoding going
5070 // back from the end is very slow, thus go from the start and keep
5071 // the text that fits in "space" between "s" and "e".
5072 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005073 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005074 space -= ptr2cells(e);
5075 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005076 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005077 space += ptr2cells(s);
5078 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005079 }
5080 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005081 msg_hist_off = TRUE;
5082 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5083 s > compl_shown_match->cp_fname ? "<" : "", s);
5084 msg((char *)IObuff);
5085 msg_hist_off = FALSE;
5086 redraw_cmdline = FALSE; // don't overwrite!
5087}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005088
glepnirdca57fb2024-06-04 22:01:21 +02005089/*
zeertzjq551d8c32024-06-05 19:53:32 +02005090 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005091 */
glepnira218cc62024-06-03 19:32:39 +02005092 static compl_T *
5093find_comp_when_fuzzy(void)
5094{
5095 int score;
5096 char_u* str;
5097 int target_idx = -1;
5098 int is_forward = compl_shows_dir_forward();
5099 int is_backward = compl_shows_dir_backward();
5100 compl_T *comp = NULL;
5101
glepnir43eef882024-06-19 20:20:48 +02005102 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005103 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02005104 return compl_first_match != compl_shown_match ?
5105 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02005106 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02005107
5108 if (is_forward)
5109 target_idx = compl_selected_item + 1;
5110 else if (is_backward)
5111 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005112 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005113
5114 score = compl_match_array[target_idx].pum_score;
5115 str = compl_match_array[target_idx].pum_text;
5116
5117 comp = compl_first_match;
5118 do {
John Marriott5e6ea922024-11-23 14:01:57 +01005119 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02005120 return comp;
5121 comp = comp->cp_next;
5122 } while (comp != NULL && !is_first_match(comp));
5123
5124 return NULL;
5125}
5126
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005127/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005128 * Find the appropriate completion item when 'complete' ('cpt') includes
5129 * a 'max_matches' postfix. In this case, we search for a match where
5130 * 'cp_in_match_array' is set, indicating that the match is also present
5131 * in 'compl_match_array'.
5132 */
5133 static compl_T *
5134find_comp_when_cpt_sources(void)
5135{
5136 int is_forward = compl_shows_dir_forward();
5137 compl_T *match = compl_shown_match;
5138
5139 do
5140 match = is_forward ? match->cp_next : match->cp_prev;
5141 while (match->cp_next && !match->cp_in_match_array
5142 && !match_at_original_text(match));
5143 return match;
5144}
5145
5146/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005147 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005148 * times. The number of matches found is returned in 'num_matches'.
5149 *
5150 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5151 * get more completions. If it is FALSE, then do nothing when there are no more
5152 * completions in the given direction.
5153 *
5154 * If "advance" is TRUE, then completion will move to the first match.
5155 * Otherwise, the original text will be shown.
5156 *
5157 * Returns OK on success and -1 if the number of matches are unknown.
5158 */
5159 static int
5160find_next_completion_match(
5161 int allow_get_expansion,
5162 int todo, // repeat completion this many times
5163 int advance,
5164 int *num_matches)
5165{
5166 int found_end = FALSE;
5167 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005168 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005169 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5170 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005171 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005172
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005173 while (--todo >= 0)
5174 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005175 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005176 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02005177 if (compl_match_array != NULL && compl_fuzzy_match)
5178 compl_shown_match = find_comp_when_fuzzy();
5179 else if (cpt_sources_active)
5180 compl_shown_match = find_comp_when_cpt_sources();
5181 else
5182 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005183 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005184 && (is_first_match(compl_shown_match->cp_next)
5185 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005186 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005187 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005188 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005189 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005190 found_end = is_first_match(compl_shown_match);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005191 if (compl_match_array != NULL && compl_fuzzy_match)
5192 compl_shown_match = find_comp_when_fuzzy();
5193 else if (cpt_sources_active)
5194 compl_shown_match = find_comp_when_cpt_sources();
5195 else
5196 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005197 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005198 }
5199 else
5200 {
5201 if (!allow_get_expansion)
5202 {
5203 if (advance)
5204 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005205 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005206 compl_pending -= todo + 1;
5207 else
5208 compl_pending += todo + 1;
5209 }
5210 return -1;
5211 }
5212
5213 if (!compl_no_select && advance)
5214 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005215 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005216 --compl_pending;
5217 else
5218 ++compl_pending;
5219 }
5220
5221 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005222 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005223
5224 // handle any pending completions
5225 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005226 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005227 {
5228 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5229 {
5230 compl_shown_match = compl_shown_match->cp_next;
5231 --compl_pending;
5232 }
5233 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5234 {
5235 compl_shown_match = compl_shown_match->cp_prev;
5236 ++compl_pending;
5237 }
5238 else
5239 break;
5240 }
5241 found_end = FALSE;
5242 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005243 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005244 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005245 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005246 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005247 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005248 ++todo;
5249 else
5250 // Remember a matching item.
5251 found_compl = compl_shown_match;
5252
5253 // Stop at the end of the list when we found a usable match.
5254 if (found_end)
5255 {
5256 if (found_compl != NULL)
5257 {
5258 compl_shown_match = found_compl;
5259 break;
5260 }
5261 todo = 1; // use first usable match after wrapping around
5262 }
5263 }
5264
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005265 return OK;
5266}
5267
5268/*
5269 * Fill in the next completion in the current direction.
5270 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5271 * get more completions. If it is FALSE, then we just do nothing when there
5272 * are no more completions in a given direction. The latter case is used when
5273 * we are still in the middle of finding completions, to allow browsing
5274 * through the ones found so far.
5275 * Return the total number of matches, or -1 if still unknown -- webb.
5276 *
5277 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5278 * compl_shown_match here.
5279 *
5280 * Note that this function may be called recursively once only. First with
5281 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5282 * calls this function with "allow_get_expansion" FALSE.
5283 */
5284 static int
5285ins_compl_next(
5286 int allow_get_expansion,
5287 int count, // repeat completion this many times; should
5288 // be at least 1
5289 int insert_match, // Insert the newly selected match
5290 int in_compl_func) // called from complete_check()
5291{
5292 int num_matches = -1;
5293 int todo = count;
5294 int advance;
5295 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005296 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005297 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005298 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5299 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005300 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005301
5302 // When user complete function return -1 for findstart which is next
5303 // time of 'always', compl_shown_match become NULL.
5304 if (compl_shown_match == NULL)
5305 return -1;
5306
John Marriott5e6ea922024-11-23 14:01:57 +01005307 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005308 && !match_at_original_text(compl_shown_match)
5309 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005310 // Update "compl_shown_match" to the actually shown match
5311 ins_compl_update_shown_match();
5312
5313 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005314 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005315 // Delete old text to be replaced
5316 ins_compl_delete();
5317
5318 // When finding the longest common text we stick at the original text,
5319 // don't let CTRL-N or CTRL-P move to the first match.
5320 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5321
5322 // When restarting the search don't insert the first match either.
5323 if (compl_restarting)
5324 {
5325 advance = FALSE;
5326 compl_restarting = FALSE;
5327 }
5328
5329 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5330 // around.
5331 if (find_next_completion_match(allow_get_expansion, todo, advance,
5332 &num_matches) == -1)
5333 return -1;
5334
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005335 if (curbuf != orig_curbuf)
5336 {
5337 // In case some completion function switched buffer, don't want to
5338 // insert the completion elsewhere.
5339 return -1;
5340 }
5341
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005342 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005343 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005344 {
glepnir6a38aff2024-12-16 21:56:16 +01005345 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005346 compl_used_match = FALSE;
5347 }
5348 else if (insert_match)
5349 {
5350 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005351 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005352 else
glepnir6a38aff2024-12-16 21:56:16 +01005353 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005354 }
5355 else
5356 compl_used_match = FALSE;
5357
5358 if (!allow_get_expansion)
5359 {
5360 // may undisplay the popup menu first
5361 ins_compl_upd_pum();
5362
5363 if (pum_enough_matches())
5364 // Will display the popup menu, don't redraw yet to avoid flicker.
5365 pum_call_update_screen();
5366 else
5367 // Not showing the popup menu yet, redraw to show the user what was
5368 // inserted.
5369 update_screen(0);
5370
5371 // display the updated popup menu
5372 ins_compl_show_pum();
5373#ifdef FEAT_GUI
5374 if (gui.in_use)
5375 {
5376 // Show the cursor after the match, not after the redrawn text.
5377 setcursor();
5378 out_flush_cursor(FALSE, FALSE);
5379 }
5380#endif
5381
5382 // Delete old text to be replaced, since we're still searching and
5383 // don't want to match ourselves!
5384 ins_compl_delete();
5385 }
5386
5387 // Enter will select a match when the match wasn't inserted and the popup
5388 // menu is visible.
5389 if (compl_no_insert && !started)
5390 compl_enter_selects = TRUE;
5391 else
5392 compl_enter_selects = !insert_match && compl_match_array != NULL;
5393
5394 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005395 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005396 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005397
5398 return num_matches;
5399}
5400
5401/*
5402 * Call this while finding completions, to check whether the user has hit a key
5403 * that should change the currently displayed completion, or exit completion
5404 * mode. Also, when compl_pending is not zero, show a completion as soon as
5405 * possible. -- webb
5406 * "frequency" specifies out of how many calls we actually check.
5407 * "in_compl_func" is TRUE when called from complete_check(), don't set
5408 * compl_curr_match.
5409 */
5410 void
5411ins_compl_check_keys(int frequency, int in_compl_func)
5412{
5413 static int count = 0;
5414 int c;
5415
5416 // Don't check when reading keys from a script, :normal or feedkeys().
5417 // That would break the test scripts. But do check for keys when called
5418 // from complete_check().
5419 if (!in_compl_func && (using_script() || ex_normal_busy))
5420 return;
5421
5422 // Only do this at regular intervals
5423 if (++count < frequency)
5424 return;
5425 count = 0;
5426
5427 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5428 // can't do its work correctly.
5429 c = vpeekc_any();
5430 if (c != NUL)
5431 {
5432 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5433 {
5434 c = safe_vgetc(); // Eat the character
5435 compl_shows_dir = ins_compl_key2dir(c);
5436 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5437 c != K_UP && c != K_DOWN, in_compl_func);
5438 }
5439 else
5440 {
5441 // Need to get the character to have KeyTyped set. We'll put it
5442 // back with vungetc() below. But skip K_IGNORE.
5443 c = safe_vgetc();
5444 if (c != K_IGNORE)
5445 {
5446 // Don't interrupt completion when the character wasn't typed,
5447 // e.g., when doing @q to replay keys.
5448 if (c != Ctrl_R && KeyTyped)
5449 compl_interrupted = TRUE;
5450
5451 vungetc(c);
5452 }
5453 }
5454 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005455 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005456 {
5457 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5458
5459 compl_pending = 0;
5460 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5461 }
5462}
5463
5464/*
5465 * Decide the direction of Insert mode complete from the key typed.
5466 * Returns BACKWARD or FORWARD.
5467 */
5468 static int
5469ins_compl_key2dir(int c)
5470{
5471 if (c == Ctrl_P || c == Ctrl_L
5472 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5473 return BACKWARD;
5474 return FORWARD;
5475}
5476
5477/*
5478 * Return TRUE for keys that are used for completion only when the popup menu
5479 * is visible.
5480 */
5481 static int
5482ins_compl_pum_key(int c)
5483{
5484 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5485 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5486 || c == K_UP || c == K_DOWN);
5487}
5488
5489/*
5490 * Decide the number of completions to move forward.
5491 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5492 */
5493 static int
5494ins_compl_key2count(int c)
5495{
5496 int h;
5497
5498 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5499 {
5500 h = pum_get_height();
5501 if (h > 3)
5502 h -= 2; // keep some context
5503 return h;
5504 }
5505 return 1;
5506}
5507
5508/*
5509 * Return TRUE if completion with "c" should insert the match, FALSE if only
5510 * to change the currently selected completion.
5511 */
5512 static int
5513ins_compl_use_match(int c)
5514{
5515 switch (c)
5516 {
5517 case K_UP:
5518 case K_DOWN:
5519 case K_PAGEDOWN:
5520 case K_KPAGEDOWN:
5521 case K_S_DOWN:
5522 case K_PAGEUP:
5523 case K_KPAGEUP:
5524 case K_S_UP:
5525 return FALSE;
5526 }
5527 return TRUE;
5528}
5529
5530/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005531 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5532 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005533 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005534 * Uses the global variables: compl_cont_status and ctrl_x_mode
5535 */
5536 static int
5537get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5538{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005539 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005540 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005541 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005542 {
5543 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5544 ;
5545 compl_col += ++startcol;
5546 compl_length = curs_col - startcol;
5547 }
5548 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005549 {
John Marriott5e6ea922024-11-23 14:01:57 +01005550 compl_pattern.string = str_foldcase(line + compl_col,
5551 compl_length, NULL, 0);
5552 if (compl_pattern.string == NULL)
5553 {
5554 compl_pattern.length = 0;
5555 return FAIL;
5556 }
5557 compl_pattern.length = STRLEN(compl_pattern.string);
5558 }
5559 else
5560 {
5561 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5562 if (compl_pattern.string == NULL)
5563 {
5564 compl_pattern.length = 0;
5565 return FAIL;
5566 }
5567 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005568 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005569 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005570 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005571 {
5572 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005573 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005574 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005575
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005576 if (!vim_iswordp(line + compl_col)
5577 || (compl_col > 0
5578 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005579 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005580 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005581 prefixlen = 0;
5582 }
John Marriott5e6ea922024-11-23 14:01:57 +01005583
5584 // we need up to 2 extra chars for the prefix
5585 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5586 compl_pattern.string = alloc(n);
5587 if (compl_pattern.string == NULL)
5588 {
5589 compl_pattern.length = 0;
5590 return FAIL;
5591 }
5592 STRCPY((char *)compl_pattern.string, prefix);
5593 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005594 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005595 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005596 }
5597 else if (--startcol < 0
5598 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5599 {
John Marriott5e6ea922024-11-23 14:01:57 +01005600 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5601
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005602 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005603 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5604 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005605 {
John Marriott5e6ea922024-11-23 14:01:57 +01005606 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005607 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005608 }
John Marriott5e6ea922024-11-23 14:01:57 +01005609 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005610 compl_col += curs_col;
5611 compl_length = 0;
5612 }
5613 else
5614 {
5615 // Search the point of change class of multibyte character
5616 // or not a word single byte character backward.
5617 if (has_mbyte)
5618 {
5619 int base_class;
5620 int head_off;
5621
5622 startcol -= (*mb_head_off)(line, line + startcol);
5623 base_class = mb_get_class(line + startcol);
5624 while (--startcol >= 0)
5625 {
5626 head_off = (*mb_head_off)(line, line + startcol);
5627 if (base_class != mb_get_class(line + startcol
5628 - head_off))
5629 break;
5630 startcol -= head_off;
5631 }
5632 }
5633 else
5634 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5635 ;
5636 compl_col += ++startcol;
5637 compl_length = (int)curs_col - startcol;
5638 if (compl_length == 1)
5639 {
5640 // Only match word with at least two chars -- webb
5641 // there's no need to call quote_meta,
5642 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005643 compl_pattern.string = alloc(7);
5644 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005645 {
John Marriott5e6ea922024-11-23 14:01:57 +01005646 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005647 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005648 }
John Marriott5e6ea922024-11-23 14:01:57 +01005649 STRCPY((char *)compl_pattern.string, "\\<");
5650 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5651 STRCAT((char *)compl_pattern.string, "\\k");
5652 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005653 }
5654 else
5655 {
John Marriott5e6ea922024-11-23 14:01:57 +01005656 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5657
5658 compl_pattern.string = alloc(n);
5659 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005660 {
John Marriott5e6ea922024-11-23 14:01:57 +01005661 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005662 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005663 }
John Marriott5e6ea922024-11-23 14:01:57 +01005664 STRCPY((char *)compl_pattern.string, "\\<");
5665 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005666 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005667 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005668 }
5669 }
5670
5671 return OK;
5672}
5673
5674/*
5675 * Get the pattern, column and length for whole line completion or for the
5676 * complete() function.
5677 * Sets the global variables: compl_col, compl_length and compl_pattern.
5678 */
5679 static int
5680get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5681{
5682 compl_col = (colnr_T)getwhitecols(line);
5683 compl_length = (int)curs_col - (int)compl_col;
5684 if (compl_length < 0) // cursor in indent: empty pattern
5685 compl_length = 0;
5686 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005687 {
John Marriott5e6ea922024-11-23 14:01:57 +01005688 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5689 NULL, 0);
5690 if (compl_pattern.string == NULL)
5691 {
5692 compl_pattern.length = 0;
5693 return FAIL;
5694 }
5695 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005696 }
John Marriott5e6ea922024-11-23 14:01:57 +01005697 else
5698 {
5699 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5700 if (compl_pattern.string == NULL)
5701 {
5702 compl_pattern.length = 0;
5703 return FAIL;
5704 }
5705 compl_pattern.length = (size_t)compl_length;
5706 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005707
5708 return OK;
5709}
5710
5711/*
5712 * Get the pattern, column and length for filename completion.
5713 * Sets the global variables: compl_col, compl_length and compl_pattern.
5714 */
5715 static int
5716get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5717{
5718 // Go back to just before the first filename character.
5719 if (startcol > 0)
5720 {
5721 char_u *p = line + startcol;
5722
5723 MB_PTR_BACK(line, p);
5724 while (p > line && vim_isfilec(PTR2CHAR(p)))
5725 MB_PTR_BACK(line, p);
5726 if (p == line && vim_isfilec(PTR2CHAR(p)))
5727 startcol = 0;
5728 else
5729 startcol = (int)(p - line) + 1;
5730 }
5731
5732 compl_col += startcol;
5733 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005734 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5735 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005736 {
John Marriott5e6ea922024-11-23 14:01:57 +01005737 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005738 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005739 }
5740
John Marriott5e6ea922024-11-23 14:01:57 +01005741 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005742
5743 return OK;
5744}
5745
5746/*
5747 * Get the pattern, column and length for command-line completion.
5748 * Sets the global variables: compl_col, compl_length and compl_pattern.
5749 */
5750 static int
5751get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5752{
John Marriott5e6ea922024-11-23 14:01:57 +01005753 compl_pattern.string = vim_strnsave(line, curs_col);
5754 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005755 {
John Marriott5e6ea922024-11-23 14:01:57 +01005756 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005757 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005758 }
John Marriott5e6ea922024-11-23 14:01:57 +01005759 compl_pattern.length = curs_col;
5760 set_cmd_context(&compl_xp, compl_pattern.string,
5761 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005762 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5763 || compl_xp.xp_context == EXPAND_NOTHING)
5764 // No completion possible, use an empty pattern to get a
5765 // "pattern not found" message.
5766 compl_col = curs_col;
5767 else
John Marriott5e6ea922024-11-23 14:01:57 +01005768 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005769 compl_length = curs_col - compl_col;
5770
5771 return OK;
5772}
5773
5774/*
5775 * Get the pattern, column and length for user defined completion ('omnifunc',
5776 * 'completefunc' and 'thesaurusfunc')
5777 * Sets the global variables: compl_col, compl_length and compl_pattern.
5778 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005779 * Callback function "cb" is set if triggered by a function in the 'cpt'
5780 * option; otherwise, it is NULL.
5781 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005782 */
5783 static int
Girish Palyacbe53192025-04-14 22:13:15 +02005784get_userdefined_compl_info(colnr_T curs_col UNUSED, callback_T *cb UNUSED,
5785 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005786{
5787 int ret = FAIL;
5788
5789#ifdef FEAT_COMPL_FUNC
5790 // Call user defined function 'completefunc' with "a:findstart"
5791 // set to 1 to obtain the length of text to use for completion.
5792 char_u *line;
5793 typval_T args[3];
5794 int col;
5795 char_u *funcname;
5796 pos_T pos;
5797 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005798 int len;
5799 string_T *compl_pat;
5800 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005801
Girish Palyacbe53192025-04-14 22:13:15 +02005802 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005803 {
Girish Palyacbe53192025-04-14 22:13:15 +02005804 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5805 // length as a string
5806 funcname = get_complete_funcname(ctrl_x_mode);
5807 if (*funcname == NUL)
5808 {
5809 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5810 ? "completefunc" : "omnifunc");
5811 return FAIL;
5812 }
5813 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005814 }
5815
5816 args[0].v_type = VAR_NUMBER;
5817 args[0].vval.v_number = 1;
5818 args[1].v_type = VAR_STRING;
5819 args[1].vval.v_string = (char_u *)"";
5820 args[2].v_type = VAR_UNKNOWN;
5821 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005822 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005823 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005824 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005825
5826 State = save_State;
5827 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005828 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005829 validate_cursor();
5830 if (!EQUAL_POS(curwin->w_cursor, pos))
5831 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005832 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005833 return FAIL;
5834 }
5835
Girish Palyacbe53192025-04-14 22:13:15 +02005836 if (startcol != NULL)
5837 *startcol = col;
5838
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005839 // Return value -2 means the user complete function wants to cancel the
5840 // complete without an error, do the same if the function did not execute
5841 // successfully.
5842 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005843 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005844 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005845 if (col == -3)
5846 {
Girish Palyacbe53192025-04-14 22:13:15 +02005847 if (is_cpt_function)
5848 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005849 ctrl_x_mode = CTRL_X_NORMAL;
5850 edit_submode = NULL;
5851 if (!shortmess(SHM_COMPLETIONMENU))
5852 msg_clr_cmdline();
5853 return FAIL;
5854 }
5855
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005856 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005857 // completion.
5858 compl_opt_refresh_always = FALSE;
5859 compl_opt_suppress_empty = FALSE;
5860
Girish Palyacbe53192025-04-14 22:13:15 +02005861 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005862 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005863
5864 // Setup variables for completion. Need to obtain "line" again,
5865 // it may have become invalid.
5866 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02005867 len = curs_col - col;
5868 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
5869 compl_pat->string = vim_strnsave(line + col, (size_t)len);
5870 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005871 {
Girish Palyacbe53192025-04-14 22:13:15 +02005872 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005873 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005874 }
Girish Palyacbe53192025-04-14 22:13:15 +02005875 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005876
Girish Palyacbe53192025-04-14 22:13:15 +02005877 if (!is_cpt_function)
5878 {
5879 compl_col = col;
5880 compl_length = len;
5881 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005882 ret = OK;
5883#endif
5884
5885 return ret;
5886}
5887
5888/*
5889 * Get the pattern, column and length for spell completion.
5890 * Sets the global variables: compl_col, compl_length and compl_pattern.
5891 * Uses the global variable: spell_bad_len
5892 */
5893 static int
5894get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5895{
5896 int ret = FAIL;
5897#ifdef FEAT_SPELL
5898 char_u *line;
5899
5900 if (spell_bad_len > 0)
5901 compl_col = curs_col - spell_bad_len;
5902 else
5903 compl_col = spell_word_start(startcol);
5904 if (compl_col >= (colnr_T)startcol)
5905 {
5906 compl_length = 0;
5907 compl_col = curs_col;
5908 }
5909 else
5910 {
5911 spell_expand_check_cap(compl_col);
5912 compl_length = (int)curs_col - compl_col;
5913 }
5914 // Need to obtain "line" again, it may have become invalid.
5915 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005916 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5917 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005918 {
John Marriott5e6ea922024-11-23 14:01:57 +01005919 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005920 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005921 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005922
John Marriott5e6ea922024-11-23 14:01:57 +01005923 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005924 ret = OK;
5925#endif
5926
5927 return ret;
5928}
5929
5930/*
5931 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005932 * "startcol" - start column number of the completion pattern/text
5933 * "cur_col" - current cursor column
5934 * On return, "line_invalid" is set to TRUE, if the current line may have
5935 * become invalid and needs to be fetched again.
5936 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005937 */
5938 static int
5939compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5940{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005941 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005942 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5943 && !thesaurus_func_complete(ctrl_x_mode)))
5944 {
5945 return get_normal_compl_info(line, startcol, curs_col);
5946 }
5947 else if (ctrl_x_mode_line_or_eval())
5948 {
5949 return get_wholeline_compl_info(line, curs_col);
5950 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005951 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005952 {
5953 return get_filename_compl_info(line, startcol, curs_col);
5954 }
5955 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5956 {
5957 return get_cmdline_compl_info(line, curs_col);
5958 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005959 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005960 || thesaurus_func_complete(ctrl_x_mode))
5961 {
Girish Palyacbe53192025-04-14 22:13:15 +02005962 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005963 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005964 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005965 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005966 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005967 {
5968 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5969 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005970 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005971 }
5972 else
5973 {
5974 internal_error("ins_complete()");
5975 return FAIL;
5976 }
5977
5978 return OK;
5979}
5980
5981/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005982 * Continue an interrupted completion mode search in "line".
5983 *
5984 * If this same ctrl_x_mode has been interrupted use the text from
5985 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5986 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5987 * the same line as the cursor then fix it (the line has been split because it
5988 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5989 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005990 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005991 static void
5992ins_compl_continue_search(char_u *line)
5993{
5994 // it is a continued search
5995 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005996 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5997 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005998 {
5999 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6000 {
6001 // line (probably) wrapped, set compl_startpos to the
6002 // first non_blank in the line, if it is not a wordchar
6003 // include it to get a better pattern, but then we don't
6004 // want the "\\<" prefix, check it below
6005 compl_col = (colnr_T)getwhitecols(line);
6006 compl_startpos.col = compl_col;
6007 compl_startpos.lnum = curwin->w_cursor.lnum;
6008 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6009 }
6010 else
6011 {
6012 // S_IPOS was set when we inserted a word that was at the
6013 // beginning of the line, which means that we'll go to SOL
6014 // mode but first we need to redefine compl_startpos
6015 if (compl_cont_status & CONT_S_IPOS)
6016 {
6017 compl_cont_status |= CONT_SOL;
6018 compl_startpos.col = (colnr_T)(skipwhite(
6019 line + compl_length
6020 + compl_startpos.col) - line);
6021 }
6022 compl_col = compl_startpos.col;
6023 }
6024 compl_length = curwin->w_cursor.col - (int)compl_col;
6025 // IObuff is used to add a "word from the next line" would we
6026 // have enough space? just being paranoid
6027#define MIN_SPACE 75
6028 if (compl_length > (IOSIZE - MIN_SPACE))
6029 {
6030 compl_cont_status &= ~CONT_SOL;
6031 compl_length = (IOSIZE - MIN_SPACE);
6032 compl_col = curwin->w_cursor.col - compl_length;
6033 }
6034 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6035 if (compl_length < 1)
6036 compl_cont_status &= CONT_LOCAL;
6037 }
6038 else if (ctrl_x_mode_line_or_eval())
6039 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6040 else
6041 compl_cont_status = 0;
6042}
6043
6044/*
6045 * start insert mode completion
6046 */
6047 static int
6048ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006049{
6050 char_u *line;
6051 int startcol = 0; // column where searched text starts
6052 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006053 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006054 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006055 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006056
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006057 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006058
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006059 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006060 did_si = FALSE;
6061 can_si = FALSE;
6062 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006063 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006064 return FAIL;
6065
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006066 line = ml_get(curwin->w_cursor.lnum);
6067 curs_col = curwin->w_cursor.col;
6068 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006069 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006070
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006071 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6072 && compl_cont_mode == ctrl_x_mode)
6073 // this same ctrl-x_mode was interrupted previously. Continue the
6074 // completion.
6075 ins_compl_continue_search(line);
6076 else
6077 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006078
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006079 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006080 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006081 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006082 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006083 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6084 compl_cont_status = 0;
6085 compl_cont_status |= CONT_N_ADDS;
6086 compl_startpos = curwin->w_cursor;
6087 startcol = (int)curs_col;
6088 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006089 }
6090
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006091 // Work out completion pattern and original text -- webb
6092 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6093 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006094 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6095 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006096 // restore did_ai, so that adding comment leader works
6097 did_ai = save_did_ai;
6098 return FAIL;
6099 }
6100 // If "line" was changed while getting completion info get it again.
6101 if (line_invalid)
6102 line = ml_get(curwin->w_cursor.lnum);
6103
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006104 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006105 {
6106 edit_submode_pre = (char_u *)_(" Adding");
6107 if (ctrl_x_mode_line_or_eval())
6108 {
6109 // Insert a new line, keep indentation but ignore 'comments'.
6110 char_u *old = curbuf->b_p_com;
6111
6112 curbuf->b_p_com = (char_u *)"";
6113 compl_startpos.lnum = curwin->w_cursor.lnum;
6114 compl_startpos.col = compl_col;
6115 ins_eol('\r');
6116 curbuf->b_p_com = old;
6117 compl_length = 0;
6118 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006119 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006120 }
glepnircfe502c2025-04-17 20:17:53 +02006121 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006122 {
6123 compl_startpos = curwin->w_cursor;
6124 compl_cont_status &= CONT_S_IPOS;
6125 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006126 }
6127 else
6128 {
6129 edit_submode_pre = NULL;
6130 compl_startpos.col = compl_col;
6131 }
6132
6133 if (compl_cont_status & CONT_LOCAL)
6134 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6135 else
6136 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6137
6138 // If any of the original typed text has been changed we need to fix
6139 // the redo buffer.
6140 ins_compl_fixRedoBufForLeader(NULL);
6141
6142 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006143 VIM_CLEAR_STRING(compl_orig_text);
6144 compl_orig_text.length = (size_t)compl_length;
6145 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006146 if (p_ic)
6147 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006148 if (compl_orig_text.string == NULL
6149 || ins_compl_add(compl_orig_text.string,
6150 (int)compl_orig_text.length,
6151 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006152 {
John Marriott5e6ea922024-11-23 14:01:57 +01006153 VIM_CLEAR_STRING(compl_pattern);
6154 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006155 return FAIL;
6156 }
6157
6158 // showmode might reset the internal line pointers, so it must
6159 // be called before line = ml_get(), or when this address is no
6160 // longer needed. -- Acevedo.
6161 edit_submode_extra = (char_u *)_("-- Searching...");
6162 edit_submode_highl = HLF_COUNT;
6163 showmode();
6164 edit_submode_extra = NULL;
6165 out_flush();
6166
6167 return OK;
6168}
6169
6170/*
6171 * display the completion status message
6172 */
6173 static void
6174ins_compl_show_statusmsg(void)
6175{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006176 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006177 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006178 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006179 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006180 ? (char_u *)_("Hit end of paragraph")
6181 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006182 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006183 }
6184
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006185 if (edit_submode_extra == NULL)
6186 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006187 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006188 {
6189 edit_submode_extra = (char_u *)_("Back at original");
6190 edit_submode_highl = HLF_W;
6191 }
6192 else if (compl_cont_status & CONT_S_IPOS)
6193 {
6194 edit_submode_extra = (char_u *)_("Word from other line");
6195 edit_submode_highl = HLF_COUNT;
6196 }
6197 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6198 {
6199 edit_submode_extra = (char_u *)_("The only match");
6200 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006201 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006202 }
6203 else
6204 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006205#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006206 // Update completion sequence number when needed.
6207 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006208 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006209#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006210 // The match should always have a sequence number now, this is
6211 // just a safety check.
6212 if (compl_curr_match->cp_number != -1)
6213 {
6214 // Space for 10 text chars. + 2x10-digit no.s = 31.
6215 // Translations may need more than twice that.
6216 static char_u match_ref[81];
6217
6218 if (compl_matches > 0)
6219 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006220 _("match %d of %d"),
6221 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006222 else
6223 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006224 _("match %d"),
6225 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006226 edit_submode_extra = match_ref;
6227 edit_submode_highl = HLF_R;
6228 if (dollar_vcol >= 0)
6229 curs_columns(FALSE);
6230 }
6231 }
6232 }
6233
6234 // Show a message about what (completion) mode we're in.
6235 if (!compl_opt_suppress_empty)
6236 {
6237 showmode();
6238 if (!shortmess(SHM_COMPLETIONMENU))
6239 {
6240 if (edit_submode_extra != NULL)
6241 {
6242 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006243 {
6244 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006245 msg_attr((char *)edit_submode_extra,
6246 edit_submode_highl < HLF_COUNT
6247 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006248 msg_hist_off = FALSE;
6249 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006250 }
6251 else
6252 msg_clr_cmdline(); // necessary for "noshowmode"
6253 }
6254 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006255}
6256
6257/*
6258 * Do Insert mode completion.
6259 * Called when character "c" was typed, which has a meaning for completion.
6260 * Returns OK if completion was done, FAIL if something failed (out of mem).
6261 */
6262 int
6263ins_complete(int c, int enable_pum)
6264{
6265 int n;
6266 int save_w_wrow;
6267 int save_w_leftcol;
6268 int insert_match;
6269
6270 compl_direction = ins_compl_key2dir(c);
6271 insert_match = ins_compl_use_match(c);
6272
6273 if (!compl_started)
6274 {
6275 if (ins_compl_start() == FAIL)
6276 return FAIL;
6277 }
6278 else if (insert_match && stop_arrow() == FAIL)
6279 return FAIL;
6280
glepnircf7f0122025-04-15 19:02:00 +02006281 compl_curr_win = curwin;
6282 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006283 compl_shown_match = compl_curr_match;
6284 compl_shows_dir = compl_direction;
6285
6286 // Find next match (and following matches).
6287 save_w_wrow = curwin->w_wrow;
6288 save_w_leftcol = curwin->w_leftcol;
6289 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6290
6291 // may undisplay the popup menu
6292 ins_compl_upd_pum();
6293
6294 if (n > 1) // all matches have been found
6295 compl_matches = n;
6296 compl_curr_match = compl_shown_match;
6297 compl_direction = compl_shows_dir;
6298
6299 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6300 // mode.
6301 if (got_int && !global_busy)
6302 {
6303 (void)vgetc();
6304 got_int = FALSE;
6305 }
6306
6307 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006308 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006309 {
6310 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6311 // because we couldn't expand anything at first place, but if we used
6312 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6313 // (such as M in M'exico) if not tried already. -- Acevedo
6314 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006315 || compl_status_adding()
6316 || (ctrl_x_mode_not_default()
6317 && !ctrl_x_mode_path_patterns()
6318 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006319 compl_cont_status &= ~CONT_N_ADDS;
6320 }
6321
6322 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6323 compl_cont_status |= CONT_S_IPOS;
6324 else
6325 compl_cont_status &= ~CONT_S_IPOS;
6326
6327 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006328
6329 // Show the popup menu, unless we got interrupted.
6330 if (enable_pum && !compl_interrupted)
6331 show_pum(save_w_wrow, save_w_leftcol);
6332
6333 compl_was_interrupted = compl_interrupted;
6334 compl_interrupted = FALSE;
6335
6336 return OK;
6337}
6338
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006339/*
6340 * Remove (if needed) and show the popup menu
6341 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006342 static void
6343show_pum(int prev_w_wrow, int prev_w_leftcol)
6344{
6345 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006346 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006347 RedrawingDisabled = 0;
6348
6349 // If the cursor moved or the display scrolled we need to remove the pum
6350 // first.
6351 setcursor();
6352 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6353 ins_compl_del_pum();
6354
6355 ins_compl_show_pum();
6356 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006357
6358 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006359}
6360
6361/*
6362 * Looks in the first "len" chars. of "src" for search-metachars.
6363 * If dest is not NULL the chars. are copied there quoting (with
6364 * a backslash) the metachars, and dest would be NUL terminated.
6365 * Returns the length (needed) of dest
6366 */
6367 static unsigned
6368quote_meta(char_u *dest, char_u *src, int len)
6369{
6370 unsigned m = (unsigned)len + 1; // one extra for the NUL
6371
6372 for ( ; --len >= 0; src++)
6373 {
6374 switch (*src)
6375 {
6376 case '.':
6377 case '*':
6378 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006379 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006380 break;
6381 // FALLTHROUGH
6382 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006383 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006384 break;
6385 // FALLTHROUGH
6386 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006387 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006388 break;
6389 // FALLTHROUGH
6390 case '^': // currently it's not needed.
6391 case '$':
6392 m++;
6393 if (dest != NULL)
6394 *dest++ = '\\';
6395 break;
6396 }
6397 if (dest != NULL)
6398 *dest++ = *src;
6399 // Copy remaining bytes of a multibyte character.
6400 if (has_mbyte)
6401 {
6402 int i, mb_len;
6403
6404 mb_len = (*mb_ptr2len)(src) - 1;
6405 if (mb_len > 0 && len >= mb_len)
6406 for (i = 0; i < mb_len; ++i)
6407 {
6408 --len;
6409 ++src;
6410 if (dest != NULL)
6411 *dest++ = *src;
6412 }
6413 }
6414 }
6415 if (dest != NULL)
6416 *dest = NUL;
6417
6418 return m;
6419}
6420
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006421#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006422 void
6423free_insexpand_stuff(void)
6424{
John Marriott5e6ea922024-11-23 14:01:57 +01006425 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006426# ifdef FEAT_EVAL
6427 free_callback(&cfu_cb);
6428 free_callback(&ofu_cb);
6429 free_callback(&tsrfu_cb);
6430# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006431}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006432#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006433
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006434#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006435/*
6436 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6437 * spelled word, if there is one.
6438 */
6439 static void
6440spell_back_to_badword(void)
6441{
6442 pos_T tpos = curwin->w_cursor;
6443
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006444 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006445 if (curwin->w_cursor.col != tpos.col)
6446 start_arrow(&tpos);
6447}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006448#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006449
6450/*
6451 * Reset the info associated with completion sources.
6452 */
6453 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006454cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006455{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006456 VIM_CLEAR(cpt_sources_array);
6457 cpt_sources_index = -1;
6458 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006459}
6460
6461/*
6462 * Initialize the info associated with completion sources.
6463 */
6464 static int
Girish Palya0ac1eb32025-04-16 20:18:33 +02006465cpt_sources_init(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006466{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006467 char_u buf[LSIZE];
6468 int slen;
Girish Palyacbe53192025-04-14 22:13:15 +02006469 int count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006470 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006471
Girish Palya0ac1eb32025-04-16 20:18:33 +02006472 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006473 {
6474 while (*p == ',' || *p == ' ') // Skip delimiters
6475 p++;
6476 if (*p) // If not end of string, count this segment
6477 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006478 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006479 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006480 }
6481 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006482 cpt_sources_clear();
6483 cpt_sources_count = count;
Girish Palyacbe53192025-04-14 22:13:15 +02006484 if (count > 0)
6485 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006486 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6487 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006488 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006489 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006490 return FAIL;
6491 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006492 count = 0;
6493 for (p = curbuf->b_p_cpt; *p;)
6494 {
6495 while (*p == ',' || *p == ' ') // Skip delimiters
6496 p++;
6497 if (*p) // If not end of string, count this segment
6498 {
6499 char_u *t;
6500
6501 vim_memset(buf, 0, LSIZE);
6502 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6503 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6504 cpt_sources_array[count].max_matches = atoi((char *)t + 1);
6505 count++;
6506 }
6507 }
Girish Palyacbe53192025-04-14 22:13:15 +02006508 }
6509 return OK;
6510}
6511
6512/*
6513 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6514 */
6515 static int
6516is_cpt_func_refresh_always(void)
6517{
6518#ifdef FEAT_COMPL_FUNC
6519 int i;
6520
Girish Palya0ac1eb32025-04-16 20:18:33 +02006521 for (i = 0; i < cpt_sources_count; i++)
6522 if (cpt_sources_array[i].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006523 return TRUE;
6524#endif
6525 return FALSE;
6526}
6527
6528/*
6529 * Make the completion list non-cyclic.
6530 */
6531#ifdef FEAT_COMPL_FUNC
6532 static void
6533ins_compl_make_linear(void)
6534{
6535 compl_T *m;
6536
6537 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6538 return;
6539 m = compl_first_match->cp_prev;
6540 m->cp_next = NULL;
6541 compl_first_match->cp_prev = NULL;
6542}
6543#endif
6544
6545/*
6546 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006547 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006548 */
6549#ifdef FEAT_COMPL_FUNC
6550 static compl_T *
6551remove_old_matches(void)
6552{
6553 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6554 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006555 int compl_shown_removed = FALSE;
6556 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6557
6558 compl_direction = forward ? FORWARD : BACKWARD;
6559 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006560
6561 // Identify the sublist of old matches that needs removal
6562 for (current = compl_first_match; current != NULL; current = current->cp_next)
6563 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006564 if (current->cp_cpt_source_idx < cpt_sources_index &&
6565 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006566 insert_at = current;
6567
Girish Palya0ac1eb32025-04-16 20:18:33 +02006568 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006569 {
6570 if (!sublist_start)
6571 sublist_start = current;
6572 sublist_end = current;
6573 if (!compl_shown_removed && compl_shown_match == current)
6574 compl_shown_removed = TRUE;
6575 }
6576
Girish Palya0ac1eb32025-04-16 20:18:33 +02006577 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6578 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006579 break;
6580 }
6581
6582 // Re-assign compl_shown_match if necessary
6583 if (compl_shown_removed)
6584 {
6585 if (forward)
6586 compl_shown_match = compl_first_match;
6587 else
6588 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006589 for (current = compl_first_match; current->cp_next != NULL;
6590 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006591 ;
6592 compl_shown_match = current;
6593 }
6594 }
6595
6596 if (!sublist_start) // No nodes to remove
6597 return insert_at;
6598
6599 // Update links to remove sublist
6600 if (sublist_start->cp_prev)
6601 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6602 else
6603 compl_first_match = sublist_end->cp_next;
6604
6605 if (sublist_end->cp_next)
6606 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6607
6608 // Free all nodes in the sublist
6609 sublist_end->cp_next = NULL;
6610 for (current = sublist_start; current != NULL; current = next)
6611 {
6612 next = current->cp_next;
6613 ins_compl_item_free(current);
6614 }
6615
6616 return insert_at;
6617}
6618#endif
6619
6620/*
6621 * Retrieve completion matches using the callback function "cb" and store the
6622 * 'refresh:always' flag.
6623 */
6624#ifdef FEAT_COMPL_FUNC
6625 static void
6626get_cpt_func_completion_matches(callback_T *cb UNUSED)
6627{
6628 int ret;
6629 int startcol;
6630
6631 VIM_CLEAR_STRING(cpt_compl_pattern);
6632 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6633 if (ret == FAIL && startcol == -3)
Girish Palya0ac1eb32025-04-16 20:18:33 +02006634 cpt_sources_array[cpt_sources_index].refresh_always = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02006635 else if (ret == OK)
6636 {
6637 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006638 cpt_sources_array[cpt_sources_index].refresh_always =
6639 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02006640 compl_opt_refresh_always = FALSE;
6641 }
6642}
6643#endif
6644
6645/*
6646 * Retrieve completion matches from functions in the 'cpt' option where the
6647 * 'refresh:always' flag is set.
6648 */
6649 static void
6650cpt_compl_refresh(void)
6651{
6652#ifdef FEAT_COMPL_FUNC
6653 char_u *cpt;
6654 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006655 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006656
6657 // Make the completion list linear (non-cyclic)
6658 ins_compl_make_linear();
6659 // Make a copy of 'cpt' in case the buffer gets wiped out
6660 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02006661 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02006662
Girish Palya0ac1eb32025-04-16 20:18:33 +02006663 cpt_sources_index = 0;
6664 for (p = cpt; *p; cpt_sources_index++)
Girish Palyacbe53192025-04-14 22:13:15 +02006665 {
6666 while (*p == ',' || *p == ' ') // Skip delimiters
6667 p++;
6668
Girish Palya0ac1eb32025-04-16 20:18:33 +02006669 if (cpt_sources_array[cpt_sources_index].refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006670 {
6671 if (*p == 'o')
6672 cb = &curbuf->b_ofu_cb;
6673 else if (*p == 'f')
6674 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6675 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6676 if (cb)
6677 {
6678 compl_curr_match = remove_old_matches();
6679 get_cpt_func_completion_matches(cb);
6680 }
6681 }
6682
6683 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6684 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006685 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02006686
6687 vim_free(cpt);
6688 // Make the list cyclic
6689 compl_matches = ins_compl_make_cyclic();
6690#endif
6691}