blob: 9ee73e15e5cc0d68d84f4cdcd6eb6b72c7a0c3e7 [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
glepnir05460682025-05-26 18:23:27 +020041# define CTRL_X_REGISTER 18 // complete words from registers
Bram Moolenaar7591bb32019-03-30 13:53:47 +010042
43# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
44
45// Message for CTRL-X mode, index is ctrl_x_mode.
46static char *ctrl_x_msgs[] =
47{
48 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
glepnir05460682025-05-26 18:23:27 +020049 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010050 NULL, // CTRL_X_SCROLL: depends on state
51 N_(" Whole line completion (^L^N^P)"),
52 N_(" File name completion (^F^N^P)"),
53 N_(" Tag completion (^]^N^P)"),
54 N_(" Path pattern completion (^N^P)"),
55 N_(" Definition completion (^D^N^P)"),
56 NULL, // CTRL_X_FINISHED
57 N_(" Dictionary completion (^K^N^P)"),
58 N_(" Thesaurus completion (^T^N^P)"),
59 N_(" Command-line completion (^V^N^P)"),
60 N_(" User defined completion (^U^N^P)"),
61 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020062 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010063 N_(" Keyword Local completion (^N^P)"),
64 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020065 N_(" Command-line completion (^V^N^P)"),
glepnir05460682025-05-26 18:23:27 +020066 N_(" Register completion (^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010067};
68
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020069#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010070static char *ctrl_x_mode_names[] = {
Hirohito Higashi355db992025-04-28 18:07:02 +020071 "keyword",
72 "ctrl_x",
73 "scroll",
74 "whole_line",
75 "files",
76 "tags",
77 "path_patterns",
78 "path_defines",
79 "unknown", // CTRL_X_FINISHED
80 "dictionary",
81 "thesaurus",
82 "cmdline",
83 "function",
84 "omni",
85 "spell",
86 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
87 "eval",
88 "cmdline",
glepnir05460682025-05-26 18:23:27 +020089 "register",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010090};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020091#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010092
93/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010094 * Structure used to store one match for insert completion.
95 */
96typedef struct compl_S compl_T;
97struct compl_S
98{
99 compl_T *cp_next;
100 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +0100101 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +0100102 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200103 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100104#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100105 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100106#endif
glepnir0fe17f82024-10-08 22:26:44 +0200107 char_u *cp_fname; // file containing the match, allocated when
108 // cp_flags has CP_FREE_FNAME
109 int cp_flags; // CP_ values
110 int cp_number; // sequence number
Girish Palyab1565882025-04-15 20:16:00 +0200111 int cp_score; // fuzzy match score or proximity score
glepnird4088ed2024-12-31 10:55:22 +0100112 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200113 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200114 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palya0ac1eb32025-04-16 20:18:33 +0200115 int cp_cpt_source_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100116};
117
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200118// values for cp_flags
119# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
120# define CP_FREE_FNAME 2 // cp_fname is allocated
121# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
122# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
123# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200124# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100125
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126/*
127 * All the current matches are stored in a list.
128 * "compl_first_match" points to the start of the list.
129 * "compl_curr_match" points to the currently selected entry.
130 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200131 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000132 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100133 */
134static compl_T *compl_first_match = NULL;
135static compl_T *compl_curr_match = NULL;
136static compl_T *compl_shown_match = NULL;
137static compl_T *compl_old_match = NULL;
138
glepnirf31cfa22025-03-06 21:59:13 +0100139// list used to store the compl_T which have the max score
140// used for completefuzzycollect
141static compl_T **compl_best_matches = NULL;
142static int compl_num_bests = 0;
143// inserted a longest when completefuzzycollect enabled
144static int compl_cfc_longest_ins = FALSE;
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// After using a cursor key <Enter> selects a match in the popup menu,
147// otherwise it inserts a line break.
148static int compl_enter_selects = FALSE;
149
150// When "compl_leader" is not NULL only matches that start with this string
151// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100152static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100153
154static int compl_get_longest = FALSE; // put longest common string
155 // in compl_leader
156
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100157// Selected one of the matches. When FALSE the match was edited or using the
158// longest common string.
159static int compl_used_match;
160
161// didn't finish finding completions.
162static int compl_was_interrupted = FALSE;
163
164// Set when character typed while looking for matches and it means we should
165// stop looking for matches.
166static int compl_interrupted = FALSE;
167
168static int compl_restarting = FALSE; // don't insert match
169
170// When the first completion is done "compl_started" is set. When it's
171// FALSE the word to be completed must be located.
172static int compl_started = FALSE;
173
174// Which Ctrl-X mode are we in?
175static int ctrl_x_mode = CTRL_X_NORMAL;
176
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000177static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200178static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
179#ifdef FEAT_COMPL_FUNC
180static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
181#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100182static int compl_direction = FORWARD;
183static int compl_shows_dir = FORWARD;
184static int compl_pending = 0; // > 1 for postponed CTRL-N
185static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000186// Length in bytes of the text being completed (this is deleted to be replaced
187// by the match.)
188static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100189static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100190static colnr_T compl_col = 0; // column where the text starts
191 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100192static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100193static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100194 // completion started
195static int compl_cont_mode = 0;
196static expand_T compl_xp;
197
glepnircf7f0122025-04-15 19:02:00 +0200198static win_T *compl_curr_win = NULL; // win where completion is active
199static buf_T *compl_curr_buf = NULL; // buf where completion is active
200
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000201// List of flags for method of completion.
202static int compl_cont_status = 0;
203# define CONT_ADDING 1 // "normal" or "adding" expansion
204# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
205 // it's set only iff N_ADDS is set
206# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
207# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
208 // if so, word-wise-expansion will set SOL
209# define CONT_SOL 16 // pattern includes start of line, just for
210 // word-wise expansion, not set for ^X^L
211# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
212 // expansion, (eg use complete=.)
213
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100214static int compl_opt_refresh_always = FALSE;
215static int compl_opt_suppress_empty = FALSE;
216
glepnira218cc62024-06-03 19:32:39 +0200217static int compl_selected_item = -1;
218
glepnir8159fb12024-07-17 20:32:54 +0200219static int *compl_fuzzy_scores;
220
Girish Palya0ac1eb32025-04-16 20:18:33 +0200221// Define the structure for completion source (in 'cpt' option) information
222typedef struct cpt_source_T
223{
Girish Palya98c29db2025-06-01 19:40:00 +0200224 int cs_refresh_always; // Whether 'refresh:always' is set for func
225 int cs_startcol; // Start column returned by func
226 int cs_max_matches; // Max items to display from this source
Girish Palya0ac1eb32025-04-16 20:18:33 +0200227} cpt_source_T;
228
229static cpt_source_T *cpt_sources_array; // Pointer to the array of completion sources
230static int cpt_sources_count; // Total number of completion sources specified in the 'cpt' option
Girish Palya7c621052025-05-26 19:41:59 +0200231static int cpt_sources_index = -1; // Index of the current completion source being expanded
Girish Palyacbe53192025-04-14 22:13:15 +0200232
glepnir6a38aff2024-12-16 21:56:16 +0100233// "compl_match_array" points the currently displayed list of entries in the
234// popup menu. It is NULL when there is no popup menu.
235static pumitem_T *compl_match_array = NULL;
236static int compl_match_arraysize;
237
glepnirf31cfa22025-03-06 21:59:13 +0100238static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup, int *user_hl, int score);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100239static void ins_compl_longest_match(compl_T *match);
240static void ins_compl_del_pum(void);
241static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100243static int ins_compl_need_restart(void);
244static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000245static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100246static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100247static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100248static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
249# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
250static void ins_compl_add_list(list_T *list);
251static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200252static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
Girish Palyacbe53192025-04-14 22:13:15 +0200253static void get_cpt_func_completion_matches(callback_T *cb);
Girish Palya98c29db2025-06-01 19:40:00 +0200254static callback_T *get_callback_if_cpt_func(char_u *p);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100255# endif
Girish Palya98c29db2025-06-01 19:40:00 +0200256static int setup_cpt_sources(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200257static int is_cpt_func_refresh_always(void);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200258static void cpt_sources_clear(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200259static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100260static int ins_compl_key2dir(int c);
261static int ins_compl_pum_key(int c);
262static int ins_compl_key2count(int c);
263static void show_pum(int prev_w_wrow, int prev_w_leftcol);
264static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100265static int ins_compl_has_multiple(void);
266static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100267static void ins_compl_longest_insert(char_u *prefix);
Girish Palya8cd42a52025-06-05 21:04:29 +0200268static void ins_compl_make_linear(void);
269static int ins_compl_make_cyclic(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100270
271#ifdef FEAT_SPELL
272static void spell_back_to_badword(void);
273static int spell_bad_len = 0; // length of located bad word
274#endif
275
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100276/*
277 * CTRL-X pressed in Insert mode.
278 */
279 void
280ins_ctrl_x(void)
281{
zeertzjqdca29d92021-08-31 19:12:51 +0200282 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100283 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000284 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100285 if (compl_cont_status & CONT_N_ADDS)
286 compl_cont_status |= CONT_INTRPT;
287 else
288 compl_cont_status = 0;
289 // We're not sure which CTRL-X mode it will be yet
290 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
291 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
292 edit_submode_pre = NULL;
293 showmode();
294 }
zeertzjqdca29d92021-08-31 19:12:51 +0200295 else
296 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
297 // CTRL-V look like CTRL-N
298 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100299
LemonBoy2bf52dd2022-04-09 18:17:34 +0100300 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301}
302
303/*
304 * Functions to check the current CTRL-X mode.
305 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000306int ctrl_x_mode_none(void)
307 { return ctrl_x_mode == 0; }
308int ctrl_x_mode_normal(void)
309 { return ctrl_x_mode == CTRL_X_NORMAL; }
310int ctrl_x_mode_scroll(void)
311 { return ctrl_x_mode == CTRL_X_SCROLL; }
312int ctrl_x_mode_whole_line(void)
313 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
314int ctrl_x_mode_files(void)
315 { return ctrl_x_mode == CTRL_X_FILES; }
316int ctrl_x_mode_tags(void)
317 { return ctrl_x_mode == CTRL_X_TAGS; }
318int ctrl_x_mode_path_patterns(void)
319 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
320int ctrl_x_mode_path_defines(void)
321 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
322int ctrl_x_mode_dictionary(void)
323 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
324int ctrl_x_mode_thesaurus(void)
325 { return ctrl_x_mode == CTRL_X_THESAURUS; }
326int ctrl_x_mode_cmdline(void)
327 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200328 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000329int ctrl_x_mode_function(void)
330 { return ctrl_x_mode == CTRL_X_FUNCTION; }
331int ctrl_x_mode_omni(void)
332 { return ctrl_x_mode == CTRL_X_OMNI; }
333int ctrl_x_mode_spell(void)
334 { return ctrl_x_mode == CTRL_X_SPELL; }
335static int ctrl_x_mode_eval(void)
336 { return ctrl_x_mode == CTRL_X_EVAL; }
337int ctrl_x_mode_line_or_eval(void)
338 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
glepnir05460682025-05-26 18:23:27 +0200339int ctrl_x_mode_register(void)
340 { return ctrl_x_mode == CTRL_X_REGISTER; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100341
342/*
343 * Whether other than default completion has been selected.
344 */
345 int
346ctrl_x_mode_not_default(void)
347{
348 return ctrl_x_mode != CTRL_X_NORMAL;
349}
350
351/*
zeertzjqdca29d92021-08-31 19:12:51 +0200352 * Whether CTRL-X was typed without a following character,
353 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100354 */
355 int
356ctrl_x_mode_not_defined_yet(void)
357{
358 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
359}
360
361/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000362 * Return TRUE if currently in "normal" or "adding" insert completion matches
363 * state
364 */
365 int
366compl_status_adding(void)
367{
368 return compl_cont_status & CONT_ADDING;
369}
370
371/*
372 * Return TRUE if the completion pattern includes start of line, just for
373 * word-wise expansion.
374 */
375 int
376compl_status_sol(void)
377{
378 return compl_cont_status & CONT_SOL;
379}
380
381/*
382 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
383 */
384 int
385compl_status_local(void)
386{
387 return compl_cont_status & CONT_LOCAL;
388}
389
390/*
391 * Clear the completion status flags
392 */
393 void
394compl_status_clear(void)
395{
396 compl_cont_status = 0;
397}
398
399/*
400 * Return TRUE if completion is using the forward direction matches
401 */
402 static int
403compl_dir_forward(void)
404{
405 return compl_direction == FORWARD;
406}
407
408/*
409 * Return TRUE if currently showing forward completion matches
410 */
411 static int
412compl_shows_dir_forward(void)
413{
414 return compl_shows_dir == FORWARD;
415}
416
417/*
418 * Return TRUE if currently showing backward completion matches
419 */
420 static int
421compl_shows_dir_backward(void)
422{
423 return compl_shows_dir == BACKWARD;
424}
425
426/*
427 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100428 */
429 int
430has_compl_option(int dict_opt)
431{
432 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200433#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200435#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100436 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100437 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
438#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100439 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100440#endif
441 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100442 {
443 ctrl_x_mode = CTRL_X_NORMAL;
444 edit_submode = NULL;
445 msg_attr(dict_opt ? _("'dictionary' option is empty")
446 : _("'thesaurus' option is empty"),
447 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100448 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100449 {
450 vim_beep(BO_COMPL);
451 setcursor();
452 out_flush();
453#ifdef FEAT_EVAL
454 if (!get_vim_var_nr(VV_TESTING))
455#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100456 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100457 }
458 return FALSE;
459 }
460 return TRUE;
461}
462
463/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000464 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100465 * This depends on the current mode.
466 */
467 int
468vim_is_ctrl_x_key(int c)
469{
470 // Always allow ^R - let its results then be checked
glepnir05460682025-05-26 18:23:27 +0200471 if (c == Ctrl_R && ctrl_x_mode != CTRL_X_REGISTER)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100472 return TRUE;
473
474 // Accept <PageUp> and <PageDown> if the popup menu is visible.
475 if (ins_compl_pum_key(c))
476 return TRUE;
477
478 switch (ctrl_x_mode)
479 {
480 case 0: // Not in any CTRL-X mode
481 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
482 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200483 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100484 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
485 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
486 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
487 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
488 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200489 || c == Ctrl_S || c == Ctrl_K || c == 's'
glepnir05460682025-05-26 18:23:27 +0200490 || c == Ctrl_Z || c == Ctrl_R);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100491 case CTRL_X_SCROLL:
492 return (c == Ctrl_Y || c == Ctrl_E);
493 case CTRL_X_WHOLE_LINE:
494 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
495 case CTRL_X_FILES:
496 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
497 case CTRL_X_DICTIONARY:
498 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
499 case CTRL_X_THESAURUS:
500 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
501 case CTRL_X_TAGS:
502 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
503#ifdef FEAT_FIND_ID
504 case CTRL_X_PATH_PATTERNS:
505 return (c == Ctrl_P || c == Ctrl_N);
506 case CTRL_X_PATH_DEFINES:
507 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
508#endif
509 case CTRL_X_CMDLINE:
510 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
511 || c == Ctrl_X);
512#ifdef FEAT_COMPL_FUNC
513 case CTRL_X_FUNCTION:
514 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
515 case CTRL_X_OMNI:
516 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
517#endif
518 case CTRL_X_SPELL:
519 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
520 case CTRL_X_EVAL:
521 return (c == Ctrl_P || c == Ctrl_N);
glepnir05460682025-05-26 18:23:27 +0200522 case CTRL_X_REGISTER:
523 return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100524 }
525 internal_error("vim_is_ctrl_x_key()");
526 return FALSE;
527}
528
529/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000530 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000531 */
532 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000533match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000534{
535 return match->cp_flags & CP_ORIGINAL_TEXT;
536}
537
538/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000539 * Returns TRUE if "match" is the first match in the completion list.
540 */
541 static int
542is_first_match(compl_T *match)
543{
544 return match == compl_first_match;
545}
546
547/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100548 * Return TRUE when character "c" is part of the item currently being
549 * completed. Used to decide whether to abandon complete mode when the menu
550 * is visible.
551 */
552 int
553ins_compl_accept_char(int c)
554{
555 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
556 // When expanding an identifier only accept identifier chars.
557 return vim_isIDc(c);
558
559 switch (ctrl_x_mode)
560 {
561 case CTRL_X_FILES:
562 // When expanding file name only accept file name chars. But not
563 // path separators, so that "proto/<Tab>" expands files in
564 // "proto", not "proto/" as a whole
565 return vim_isfilec(c) && !vim_ispathsep(c);
566
567 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200568 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100569 case CTRL_X_OMNI:
570 // Command line and Omni completion can work with just about any
571 // printable character, but do stop at white space.
572 return vim_isprintc(c) && !VIM_ISWHITE(c);
573
574 case CTRL_X_WHOLE_LINE:
575 // For while line completion a space can be part of the line.
576 return vim_isprintc(c);
577 }
578 return vim_iswordc(c);
579}
580
581/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100583 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000584 */
585 static char_u *
586ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200587 char_u *str,
588 int char_len,
589 int compl_char_len,
590 int min_len,
591 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000592{
593 int *wca; // Wide character array.
594 char_u *p;
595 int i, c;
596 int has_lower = FALSE;
597 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100598 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000599
600 IObuff[0] = NUL;
601
602 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100603 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000604 if (wca == NULL)
605 return IObuff;
606
607 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100608 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100609 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000610 if (has_mbyte)
611 wca[i] = mb_ptr2char_adv(&p);
612 else
613 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100614 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000615
616 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100617 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000618 for (i = 0; i < min_len; ++i)
619 {
glepnir6e199932024-12-14 21:13:27 +0100620 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000621 if (MB_ISLOWER(c))
622 {
623 has_lower = TRUE;
624 if (MB_ISUPPER(wca[i]))
625 {
626 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100627 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000628 wca[i] = MB_TOLOWER(wca[i]);
629 break;
630 }
631 }
632 }
633
634 // Rule 2: No lower case, 2nd consecutive letter converted to
635 // upper case.
636 if (!has_lower)
637 {
John Marriott5e6ea922024-11-23 14:01:57 +0100638 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000639 for (i = 0; i < min_len; ++i)
640 {
glepnir6e199932024-12-14 21:13:27 +0100641 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000642 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
643 {
644 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100645 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000646 wca[i] = MB_TOUPPER(wca[i]);
647 break;
648 }
649 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
650 }
651 }
652
653 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100654 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000655 for (i = 0; i < min_len; ++i)
656 {
glepnir6e199932024-12-14 21:13:27 +0100657 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000658 if (MB_ISLOWER(c))
659 wca[i] = MB_TOLOWER(wca[i]);
660 else if (MB_ISUPPER(c))
661 wca[i] = MB_TOUPPER(wca[i]);
662 }
663
664 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000665 p = IObuff;
666 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100667 ga_init2(&gap, 1, 500);
668 while (i < char_len)
669 {
670 if (gap.ga_data != NULL)
671 {
672 if (ga_grow(&gap, 10) == FAIL)
673 {
674 ga_clear(&gap);
675 return (char_u *)"[failed]";
676 }
677 p = (char_u *)gap.ga_data + gap.ga_len;
678 if (has_mbyte)
679 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
680 else
681 {
682 *p = wca[i++];
683 ++gap.ga_len;
684 }
685 }
686 else if ((p - IObuff) + 6 >= IOSIZE)
687 {
688 // Multi-byte characters can occupy up to five bytes more than
689 // ASCII characters, and we also need one byte for NUL, so when
690 // getting to six bytes from the edge of IObuff switch to using a
691 // growarray. Add the character in the next round.
692 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100693 {
694 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100696 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100697 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100699 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100700 }
701 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000702 p += (*mb_char2bytes)(wca[i++], p);
703 else
704 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100705 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000706 vim_free(wca);
707
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100708 if (gap.ga_data != NULL)
709 {
710 *tofree = gap.ga_data;
711 return gap.ga_data;
712 }
713
714 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000715 return IObuff;
716}
717
718/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
720 * case of the originally typed text is used, and the case of the completed
721 * text is inferred, ie this tries to work out what case you probably wanted
722 * the rest of the word to be in -- webb
723 */
724 int
725ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200726 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100727 int len,
728 int icase,
729 char_u *fname,
730 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100731 int cont_s_ipos, // next ^X<> will set initial_pos
732 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200734 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 int char_len; // count multi-byte characters
737 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100738 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200739 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 int res;
741 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742
743 if (p_ic && curbuf->b_p_inf && len > 0)
744 {
745 // Infer case of completed part.
746
747 // Find actual length of completion.
748 if (has_mbyte)
749 {
750 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100751 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752 while (*p != NUL)
753 {
754 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100755 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100756 }
757 }
758 else
glepnir6e199932024-12-14 21:13:27 +0100759 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100760 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100761 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762
763 // Find actual length of original text.
764 if (has_mbyte)
765 {
John Marriott5e6ea922024-11-23 14:01:57 +0100766 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100767 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100768 while (*p != NUL)
769 {
770 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100771 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100772 }
773 }
774 else
glepnir6e199932024-12-14 21:13:27 +0100775 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100776 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100777 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100778
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100779 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100781 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100782
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100783 str = ins_compl_infercase_gettext(str, char_len,
784 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100785 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200786 if (cont_s_ipos)
787 flags |= CP_CONT_S_IPOS;
788 if (icase)
789 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200790
glepnirf31cfa22025-03-06 21:59:13 +0100791 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100792 vim_free(tofree);
793 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100794}
795
796/*
glepnirf31cfa22025-03-06 21:59:13 +0100797 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
798 */
799 static int
800cfc_has_mode(void)
801{
glepnir58760162025-03-13 21:39:51 +0100802 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
803 return (cfc_flags & CFC_KEYWORD) != 0;
804 else if (ctrl_x_mode_files())
805 return (cfc_flags & CFC_FILES) != 0;
806 else if (ctrl_x_mode_whole_line())
807 return (cfc_flags & CFC_WHOLELINE) != 0;
808 else
809 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100810}
811
812/*
Girish Palyab1565882025-04-15 20:16:00 +0200813 * Returns TRUE if matches should be sorted based on proximity to the cursor.
814 */
815 static int
816is_nearest_active(void)
817{
glepnirc3fbaa02025-05-08 23:05:10 +0200818 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200819}
820
821/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000822 * Add a match to the list of matches. The arguments are:
823 * str - text of the match to add
824 * len - length of "str". If -1, then the length of "str" is
825 * computed.
826 * fname - file name to associate with this match.
827 * cptext - list of strings to use with this match (for abbr, menu, info
828 * and kind)
829 * user_data - user supplied data (any vim type) for this match
830 * cdir - match direction. If 0, use "compl_direction".
831 * flags_arg - match flags (cp_flags)
832 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100833 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000834 * If "cdir" is FORWARD, then the match is added after the current match.
835 * Otherwise, it is added before the current match.
836 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100837 * If the given string is already in the list of completions, then return
838 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
839 * maybe because alloc() returns NULL, then FAIL is returned.
840 */
841 static int
842ins_compl_add(
843 char_u *str,
844 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100845 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100846 char_u **cptext, // extra text for popup menu or NULL
847 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100848 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200849 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200850 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100851 int *user_hl, // user abbr/kind hlattr
852 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100853{
glepnirf31cfa22025-03-06 21:59:13 +0100854 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100855 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200856 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100857 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100858
Bram Moolenaarceb06192021-04-04 15:05:22 +0200859 if (flags & CP_FAST)
860 fast_breakcheck();
861 else
862 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100863 if (got_int)
864 return FAIL;
865 if (len < 0)
866 len = (int)STRLEN(str);
867
868 // If the same match is already present, don't add it.
869 if (compl_first_match != NULL && !adup)
870 {
871 match = compl_first_match;
872 do
873 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000874 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100875 && STRNCMP(match->cp_str.string, str, len) == 0
876 && ((int)match->cp_str.length <= len
877 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200878 {
879 if (is_nearest_active() && score > 0 && score < match->cp_score)
Girish Palyab1565882025-04-15 20:16:00 +0200880 match->cp_score = score;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200882 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100883 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000884 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100885 }
886
887 // Remove any popup menu before changing the list of matches.
888 ins_compl_del_pum();
889
890 // Allocate a new match structure.
891 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200892 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100893 if (match == NULL)
894 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100895 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100896 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100897 {
898 vim_free(match);
899 return FAIL;
900 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100901
John Marriott5e6ea922024-11-23 14:01:57 +0100902 match->cp_str.length = len;
903
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100904 // match-fname is:
905 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200906 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100907 // - NULL otherwise. --Acevedo
908 if (fname != NULL
909 && compl_curr_match != NULL
910 && compl_curr_match->cp_fname != NULL
911 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
912 match->cp_fname = compl_curr_match->cp_fname;
913 else if (fname != NULL)
914 {
915 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200916 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100917 }
918 else
919 match->cp_fname = NULL;
920 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100921 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
922 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100923 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200924 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100925
926 if (cptext != NULL)
927 {
glepnir19e1dd62025-05-08 22:50:38 +0200928 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100929 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100930 if (cptext[i] != NULL && *cptext[i] != NUL)
931 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100932 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100933 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100934#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100935 if (user_data != NULL)
936 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100937#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100938
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000939 // Link the new match structure after (FORWARD) or before (BACKWARD) the
940 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100941 if (compl_first_match == NULL)
942 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +0100943 else if (cfc_has_mode() && score > 0 && compl_get_longest)
944 {
945 current = compl_first_match->cp_next;
946 prev = compl_first_match;
947 inserted = FALSE;
948 // The direction is ignored when using longest and
949 // completefuzzycollect, because matches are inserted
950 // and sorted by score.
951 while (current != NULL && current != compl_first_match)
952 {
953 if (current->cp_score < score)
954 {
Hirohito Higashi355db992025-04-28 18:07:02 +0200955 match->cp_next = current;
956 match->cp_prev = current->cp_prev;
957 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +0100958 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +0200959 current->cp_prev = match;
960 inserted = TRUE;
961 break;
glepnirf31cfa22025-03-06 21:59:13 +0100962 }
963 prev = current;
964 current = current->cp_next;
965 }
966 if (!inserted)
967 {
968 prev->cp_next = match;
969 match->cp_prev = prev;
970 match->cp_next = compl_first_match;
971 compl_first_match->cp_prev = match;
972 }
973 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100974 else if (dir == FORWARD)
975 {
976 match->cp_next = compl_curr_match->cp_next;
977 match->cp_prev = compl_curr_match;
978 }
979 else // BACKWARD
980 {
981 match->cp_next = compl_curr_match;
982 match->cp_prev = compl_curr_match->cp_prev;
983 }
984 if (match->cp_next)
985 match->cp_next->cp_prev = match;
986 if (match->cp_prev)
987 match->cp_prev->cp_next = match;
988 else // if there's nothing before, it is the first match
989 compl_first_match = match;
990 compl_curr_match = match;
991
992 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +0100993 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100994 ins_compl_longest_match(match);
995
996 return OK;
997}
998
999/*
1000 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001001 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002 */
1003 static int
1004ins_compl_equal(compl_T *match, char_u *str, int len)
1005{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001006 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001007 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001008 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001009 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1010 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001011}
1012
1013/*
glepnir6a38aff2024-12-16 21:56:16 +01001014 * when len is -1 mean use whole length of p otherwise part of p
1015 */
1016 static void
1017ins_compl_insert_bytes(char_u *p, int len)
1018{
1019 if (len == -1)
1020 len = (int)STRLEN(p);
1021 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001022 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001023}
1024
1025/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001026 * Checks if the column is within the currently inserted completion text
1027 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001028 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001029 */
1030 int
glepnir76bdb822025-02-08 19:04:51 +01001031ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001032{
glepnir76bdb822025-02-08 19:04:51 +01001033 int start_col;
1034 int attr;
1035
1036 if ((get_cot_flags() & COT_FUZZY)
1037 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001038 return -1;
1039
glepnir76bdb822025-02-08 19:04:51 +01001040 start_col = compl_col + (int)ins_compl_leader_len();
1041 if (!ins_compl_has_multiple())
1042 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1043
1044 // Multiple lines
1045 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1046 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1047 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1048 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001049
1050 return -1;
1051}
1052
1053/*
glepnir76bdb822025-02-08 19:04:51 +01001054 * Returns TRUE if the current completion string contains newline characters,
1055 * indicating it's a multi-line completion.
1056 */
1057 static int
1058ins_compl_has_multiple(void)
1059{
1060 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1061}
1062
1063/*
1064 * Returns TRUE if the given line number falls within the range of a multi-line
1065 * completion, i.e. between the starting line (compl_lnum) and current cursor
1066 * line. Always returns FALSE for single-line completions.
1067 */
1068 int
1069ins_compl_lnum_in_range(linenr_T lnum)
1070{
1071 if (!ins_compl_has_multiple())
1072 return FALSE;
1073 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1074}
1075
1076/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001077 * Reduce the longest common string for match "match".
1078 */
1079 static void
1080ins_compl_longest_match(compl_T *match)
1081{
1082 char_u *p, *s;
1083 int c1, c2;
1084 int had_match;
1085
John Marriott5e6ea922024-11-23 14:01:57 +01001086 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001087 {
1088 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001089 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1090 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001091 return;
1092
John Marriott5e6ea922024-11-23 14:01:57 +01001093 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001094 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001095 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001096
1097 // When the match isn't there (to avoid matching itself) remove it
1098 // again after redrawing.
1099 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001100 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001101 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001102
1103 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001104 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001105
1106 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001107 p = compl_leader.string;
1108 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001109 while (*p != NUL)
1110 {
1111 if (has_mbyte)
1112 {
1113 c1 = mb_ptr2char(p);
1114 c2 = mb_ptr2char(s);
1115 }
1116 else
1117 {
1118 c1 = *p;
1119 c2 = *s;
1120 }
1121 if ((match->cp_flags & CP_ICASE)
1122 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1123 break;
1124 if (has_mbyte)
1125 {
1126 MB_PTR_ADV(p);
1127 MB_PTR_ADV(s);
1128 }
1129 else
1130 {
1131 ++p;
1132 ++s;
1133 }
1134 }
1135
1136 if (*p != NUL)
1137 {
1138 // Leader was shortened, need to change the inserted text.
1139 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001140 compl_leader.length = (size_t)(p - compl_leader.string);
1141
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001142 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001143 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001144
1145 // When the match isn't there (to avoid matching itself) remove it
1146 // again after redrawing.
1147 if (!had_match)
1148 ins_compl_delete();
1149 }
1150
1151 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001152}
1153
1154/*
1155 * Add an array of matches to the list of matches.
1156 * Frees matches[].
1157 */
1158 static void
1159ins_compl_add_matches(
1160 int num_matches,
1161 char_u **matches,
1162 int icase)
1163{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001164 int add_r = OK;
1165 int dir = compl_direction;
1166
glepnir19e1dd62025-05-08 22:50:38 +02001167 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001168 {
1169 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001170 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001171 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001172 // if dir was BACKWARD then honor it just once
1173 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001174 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 FreeWild(num_matches, matches);
1176}
1177
1178/*
1179 * Make the completion list cyclic.
1180 * Return the number of matches (excluding the original).
1181 */
1182 static int
1183ins_compl_make_cyclic(void)
1184{
1185 compl_T *match;
1186 int count = 0;
1187
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001188 if (compl_first_match == NULL)
1189 return 0;
1190
1191 // Find the end of the list.
1192 match = compl_first_match;
1193 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001194 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001195 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001196 match = match->cp_next;
1197 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001198 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001199 match->cp_next = compl_first_match;
1200 compl_first_match->cp_prev = match;
1201
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001202 return count;
1203}
1204
1205/*
1206 * Return whether there currently is a shown match.
1207 */
1208 int
1209ins_compl_has_shown_match(void)
1210{
1211 return compl_shown_match == NULL
1212 || compl_shown_match != compl_shown_match->cp_next;
1213}
1214
1215/*
1216 * Return whether the shown match is long enough.
1217 */
1218 int
1219ins_compl_long_shown_match(void)
1220{
John Marriott5e6ea922024-11-23 14:01:57 +01001221 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001222 > curwin->w_cursor.col - compl_col;
1223}
1224
1225/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001226 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001228 unsigned int
1229get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001230{
zeertzjq529b9ad2024-06-05 20:27:06 +02001231 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001232}
1233
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001234/*
1235 * Update the screen and when there is any scrolling remove the popup menu.
1236 */
1237 static void
1238ins_compl_upd_pum(void)
1239{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001240 if (compl_match_array == NULL)
1241 return;
1242
glepnir19e1dd62025-05-08 22:50:38 +02001243 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001244 // Update the screen later, before drawing the popup menu over it.
1245 pum_call_update_screen();
1246 if (h != curwin->w_cline_height)
1247 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001248}
1249
1250/*
1251 * Remove any popup menu.
1252 */
1253 static void
1254ins_compl_del_pum(void)
1255{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001256 if (compl_match_array == NULL)
1257 return;
1258
1259 pum_undisplay();
1260 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001261}
1262
1263/*
1264 * Return TRUE if the popup menu should be displayed.
1265 */
1266 int
1267pum_wanted(void)
1268{
1269 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001270 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001271 return FALSE;
1272
1273 // The display looks bad on a B&W display.
1274 if (t_colors < 8
1275#ifdef FEAT_GUI
1276 && !gui.in_use
1277#endif
1278 )
1279 return FALSE;
1280 return TRUE;
1281}
1282
1283/*
1284 * Return TRUE if there are two or more matches to be shown in the popup menu.
1285 * One if 'completopt' contains "menuone".
1286 */
1287 static int
1288pum_enough_matches(void)
1289{
1290 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001291 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001292
1293 // Don't display the popup menu if there are no matches or there is only
1294 // one (ignoring the original text).
1295 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001296 do
1297 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001298 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299 break;
1300 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001301 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001302
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001304 return (i >= 1);
1305 return (i >= 2);
1306}
1307
Bram Moolenaar3075a452021-11-17 15:51:52 +00001308#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001309/*
1310 * Allocate Dict for the completed item.
1311 * { word, abbr, menu, kind, info }
1312 */
1313 static dict_T *
1314ins_compl_dict_alloc(compl_T *match)
1315{
1316 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1317
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001318 if (dict == NULL)
1319 return NULL;
1320
John Marriott5e6ea922024-11-23 14:01:57 +01001321 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001322 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1323 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1324 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1325 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1326 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1327 dict_add_string(dict, "user_data", (char_u *)"");
1328 else
1329 dict_add_tv(dict, "user_data", &match->cp_user_data);
1330
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001331 return dict;
1332}
1333
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001334/*
1335 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1336 * completion menu is changed.
1337 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001338 static void
1339trigger_complete_changed_event(int cur)
1340{
1341 dict_T *v_event;
1342 dict_T *item;
1343 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001344 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001345
1346 if (recursive)
1347 return;
1348
glepnir40891ba2025-02-10 22:18:00 +01001349 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001350 if (item == NULL)
1351 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001352 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001353 dict_add_dict(v_event, "completed_item", item);
1354 pum_set_event_info(v_event);
1355 dict_set_items_ro(v_event);
1356
1357 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001358 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001359 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001360 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001361 recursive = FALSE;
1362
Bram Moolenaar3075a452021-11-17 15:51:52 +00001363 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001364}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001365#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001366
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001367/*
Girish Palya8cd42a52025-06-05 21:04:29 +02001368 * Helper functions for mergesort_list().
Girish Palya19ef6b02025-05-28 20:28:21 +02001369 */
Girish Palya8cd42a52025-06-05 21:04:29 +02001370 static void*
1371cp_get_next(void *node)
Girish Palya19ef6b02025-05-28 20:28:21 +02001372{
Girish Palya8cd42a52025-06-05 21:04:29 +02001373 return ((compl_T*)node)->cp_next;
Girish Palya19ef6b02025-05-28 20:28:21 +02001374}
1375
Girish Palya8cd42a52025-06-05 21:04:29 +02001376 static void
1377cp_set_next(void *node, void *next)
glepnira218cc62024-06-03 19:32:39 +02001378{
Girish Palya8cd42a52025-06-05 21:04:29 +02001379 ((compl_T*)node)->cp_next = (compl_T*)next;
1380}
1381
1382 static void*
1383cp_get_prev(void* node)
1384{
1385 return ((compl_T*)node)->cp_prev;
1386}
1387
1388 static void
1389cp_set_prev(void* node, void* prev)
1390{
1391 ((compl_T*)node)->cp_prev = (compl_T*)prev;
1392}
1393
1394 static int
1395cp_compare_fuzzy(const void* a, const void* b)
1396{
1397 int score_a = ((compl_T*)a)->cp_score;
1398 int score_b = ((compl_T*)b)->cp_score;
1399 return (score_b > score_a) ? 1 : (score_b < score_a) ? -1 : 0;
glepnira218cc62024-06-03 19:32:39 +02001400}
1401
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001402 static int
1403cp_compare_nearest(const void* a, const void* b)
1404{
1405 int score_a = ((compl_T*)a)->cp_score;
1406 int score_b = ((compl_T*)b)->cp_score;
1407 if (score_a < 0 || score_b < 0)
1408 return 0;
1409 return (score_a > score_b) ? 1 : (score_a < score_b) ? -1 : 0;
1410}
1411
1412/*
1413 * Set fuzzy score.
1414 */
1415 static void
1416set_fuzzy_score(void)
1417{
zeertzjq91782b42025-06-10 20:06:53 +02001418 compl_T *compl;
zeertzjqde1c7ac2025-06-09 20:34:57 +02001419
zeertzjq91782b42025-06-10 20:06:53 +02001420 if (!compl_first_match
1421 || compl_leader.string == NULL || compl_leader.length == 0)
1422 return;
1423
1424 compl = compl_first_match;
1425 do
1426 {
1427 compl->cp_score = fuzzy_match_str(compl->cp_str.string,
1428 compl_leader.string);
1429 compl = compl->cp_next;
1430 } while (compl != NULL && !is_first_match(compl));
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001431}
1432
1433/*
1434 * Sort completion matches, excluding the node that contains the leader.
1435 */
1436 static void
1437sort_compl_match_list(int (*compare)(const void *, const void *))
1438{
zeertzjq91782b42025-06-10 20:06:53 +02001439 compl_T *compl;
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001440
1441 if (!compl_first_match || is_first_match(compl_first_match->cp_next))
1442 return;
1443
zeertzjq91782b42025-06-10 20:06:53 +02001444 compl = compl_first_match->cp_prev;
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001445 ins_compl_make_linear();
1446 if (compl_shows_dir_forward())
1447 {
1448 compl_first_match->cp_next->cp_prev = NULL;
1449 compl_first_match->cp_next = mergesort_list(compl_first_match->cp_next,
1450 cp_get_next, cp_set_next, cp_get_prev, cp_set_prev, compare);
1451 compl_first_match->cp_next->cp_prev = compl_first_match;
1452 }
1453 else
1454 {
1455 compl->cp_prev->cp_next = NULL;
1456 compl_first_match = mergesort_list(compl_first_match, cp_get_next,
1457 cp_set_next, cp_get_prev, cp_set_prev, compare);
1458 compl_T *tail = compl_first_match;
1459 while (tail->cp_next != NULL)
1460 tail = tail->cp_next;
1461 tail->cp_next = compl;
1462 compl->cp_prev = tail;
1463 }
1464 (void)ins_compl_make_cyclic();
1465}
1466
glepnira218cc62024-06-03 19:32:39 +02001467/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001468 * Build a popup menu to show the completion matches.
1469 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1470 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001471 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001472 static int
1473ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001474{
1475 compl_T *compl;
1476 compl_T *shown_compl = NULL;
1477 int did_find_shown_match = FALSE;
1478 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001479 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001480 int cur = -1;
zeertzjqaa925ee2024-06-09 18:24:05 +02001481 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001482 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001483 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
glepnir80b66202024-11-27 21:53:53 +01001484 compl_T *match_head = NULL;
1485 compl_T *match_tail = NULL;
1486 compl_T *match_next = NULL;
Girish Palya8cd42a52025-06-05 21:04:29 +02001487 int *match_count = NULL;
Girish Palya19ef6b02025-05-28 20:28:21 +02001488 int is_forward = compl_shows_dir_forward();
Girish Palya8cd42a52025-06-05 21:04:29 +02001489 int is_cpt_completion = (cpt_sources_array != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001490
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001491 // Need to build the popup menu list.
1492 compl_match_arraysize = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001493
glepnira49c0772024-11-30 10:56:30 +01001494 // If the current match is the original text don't find the first
1495 // match after it, don't highlight anything.
1496 if (match_at_original_text(compl_shown_match))
1497 shown_match_ok = TRUE;
1498
1499 if (compl_leader.string != NULL
1500 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1501 && shown_match_ok == FALSE)
1502 compl_shown_match = compl_no_select ? compl_first_match
1503 : compl_first_match->cp_next;
1504
Girish Palya8cd42a52025-06-05 21:04:29 +02001505 if (is_cpt_completion)
1506 {
1507 match_count = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1508 if (match_count == NULL)
1509 return -1;
1510 }
1511
1512 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001513 do
1514 {
glepnird4088ed2024-12-31 10:55:22 +01001515 compl->cp_in_match_array = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001516
Girish Palyadc314052025-05-08 23:28:52 +02001517 // Apply 'smartcase' behavior during normal mode
1518 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1519 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1520 compl->cp_flags &= ~CP_ICASE;
1521
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001522 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001523 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001524 || ins_compl_equal(compl, compl_leader.string,
1525 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001526 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001527 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001528 // Limit number of items from each source if max_items is set.
1529 int match_limit_exceeded = FALSE;
1530 int cur_source = compl->cp_cpt_source_idx;
1531 if (is_forward && cur_source != -1 && is_cpt_completion)
glepnira49c0772024-11-30 10:56:30 +01001532 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001533 match_count[cur_source]++;
1534 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
1535 if (max_matches > 0 && match_count[cur_source] > max_matches)
1536 match_limit_exceeded = TRUE;
1537 }
1538
1539 if (!match_limit_exceeded)
1540 {
1541 ++compl_match_arraysize;
1542 compl->cp_in_match_array = TRUE;
1543 if (match_head == NULL)
1544 match_head = compl;
glepnira49c0772024-11-30 10:56:30 +01001545 else
Girish Palya8cd42a52025-06-05 21:04:29 +02001546 match_tail->cp_match_next = compl;
1547 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001548
Girish Palya8cd42a52025-06-05 21:04:29 +02001549 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001550 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001551 if (compl == compl_shown_match || did_find_shown_match)
1552 {
1553 // This item is the shown match or this is the
1554 // first displayed item after the shown match.
1555 compl_shown_match = compl;
1556 did_find_shown_match = TRUE;
1557 shown_match_ok = TRUE;
1558 }
1559 else
1560 // Remember this displayed match for when the
1561 // shown match is just below it.
1562 shown_compl = compl;
glepnira49c0772024-11-30 10:56:30 +01001563 cur = i;
glepnira49c0772024-11-30 10:56:30 +01001564 }
Girish Palya8cd42a52025-06-05 21:04:29 +02001565 else if (fuzzy_filter)
1566 {
1567 if (i == 0)
1568 shown_compl = compl;
1569
1570 if (!shown_match_ok && compl == compl_shown_match)
1571 {
1572 cur = i;
1573 shown_match_ok = TRUE;
1574 }
1575 }
1576 i++;
glepnira49c0772024-11-30 10:56:30 +01001577 }
glepnir80b66202024-11-27 21:53:53 +01001578 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001579
glepnirf400a0c2025-01-23 19:55:14 +01001580 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001581 {
1582 did_find_shown_match = TRUE;
1583
1584 // When the original text is the shown match don't set
1585 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001586 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001587 shown_match_ok = TRUE;
1588
1589 if (!shown_match_ok && shown_compl != NULL)
1590 {
1591 // The shown match isn't displayed, set it to the
1592 // previously displayed match.
1593 compl_shown_match = shown_compl;
1594 shown_match_ok = TRUE;
1595 }
1596 }
glepnira49c0772024-11-30 10:56:30 +01001597 compl = compl->cp_next;
1598 } while (compl != NULL && !is_first_match(compl));
1599
Girish Palya8cd42a52025-06-05 21:04:29 +02001600 vim_free(match_count);
1601
glepnira49c0772024-11-30 10:56:30 +01001602 if (compl_match_arraysize == 0)
1603 return -1;
1604
Girish Palya8cd42a52025-06-05 21:04:29 +02001605 if (fuzzy_filter && !compl_no_select && !shown_match_ok)
glepnirc0b7ca42025-02-13 20:27:44 +01001606 {
1607 compl_shown_match = shown_compl;
1608 shown_match_ok = TRUE;
1609 cur = 0;
1610 }
1611
glepnira49c0772024-11-30 10:56:30 +01001612 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1613 if (compl_match_array == NULL)
1614 return -1;
1615
1616 compl = match_head;
1617 i = 0;
1618 while (compl != NULL)
1619 {
glepnir6e199932024-12-14 21:13:27 +01001620 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1621 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001622 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1623 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
Girish Palya19ef6b02025-05-28 20:28:21 +02001624 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001625 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1626 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001627 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1628 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001629 match_next = compl->cp_match_next;
1630 compl->cp_match_next = NULL;
1631 compl = match_next;
1632 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001633
1634 if (!shown_match_ok) // no displayed match at all
1635 cur = -1;
1636
1637 return cur;
1638}
1639
1640/*
1641 * Show the popup menu for the list of matches.
1642 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1643 */
1644 void
1645ins_compl_show_pum(void)
1646{
1647 int i;
1648 int cur = -1;
1649 colnr_T col;
1650
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001651 if (!pum_wanted() || !pum_enough_matches())
1652 return;
1653
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001654 // Update the screen later, before drawing the popup menu over it.
1655 pum_call_update_screen();
1656
1657 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001658 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001659 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001660 else
1661 {
1662 // popup menu already exists, only need to find the current item.
1663 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001664 {
John Marriott5e6ea922024-11-23 14:01:57 +01001665 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001666 || compl_match_array[i].pum_text
1667 == compl_shown_match->cp_text[CPT_ABBR])
1668 {
1669 cur = i;
1670 break;
1671 }
glepnir19e1dd62025-05-08 22:50:38 +02001672 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001673 }
1674
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001675 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001676 {
1677#ifdef FEAT_EVAL
1678 if (compl_started && has_completechanged())
1679 trigger_complete_changed_event(cur);
1680#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001681 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001682 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001683
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001684 // In Replace mode when a $ is displayed at the end of the line only
1685 // part of the screen would be updated. We do need to redraw here.
1686 dollar_vcol = -1;
1687
1688 // Compute the screen column of the start of the completed text.
1689 // Use the cursor to get all wrapping and other settings right.
1690 col = curwin->w_cursor.col;
1691 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001692 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001693 pum_display(compl_match_array, compl_match_arraysize, cur);
1694 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001695
glepnircbb46b42024-02-03 18:11:13 +01001696 // After adding leader, set the current match to shown match.
1697 if (compl_started && compl_curr_match != compl_shown_match)
1698 compl_curr_match = compl_shown_match;
1699
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001700#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001701 if (has_completechanged())
1702 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001703#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001704}
1705
1706#define DICT_FIRST (1) // use just first element in "dict"
1707#define DICT_EXACT (2) // "dict" is the exact name of a file
1708
1709/*
glepnir40c1c332024-06-11 19:37:04 +02001710 * Get current completion leader
1711 */
1712 char_u *
1713ins_compl_leader(void)
1714{
John Marriott5e6ea922024-11-23 14:01:57 +01001715 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1716}
1717
1718/*
1719 * Get current completion leader length
1720 */
1721 size_t
1722ins_compl_leader_len(void)
1723{
1724 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001725}
1726
1727/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001728 * Add any identifiers that match the given pattern "pat" in the list of
1729 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001730 */
1731 static void
1732ins_compl_dictionaries(
1733 char_u *dict_start,
1734 char_u *pat,
1735 int flags, // DICT_FIRST and/or DICT_EXACT
1736 int thesaurus) // Thesaurus completion
1737{
1738 char_u *dict = dict_start;
1739 char_u *ptr;
1740 char_u *buf;
1741 regmatch_T regmatch;
1742 char_u **files;
1743 int count;
1744 int save_p_scs;
1745 int dir = compl_direction;
1746
1747 if (*dict == NUL)
1748 {
1749#ifdef FEAT_SPELL
1750 // When 'dictionary' is empty and spell checking is enabled use
1751 // "spell".
1752 if (!thesaurus && curwin->w_p_spell)
1753 dict = (char_u *)"spell";
1754 else
1755#endif
1756 return;
1757 }
1758
1759 buf = alloc(LSIZE);
1760 if (buf == NULL)
1761 return;
1762 regmatch.regprog = NULL; // so that we can goto theend
1763
1764 // If 'infercase' is set, don't use 'smartcase' here
1765 save_p_scs = p_scs;
1766 if (curbuf->b_p_inf)
1767 p_scs = FALSE;
1768
1769 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1770 // to only match at the start of a line. Otherwise just match the
1771 // pattern. Also need to double backslashes.
1772 if (ctrl_x_mode_line_or_eval())
1773 {
1774 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001775
1776 if (pat_esc == NULL)
1777 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001778 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001779 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001780 if (ptr == NULL)
1781 {
1782 vim_free(pat_esc);
1783 goto theend;
1784 }
1785 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1786 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1787 vim_free(pat_esc);
1788 vim_free(ptr);
1789 }
1790 else
1791 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001792 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001793 if (regmatch.regprog == NULL)
1794 goto theend;
1795 }
1796
1797 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1798 regmatch.rm_ic = ignorecase(pat);
1799 while (*dict != NUL && !got_int && !compl_interrupted)
1800 {
1801 // copy one dictionary file name into buf
1802 if (flags == DICT_EXACT)
1803 {
1804 count = 1;
1805 files = &dict;
1806 }
1807 else
1808 {
1809 // Expand wildcards in the dictionary name, but do not allow
1810 // backticks (for security, the 'dict' option may have been set in
1811 // a modeline).
1812 copy_option_part(&dict, buf, LSIZE, ",");
1813# ifdef FEAT_SPELL
1814 if (!thesaurus && STRCMP(buf, "spell") == 0)
1815 count = -1;
1816 else
1817# endif
1818 if (vim_strchr(buf, '`') != NULL
1819 || expand_wildcards(1, &buf, &count, &files,
1820 EW_FILE|EW_SILENT) != OK)
1821 count = 0;
1822 }
1823
1824# ifdef FEAT_SPELL
1825 if (count == -1)
1826 {
1827 // Complete from active spelling. Skip "\<" in the pattern, we
1828 // don't use it as a RE.
1829 if (pat[0] == '\\' && pat[1] == '<')
1830 ptr = pat + 2;
1831 else
1832 ptr = pat;
1833 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1834 }
1835 else
1836# endif
1837 if (count > 0) // avoid warning for using "files" uninit
1838 {
1839 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001840 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001841 if (flags != DICT_EXACT)
1842 FreeWild(count, files);
1843 }
1844 if (flags != 0)
1845 break;
1846 }
1847
1848theend:
1849 p_scs = save_p_scs;
1850 vim_regfree(regmatch.regprog);
1851 vim_free(buf);
1852}
1853
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001854/*
1855 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1856 * skipping the word at 'skip_word'. Returns OK on success.
1857 */
1858 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001859thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001860 char_u *fname,
1861 char_u **buf_arg,
1862 int dir,
1863 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001864{
1865 int status = OK;
1866 char_u *ptr;
1867 char_u *wstart;
1868
1869 // Add the other matches on the line
1870 ptr = *buf_arg;
1871 while (!got_int)
1872 {
1873 // Find start of the next word. Skip white
1874 // space and punctuation.
1875 ptr = find_word_start(ptr);
1876 if (*ptr == NUL || *ptr == NL)
1877 break;
1878 wstart = ptr;
1879
1880 // Find end of the word.
1881 if (has_mbyte)
1882 // Japanese words may have characters in
1883 // different classes, only separate words
1884 // with single-byte non-word characters.
1885 while (*ptr != NUL)
1886 {
1887 int l = (*mb_ptr2len)(ptr);
1888
1889 if (l < 2 && !vim_iswordc(*ptr))
1890 break;
1891 ptr += l;
1892 }
1893 else
1894 ptr = find_word_end(ptr);
1895
1896 // Add the word. Skip the regexp match.
1897 if (wstart != skip_word)
1898 {
1899 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001900 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001901 if (status == FAIL)
1902 break;
1903 }
1904 }
1905
1906 *buf_arg = ptr;
1907 return status;
1908}
1909
1910/*
1911 * Process "count" dictionary/thesaurus "files" and add the text matching
1912 * "regmatch".
1913 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001914 static void
1915ins_compl_files(
1916 int count,
1917 char_u **files,
1918 int thesaurus,
1919 int flags,
1920 regmatch_T *regmatch,
1921 char_u *buf,
1922 int *dir)
1923{
1924 char_u *ptr;
1925 int i;
1926 FILE *fp;
1927 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001928 char_u *leader = NULL;
1929 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001930 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001931 int score = 0;
1932 int len = 0;
1933 char_u *line_end = NULL;
1934
1935 if (in_fuzzy_collect)
1936 {
1937 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001938 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001939 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001940
1941 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1942 {
1943 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001944 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001945 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001946 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001947 vim_snprintf((char *)IObuff, IOSIZE,
1948 _("Scanning dictionary: %s"), (char *)files[i]);
1949 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1950 }
1951
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001952 if (fp == NULL)
1953 continue;
1954
1955 // Read dictionary file line by line.
1956 // Check each line for a match.
1957 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001958 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001959 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001960 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001961 {
glepnirf31cfa22025-03-06 21:59:13 +01001962 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001963 {
glepnirf31cfa22025-03-06 21:59:13 +01001964 ptr = regmatch->startp[0];
1965 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1966 : find_word_end(ptr);
1967 add_r = ins_compl_add_infercase(regmatch->startp[0],
1968 (int)(ptr - regmatch->startp[0]),
1969 p_ic, files[i], *dir, FALSE, 0);
1970 if (thesaurus)
1971 {
1972 // For a thesaurus, add all the words in the line
1973 ptr = buf;
1974 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1975 regmatch->startp[0]);
1976 }
1977 if (add_r == OK)
1978 // if dir was BACKWARD then honor it just once
1979 *dir = FORWARD;
1980 else if (add_r == FAIL)
1981 break;
1982 // avoid expensive call to vim_regexec() when at end
1983 // of line
1984 if (*ptr == '\n' || got_int)
1985 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001986 }
glepnirf31cfa22025-03-06 21:59:13 +01001987 }
1988 else if (in_fuzzy_collect && leader_len > 0)
1989 {
1990 line_end = find_line_end(ptr);
1991 while (ptr < line_end)
1992 {
1993 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1994 {
1995 char_u *end_ptr = ctrl_x_mode_line_or_eval()
1996 ? find_line_end(ptr) : find_word_end(ptr);
1997 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
1998 p_ic, files[i], *dir, FALSE, score);
1999 if (add_r == FAIL)
2000 break;
2001 ptr = end_ptr; // start from next word
2002 if (compl_get_longest && ctrl_x_mode_normal()
2003 && compl_first_match->cp_next
2004 && score == compl_first_match->cp_next->cp_score)
2005 compl_num_bests++;
2006 }
glepnirf31cfa22025-03-06 21:59:13 +01002007 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002008 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002009 line_breakcheck();
2010 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002011 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002012 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002013 }
2014}
2015
2016/*
2017 * Find the start of the next word.
2018 * Returns a pointer to the first char of the word. Also stops at a NUL.
2019 */
2020 char_u *
2021find_word_start(char_u *ptr)
2022{
2023 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002024 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002025 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2026 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002027 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002028 else
glepnir19e1dd62025-05-08 22:50:38 +02002029 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002030 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2031 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002032 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002033 return ptr;
2034}
2035
2036/*
2037 * Find the end of the word. Assumes it starts inside a word.
2038 * Returns a pointer to just after the word.
2039 */
2040 char_u *
2041find_word_end(char_u *ptr)
2042{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002043 if (has_mbyte)
2044 {
glepnir19e1dd62025-05-08 22:50:38 +02002045 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002046 if (start_class > 1)
2047 while (*ptr != NUL)
2048 {
2049 ptr += (*mb_ptr2len)(ptr);
2050 if (mb_get_class(ptr) != start_class)
2051 break;
2052 }
2053 }
2054 else
2055 while (vim_iswordc(*ptr))
2056 ++ptr;
2057 return ptr;
2058}
2059
2060/*
2061 * Find the end of the line, omitting CR and NL at the end.
2062 * Returns a pointer to just after the line.
2063 */
glepnirdd42b052025-03-08 16:52:55 +01002064 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002065find_line_end(char_u *ptr)
2066{
glepnir19e1dd62025-05-08 22:50:38 +02002067 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002068 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2069 --s;
2070 return s;
2071}
2072
2073/*
Girish Palyacbe53192025-04-14 22:13:15 +02002074 * Free a completion item in the list
2075 */
2076 static void
2077ins_compl_item_free(compl_T *match)
2078{
Girish Palyacbe53192025-04-14 22:13:15 +02002079 VIM_CLEAR_STRING(match->cp_str);
2080 // several entries may use the same fname, free it just once.
2081 if (match->cp_flags & CP_FREE_FNAME)
2082 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002083 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002084 vim_free(match->cp_text[i]);
2085#ifdef FEAT_EVAL
2086 clear_tv(&match->cp_user_data);
2087#endif
2088 vim_free(match);
2089}
2090
2091/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002092 * Free the list of completions
2093 */
2094 static void
2095ins_compl_free(void)
2096{
2097 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098
John Marriott5e6ea922024-11-23 14:01:57 +01002099 VIM_CLEAR_STRING(compl_pattern);
2100 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002101
2102 if (compl_first_match == NULL)
2103 return;
2104
2105 ins_compl_del_pum();
2106 pum_clear();
2107
2108 compl_curr_match = compl_first_match;
2109 do
2110 {
2111 match = compl_curr_match;
2112 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002113 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002114 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002115 compl_first_match = compl_curr_match = NULL;
2116 compl_shown_match = NULL;
2117 compl_old_match = NULL;
2118}
2119
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002120/*
2121 * Reset/clear the completion state.
2122 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002123 void
2124ins_compl_clear(void)
2125{
2126 compl_cont_status = 0;
2127 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002128 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002129 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002130 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002131 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002132 compl_curr_win = NULL;
2133 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002134 VIM_CLEAR_STRING(compl_pattern);
2135 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002136 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002137 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002138 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002139 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002140#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002141 // clear v:completed_item
2142 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002143#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002144}
2145
2146/*
2147 * Return TRUE when Insert completion is active.
2148 */
2149 int
2150ins_compl_active(void)
2151{
2152 return compl_started;
2153}
2154
2155/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002156 * Return True when wp is the actual completion window
2157 */
2158 int
glepnircf7f0122025-04-15 19:02:00 +02002159ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002160{
glepnircf7f0122025-04-15 19:02:00 +02002161 return ins_compl_active() && wp == compl_curr_win
2162 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002163}
2164
2165/*
Girish Palyacbe53192025-04-14 22:13:15 +02002166 * Selected one of the matches. When FALSE, the match was either edited or
2167 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002168 */
2169 int
2170ins_compl_used_match(void)
2171{
2172 return compl_used_match;
2173}
2174
2175/*
2176 * Initialize get longest common string.
2177 */
2178 void
2179ins_compl_init_get_longest(void)
2180{
2181 compl_get_longest = FALSE;
2182}
2183
2184/*
2185 * Returns TRUE when insert completion is interrupted.
2186 */
2187 int
2188ins_compl_interrupted(void)
2189{
2190 return compl_interrupted;
2191}
2192
2193/*
2194 * Returns TRUE if the <Enter> key selects a match in the completion popup
2195 * menu.
2196 */
2197 int
2198ins_compl_enter_selects(void)
2199{
2200 return compl_enter_selects;
2201}
2202
2203/*
2204 * Return the column where the text starts that is being completed
2205 */
2206 colnr_T
2207ins_compl_col(void)
2208{
2209 return compl_col;
2210}
2211
2212/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002213 * Return the length in bytes of the text being completed
2214 */
2215 int
2216ins_compl_len(void)
2217{
2218 return compl_length;
2219}
2220
2221/*
glepnir94a045e2025-03-01 16:12:23 +01002222 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2223 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002224 */
2225 static int
2226ins_compl_has_preinsert(void)
2227{
glepnira2c55592025-02-28 17:43:42 +01002228 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002229 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2230 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002231}
2232
2233/*
2234 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2235 * the `compl_ins_end_col` range.
2236 */
2237 int
2238ins_compl_preinsert_effect(void)
2239{
2240 if (!ins_compl_has_preinsert())
2241 return FALSE;
2242
2243 return curwin->w_cursor.col < compl_ins_end_col;
2244}
2245
2246/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002247 * Delete one character before the cursor and show the subset of the matches
2248 * that match the word that is now before the cursor.
2249 * Returns the character to be used, NUL if the work is done and another char
2250 * to be got from the user.
2251 */
2252 int
2253ins_compl_bs(void)
2254{
2255 char_u *line;
2256 char_u *p;
2257
glepniredd4ac32025-01-29 18:53:51 +01002258 if (ins_compl_preinsert_effect())
2259 ins_compl_delete();
2260
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002261 line = ml_get_curline();
2262 p = line + curwin->w_cursor.col;
2263 MB_PTR_BACK(line, p);
2264
2265 // Stop completion when the whole word was deleted. For Omni completion
2266 // allow the word to be deleted, we won't match everything.
2267 // Respect the 'backspace' option.
2268 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002269 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2270 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002271 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2272 - compl_length < 0))
2273 return K_BS;
2274
2275 // Deleted more than what was used to find matches or didn't finish
2276 // finding all matches: need to look for matches all over again.
2277 if (curwin->w_cursor.col <= compl_col + compl_length
2278 || ins_compl_need_restart())
2279 ins_compl_restart();
2280
John Marriott5e6ea922024-11-23 14:01:57 +01002281 VIM_CLEAR_STRING(compl_leader);
2282 compl_leader.length = (size_t)((p - line) - compl_col);
2283 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2284 if (compl_leader.string == NULL)
2285 {
2286 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002287 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002288 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002289
2290 ins_compl_new_leader();
2291 if (compl_shown_match != NULL)
2292 // Make sure current match is not a hidden item.
2293 compl_curr_match = compl_shown_match;
2294 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002295}
2296
2297/*
2298 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2299 * be called.
2300 */
2301 static int
2302ins_compl_need_restart(void)
2303{
2304 // Return TRUE if we didn't complete finding matches or when the
2305 // 'completefunc' returned "always" in the "refresh" dictionary item.
2306 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002307 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002308 && compl_opt_refresh_always);
2309}
2310
2311/*
2312 * Called after changing "compl_leader".
2313 * Show the popup menu with a different set of matches.
2314 * May also search for matches again if the previous search was interrupted.
2315 */
2316 static void
2317ins_compl_new_leader(void)
2318{
2319 ins_compl_del_pum();
2320 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002321 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002322 compl_used_match = FALSE;
2323
2324 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002325 {
John Marriott5e6ea922024-11-23 14:01:57 +01002326 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002327 if (is_cpt_func_refresh_always())
2328 cpt_compl_refresh();
2329 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002330 else
2331 {
2332#ifdef FEAT_SPELL
2333 spell_bad_len = 0; // need to redetect bad word
2334#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002335 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002336 // the popup menu display the changed text before the cursor. Set
2337 // "compl_restarting" to avoid that the first match is inserted.
2338 pum_call_update_screen();
2339#ifdef FEAT_GUI
2340 if (gui.in_use)
2341 {
2342 // Show the cursor after the match, not after the redrawn text.
2343 setcursor();
2344 out_flush_cursor(FALSE, FALSE);
2345 }
2346#endif
2347 compl_restarting = TRUE;
2348 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2349 compl_cont_status = 0;
2350 compl_restarting = FALSE;
2351 }
2352
Girish Palyab8ee1cf2025-06-08 16:20:06 +02002353 // When 'cot' contains "fuzzy" set the cp_score
2354 if (get_cot_flags() & COT_FUZZY)
2355 set_fuzzy_score();
2356 // Sort the matches linked list based on fuzzy score
2357 int cur_cot_flags = get_cot_flags();
2358 if ((cur_cot_flags & COT_FUZZY) && !(cur_cot_flags & COT_NOSORT))
2359 {
2360 sort_compl_match_list(cp_compare_fuzzy);
2361 if ((cur_cot_flags & COT_NOINSERT) && !(cur_cot_flags & COT_NOSELECT)
2362 && compl_first_match)
2363 {
2364 compl_shown_match = compl_first_match;
2365 if (compl_shows_dir_forward())
2366 compl_shown_match = compl_first_match->cp_next;
2367 }
2368 }
2369
glepnir44180412025-02-20 22:09:48 +01002370 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002371
2372 // Show the popup menu with a different set of matches.
2373 ins_compl_show_pum();
2374
2375 // Don't let Enter select the original text when there is no popup menu.
2376 if (compl_match_array == NULL)
2377 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002378 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2379 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002380}
2381
2382/*
2383 * Return the length of the completion, from the completion start column to
2384 * the cursor column. Making sure it never goes below zero.
2385 */
2386 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002387get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002388{
2389 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002390 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002391}
2392
2393/*
2394 * Append one character to the match leader. May reduce the number of
2395 * matches.
2396 */
2397 void
2398ins_compl_addleader(int c)
2399{
glepnir19e1dd62025-05-08 22:50:38 +02002400 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002401
glepniredd4ac32025-01-29 18:53:51 +01002402 if (ins_compl_preinsert_effect())
2403 ins_compl_delete();
2404
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002405 if (stop_arrow() == FAIL)
2406 return;
2407 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2408 {
2409 char_u buf[MB_MAXBYTES + 1];
2410
2411 (*mb_char2bytes)(c, buf);
2412 buf[cc] = NUL;
2413 ins_char_bytes(buf, cc);
2414 if (compl_opt_refresh_always)
2415 AppendToRedobuff(buf);
2416 }
2417 else
2418 {
2419 ins_char(c);
2420 if (compl_opt_refresh_always)
2421 AppendCharToRedobuff(c);
2422 }
2423
2424 // If we didn't complete finding matches we must search again.
2425 if (ins_compl_need_restart())
2426 ins_compl_restart();
2427
2428 // When 'always' is set, don't reset compl_leader. While completing,
2429 // cursor doesn't point original position, changing compl_leader would
2430 // break redo.
2431 if (!compl_opt_refresh_always)
2432 {
John Marriott5e6ea922024-11-23 14:01:57 +01002433 VIM_CLEAR_STRING(compl_leader);
2434 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2435 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2436 compl_leader.length);
2437 if (compl_leader.string == NULL)
2438 {
2439 compl_leader.length = 0;
2440 return;
2441 }
2442
2443 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002444 }
2445}
2446
2447/*
2448 * Setup for finding completions again without leaving CTRL-X mode. Used when
2449 * BS or a key was typed while still searching for matches.
2450 */
2451 static void
2452ins_compl_restart(void)
2453{
2454 ins_compl_free();
2455 compl_started = FALSE;
2456 compl_matches = 0;
2457 compl_cont_status = 0;
2458 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002459 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002460}
2461
2462/*
2463 * Set the first match, the original text.
2464 */
2465 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002466ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002467{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002468 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002469 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2470 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002471 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002472 {
John Marriott5e6ea922024-11-23 14:01:57 +01002473 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002474 if (p != NULL)
2475 {
John Marriott5e6ea922024-11-23 14:01:57 +01002476 VIM_CLEAR_STRING(compl_first_match->cp_str);
2477 compl_first_match->cp_str.string = p;
2478 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002479 }
2480 }
2481 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002482 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002483 {
John Marriott5e6ea922024-11-23 14:01:57 +01002484 char_u *p = vim_strnsave(str, len);
2485 if (p != NULL)
2486 {
2487 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2488 compl_first_match->cp_prev->cp_str.string = p;
2489 compl_first_match->cp_prev->cp_str.length = len;
2490 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002491 }
2492}
2493
2494/*
2495 * Append one character to the match leader. May reduce the number of
2496 * matches.
2497 */
2498 void
2499ins_compl_addfrommatch(void)
2500{
2501 char_u *p;
2502 int len = (int)curwin->w_cursor.col - (int)compl_col;
2503 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002504
John Marriott5e6ea922024-11-23 14:01:57 +01002505 p = compl_shown_match->cp_str.string;
2506 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002507 {
John Marriott5e6ea922024-11-23 14:01:57 +01002508 size_t plen;
2509 compl_T *cp;
2510
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002511 // When still at the original match use the first entry that matches
2512 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002513 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002514 return;
2515
2516 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002517 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002518 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002519 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002520 {
John Marriott5e6ea922024-11-23 14:01:57 +01002521 if (compl_leader.string == NULL
2522 || ins_compl_equal(cp, compl_leader.string,
2523 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002524 {
John Marriott5e6ea922024-11-23 14:01:57 +01002525 p = cp->cp_str.string;
2526 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002527 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002528 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002529 }
John Marriott5e6ea922024-11-23 14:01:57 +01002530 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002531 return;
2532 }
2533 p += len;
2534 c = PTR2CHAR(p);
2535 ins_compl_addleader(c);
2536}
2537
2538/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002539 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002540 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2541 * compl_cont_mode and compl_cont_status.
2542 * Returns TRUE when the character is not to be inserted.
2543 */
2544 static int
2545set_ctrl_x_mode(int c)
2546{
glepnir05460682025-05-26 18:23:27 +02002547 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002548
2549 switch (c)
2550 {
2551 case Ctrl_E:
2552 case Ctrl_Y:
2553 // scroll the window one line up or down
2554 ctrl_x_mode = CTRL_X_SCROLL;
2555 if (!(State & REPLACE_FLAG))
2556 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2557 else
2558 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2559 edit_submode_pre = NULL;
2560 showmode();
2561 break;
2562 case Ctrl_L:
2563 // complete whole line
2564 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2565 break;
2566 case Ctrl_F:
2567 // complete filenames
2568 ctrl_x_mode = CTRL_X_FILES;
2569 break;
2570 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002571 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002572 ctrl_x_mode = CTRL_X_DICTIONARY;
2573 break;
2574 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002575 // When CTRL-R is followed by '=', don't trigger register completion
2576 // This allows expressions like <C-R>=func()<CR> to work normally
2577 if (vpeekc() == '=')
2578 break;
2579 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002580 break;
2581 case Ctrl_T:
2582 // complete words from a thesaurus
2583 ctrl_x_mode = CTRL_X_THESAURUS;
2584 break;
2585#ifdef FEAT_COMPL_FUNC
2586 case Ctrl_U:
2587 // user defined completion
2588 ctrl_x_mode = CTRL_X_FUNCTION;
2589 break;
2590 case Ctrl_O:
2591 // omni completion
2592 ctrl_x_mode = CTRL_X_OMNI;
2593 break;
2594#endif
2595 case 's':
2596 case Ctrl_S:
2597 // complete spelling suggestions
2598 ctrl_x_mode = CTRL_X_SPELL;
2599#ifdef FEAT_SPELL
2600 ++emsg_off; // Avoid getting the E756 error twice.
2601 spell_back_to_badword();
2602 --emsg_off;
2603#endif
2604 break;
2605 case Ctrl_RSB:
2606 // complete tag names
2607 ctrl_x_mode = CTRL_X_TAGS;
2608 break;
2609#ifdef FEAT_FIND_ID
2610 case Ctrl_I:
2611 case K_S_TAB:
2612 // complete keywords from included files
2613 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2614 break;
2615 case Ctrl_D:
2616 // complete definitions from included files
2617 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2618 break;
2619#endif
2620 case Ctrl_V:
2621 case Ctrl_Q:
2622 // complete vim commands
2623 ctrl_x_mode = CTRL_X_CMDLINE;
2624 break;
2625 case Ctrl_Z:
2626 // stop completion
2627 ctrl_x_mode = CTRL_X_NORMAL;
2628 edit_submode = NULL;
2629 showmode();
2630 retval = TRUE;
2631 break;
2632 case Ctrl_P:
2633 case Ctrl_N:
2634 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2635 // just started ^X mode, or there were enough ^X's to cancel
2636 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2637 // do normal expansion when interrupting a different mode (say
2638 // ^X^F^X^P or ^P^X^X^P, see below)
2639 // nothing changes if interrupting mode 0, (eg, the flag
2640 // doesn't change when going to ADDING mode -- Acevedo
2641 if (!(compl_cont_status & CONT_INTRPT))
2642 compl_cont_status |= CONT_LOCAL;
2643 else if (compl_cont_mode != 0)
2644 compl_cont_status &= ~CONT_LOCAL;
2645 // FALLTHROUGH
2646 default:
2647 // If we have typed at least 2 ^X's... for modes != 0, we set
2648 // compl_cont_status = 0 (eg, as if we had just started ^X
2649 // mode).
2650 // For mode 0, we set "compl_cont_mode" to an impossible
2651 // value, in both cases ^X^X can be used to restart the same
2652 // mode (avoiding ADDING mode).
2653 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2654 // 'complete' and local ^P expansions respectively.
2655 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2656 // mode -- Acevedo
2657 if (c == Ctrl_X)
2658 {
2659 if (compl_cont_mode != 0)
2660 compl_cont_status = 0;
2661 else
2662 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2663 }
2664 ctrl_x_mode = CTRL_X_NORMAL;
2665 edit_submode = NULL;
2666 showmode();
2667 break;
2668 }
2669
2670 return retval;
2671}
2672
2673/*
glepnir1c5a1202024-12-04 20:27:34 +01002674 * Trigger CompleteDone event and adds relevant information to v:event
2675 */
2676 static void
2677trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2678{
2679#if defined(FEAT_EVAL)
2680 save_v_event_T save_v_event;
2681 dict_T *v_event = get_v_event(&save_v_event);
2682 char_u *mode_str = NULL;
2683
2684 mode = mode & ~CTRL_X_WANT_IDENT;
2685 if (ctrl_x_mode_names[mode])
2686 mode_str = (char_u *)ctrl_x_mode_names[mode];
2687
2688 (void)dict_add_string(v_event, "complete_word",
2689 word == NULL ? (char_u *)"" : word);
2690 (void)dict_add_string(v_event, "complete_type",
2691 mode_str != NULL ? mode_str : (char_u *)"");
2692
2693 dict_set_items_ro(v_event);
2694#endif
2695 ins_apply_autocmds(EVENT_COMPLETEDONE);
2696
2697#if defined(FEAT_EVAL)
2698 restore_v_event(v_event, &save_v_event);
2699#endif
2700}
2701
2702/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002703 * Stop insert completion mode
2704 */
2705 static int
2706ins_compl_stop(int c, int prev_mode, int retval)
2707{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002708 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002709 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002710
glepnir84a75032025-03-15 09:59:22 +01002711 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002712 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002713 ins_compl_delete();
2714
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002715 // Get here when we have finished typing a sequence of ^N and
2716 // ^P or other completion characters in CTRL-X mode. Free up
2717 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002718 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002719 {
glepnir40891ba2025-02-10 22:18:00 +01002720 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002721
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002722 // If any of the original typed text has been changed, eg when
2723 // ignorecase is set, we must add back-spaces to the redo
2724 // buffer. We add as few as necessary to delete just the part
2725 // of the original text that has changed.
2726 // When using the longest match, edited the match or used
2727 // CTRL-E then don't use the current match.
2728 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002729 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002730 ins_compl_fixRedoBufForLeader(ptr);
2731 }
2732
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002733 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002734
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002735 // When completing whole lines: fix indent for 'cindent'.
2736 // Otherwise, break line if it's too long.
2737 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2738 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002739 // re-indent the current line
2740 if (want_cindent)
2741 {
2742 do_c_expr_indent();
2743 want_cindent = FALSE; // don't do it again
2744 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002745 }
2746 else
2747 {
2748 int prev_col = curwin->w_cursor.col;
2749
2750 // put the cursor on the last char, for 'tw' formatting
2751 if (prev_col > 0)
2752 dec_cursor();
2753 // only format when something was inserted
2754 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2755 insertchar(NUL, 0, -1);
2756 if (prev_col > 0
2757 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2758 inc_cursor();
2759 }
2760
2761 // If the popup menu is displayed pressing CTRL-Y means accepting
2762 // the selection without inserting anything. When
2763 // compl_enter_selects is set the Enter key does the same.
2764 if ((c == Ctrl_Y || (compl_enter_selects
2765 && (c == CAR || c == K_KENTER || c == NL)))
2766 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002767 {
2768 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002769 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002770 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002771
2772 // CTRL-E means completion is Ended, go back to the typed text.
2773 // but only do this, if the Popup is still visible
2774 if (c == Ctrl_E)
2775 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002776 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002777 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002778
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002779 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002780 if (compl_leader.string != NULL)
2781 {
2782 p = compl_leader.string;
2783 plen = compl_leader.length;
2784 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002785 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002786 {
2787 p = compl_orig_text.string;
2788 plen = compl_orig_text.length;
2789 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002790 if (p != NULL)
2791 {
2792 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002793
John Marriott5e6ea922024-11-23 14:01:57 +01002794 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002795 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002796 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002797 retval = TRUE;
2798 }
2799
2800 auto_format(FALSE, TRUE);
2801
2802 // Trigger the CompleteDonePre event to give scripts a chance to
2803 // act upon the completion before clearing the info, and restore
2804 // ctrl_x_mode, so that complete_info() can be used.
2805 ctrl_x_mode = prev_mode;
2806 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2807
2808 ins_compl_free();
2809 compl_started = FALSE;
2810 compl_matches = 0;
2811 if (!shortmess(SHM_COMPLETIONMENU))
2812 msg_clr_cmdline(); // necessary for "noshowmode"
2813 ctrl_x_mode = CTRL_X_NORMAL;
2814 compl_enter_selects = FALSE;
2815 if (edit_submode != NULL)
2816 {
2817 edit_submode = NULL;
2818 showmode();
2819 }
2820
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002821 if (c == Ctrl_C && cmdwin_type != 0)
2822 // Avoid the popup menu remains displayed when leaving the
2823 // command line window.
2824 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002825 // Indent now if a key was typed that is in 'cinkeys'.
2826 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2827 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002828 // Trigger the CompleteDone event to give scripts a chance to act
2829 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002830 trigger_complete_done_event(prev_mode, word);
2831 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002832
2833 return retval;
2834}
2835
2836/*
glepnircf7f0122025-04-15 19:02:00 +02002837 * Cancel completion.
2838 */
2839 int
2840ins_compl_cancel(void)
2841{
2842 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2843}
2844
2845/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002846 * Prepare for Insert mode completion, or stop it.
2847 * Called just after typing a character in Insert mode.
2848 * Returns TRUE when the character is not to be inserted;
2849 */
2850 int
2851ins_compl_prep(int c)
2852{
glepnir19e1dd62025-05-08 22:50:38 +02002853 int retval = FALSE;
2854 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002855
2856 // Forget any previous 'special' messages if this is actually
2857 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2858 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2859 edit_submode_extra = NULL;
2860
zeertzjq440d4cb2023-03-02 17:51:32 +00002861 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002862 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002863 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002864 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002865 return retval;
2866
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002867#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002868 // Ignore mouse events in a popup window
2869 if (is_mouse_key(c))
2870 {
2871 // Ignore drag and release events, the position does not need to be in
2872 // the popup and it may have just closed.
2873 if (c == K_LEFTRELEASE
2874 || c == K_LEFTRELEASE_NM
2875 || c == K_MIDDLERELEASE
2876 || c == K_RIGHTRELEASE
2877 || c == K_X1RELEASE
2878 || c == K_X2RELEASE
2879 || c == K_LEFTDRAG
2880 || c == K_MIDDLEDRAG
2881 || c == K_RIGHTDRAG
2882 || c == K_X1DRAG
2883 || c == K_X2DRAG)
2884 return retval;
2885 if (popup_visible)
2886 {
2887 int row = mouse_row;
2888 int col = mouse_col;
2889 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2890
2891 if (wp != NULL && WIN_IS_POPUP(wp))
2892 return retval;
2893 }
2894 }
2895#endif
2896
zeertzjqdca29d92021-08-31 19:12:51 +02002897 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2898 {
2899 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2900 || !vim_is_ctrl_x_key(c))
2901 {
2902 // Not starting another completion mode.
2903 ctrl_x_mode = CTRL_X_CMDLINE;
2904
2905 // CTRL-X CTRL-Z should stop completion without inserting anything
2906 if (c == Ctrl_Z)
2907 retval = TRUE;
2908 }
2909 else
2910 {
2911 ctrl_x_mode = CTRL_X_CMDLINE;
2912
2913 // Other CTRL-X keys first stop completion, then start another
2914 // completion mode.
2915 ins_compl_prep(' ');
2916 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2917 }
2918 }
2919
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002920 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002921 if (ctrl_x_mode_not_defined_yet()
2922 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002923 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002924 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002925 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002926 }
2927
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002928 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002929 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2930 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002931 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002932 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002933 {
2934 // We're already in CTRL-X mode, do we stay in it?
2935 if (!vim_is_ctrl_x_key(c))
2936 {
glepnir40891ba2025-02-10 22:18:00 +01002937 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002938 edit_submode = NULL;
2939 }
2940 showmode();
2941 }
2942
2943 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2944 {
2945 // Show error message from attempted keyword completion (probably
2946 // 'Pattern not found') until another key is hit, then go back to
2947 // showing what mode we are in.
2948 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002949 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002950 && c != Ctrl_R && !ins_compl_pum_key(c))
2951 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002952 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002953 }
2954 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2955 // Trigger the CompleteDone event to give scripts a chance to act
2956 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002957 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002958
LemonBoy2bf52dd2022-04-09 18:17:34 +01002959 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002960
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002961 // reset continue_* if we left expansion-mode, if we stay they'll be
2962 // (re)set properly in ins_complete()
2963 if (!vim_is_ctrl_x_key(c))
2964 {
2965 compl_cont_status = 0;
2966 compl_cont_mode = 0;
2967 }
2968
2969 return retval;
2970}
2971
2972/*
2973 * Fix the redo buffer for the completion leader replacing some of the typed
2974 * text. This inserts backspaces and appends the changed text.
2975 * "ptr" is the known leader text or NUL.
2976 */
2977 static void
2978ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2979{
John Marriott5e6ea922024-11-23 14:01:57 +01002980 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002981 char_u *p;
2982 char_u *ptr = ptr_arg;
2983
2984 if (ptr == NULL)
2985 {
John Marriott5e6ea922024-11-23 14:01:57 +01002986 if (compl_leader.string != NULL)
2987 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002988 else
2989 return; // nothing to do
2990 }
John Marriott5e6ea922024-11-23 14:01:57 +01002991 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002992 {
John Marriott5e6ea922024-11-23 14:01:57 +01002993 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002994 // Find length of common prefix between original text and new completion
2995 while (p[len] != NUL && p[len] == ptr[len])
2996 len++;
2997 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002998 if (len > 0)
2999 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01003000 // Add backspace characters for each remaining character in
3001 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003002 for (p += len; *p != NUL; MB_PTR_ADV(p))
3003 AppendCharToRedobuff(K_BS);
3004 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003005 if (ptr != NULL)
3006 AppendToRedobuffLit(ptr + len, -1);
3007}
3008
3009/*
3010 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3011 * (depending on flag) starting from buf and looking for a non-scanned
3012 * buffer (other than curbuf). curbuf is special, if it is called with
3013 * buf=curbuf then it has to be the first call for a given flag/expansion.
3014 *
3015 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3016 */
3017 static buf_T *
3018ins_compl_next_buf(buf_T *buf, int flag)
3019{
glepnir19e1dd62025-05-08 22:50:38 +02003020 static win_T *wp = NULL;
3021 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003022
3023 if (flag == 'w') // just windows
3024 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003025 if (buf == curbuf || !win_valid(wp))
3026 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003027 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003028
3029 while (TRUE)
3030 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003031 // Move to next window (wrap to first window if at the end)
3032 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3033 // Break if we're back at start or found an unscanned buffer
3034 if (wp == curwin || !wp->w_buffer->b_scanned)
3035 break;
glepnir40891ba2025-02-10 22:18:00 +01003036 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003037 buf = wp->w_buffer;
3038 }
3039 else
glepnir40891ba2025-02-10 22:18:00 +01003040 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003041 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3042 // (unlisted buffers)
3043 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003044 while (TRUE)
3045 {
3046 // Move to next buffer (wrap to first buffer if at the end)
3047 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3048 // Break if we're back at start buffer
3049 if (buf == curbuf)
3050 break;
3051
3052 // Check buffer conditions based on flag
3053 if (flag == 'U')
3054 skip_buffer = buf->b_p_bl;
3055 else
3056 skip_buffer = !buf->b_p_bl ||
3057 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3058
3059 // Break if we found a buffer that matches our criteria
3060 if (!skip_buffer && !buf->b_scanned)
3061 break;
3062 }
3063 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003064 return buf;
3065}
3066
3067#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003068
3069# ifdef FEAT_EVAL
3070static callback_T cfu_cb; // 'completefunc' callback function
3071static callback_T ofu_cb; // 'omnifunc' callback function
3072static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3073# endif
3074
3075/*
3076 * Copy a global callback function to a buffer local callback.
3077 */
3078 static void
3079copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3080{
3081 free_callback(bufcb);
3082 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3083 copy_callback(bufcb, globcb);
3084}
3085
3086/*
3087 * Parse the 'completefunc' option value and set the callback function.
3088 * Invoked when the 'completefunc' option is set. The option value can be a
3089 * name of a function (string), or function(<name>) or funcref(<name>) or a
3090 * lambda expression.
3091 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003092 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003093did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003094{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003095 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3096 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003097
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003098 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003099
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003100 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003101}
3102
3103/*
3104 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003105 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003106 */
3107 void
3108set_buflocal_cfu_callback(buf_T *buf UNUSED)
3109{
3110# ifdef FEAT_EVAL
3111 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3112# endif
3113}
3114
3115/*
3116 * Parse the 'omnifunc' option value and set the callback function.
3117 * Invoked when the 'omnifunc' option is set. The option value can be a
3118 * name of a function (string), or function(<name>) or funcref(<name>) or a
3119 * lambda expression.
3120 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003121 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003122did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003123{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003124 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3125 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003126
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003127 set_buflocal_ofu_callback(curbuf);
3128 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003129}
3130
3131/*
3132 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003133 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003134 */
3135 void
3136set_buflocal_ofu_callback(buf_T *buf UNUSED)
3137{
3138# ifdef FEAT_EVAL
3139 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3140# endif
3141}
3142
3143/*
3144 * Parse the 'thesaurusfunc' option value and set the callback function.
3145 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3146 * name of a function (string), or function(<name>) or funcref(<name>) or a
3147 * lambda expression.
3148 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003149 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003150did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003151{
3152 int retval;
3153
zeertzjq6eda2692024-11-03 09:23:33 +01003154 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003155 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003156 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3157 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003158 else
3159 {
3160 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003161 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003162 // when using :set, free the local callback
3163 if (!(args->os_flags & OPT_GLOBAL))
3164 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003165 }
3166
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003167 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003168}
3169
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003170/*
3171 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003172 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003173 */
3174 int
3175set_ref_in_insexpand_funcs(int copyID)
3176{
glepnir19e1dd62025-05-08 22:50:38 +02003177 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003178 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3179 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3180
3181 return abort;
3182}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003183
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003184/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003185 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003186 */
3187 static char_u *
3188get_complete_funcname(int type)
3189{
3190 switch (type)
3191 {
3192 case CTRL_X_FUNCTION:
3193 return curbuf->b_p_cfu;
3194 case CTRL_X_OMNI:
3195 return curbuf->b_p_ofu;
3196 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003197 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003198 default:
3199 return (char_u *)"";
3200 }
3201}
3202
3203/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003204 * Get the callback to use for insert mode completion.
3205 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003206 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003207get_insert_callback(int type)
3208{
3209 if (type == CTRL_X_FUNCTION)
3210 return &curbuf->b_cfu_cb;
3211 if (type == CTRL_X_OMNI)
3212 return &curbuf->b_ofu_cb;
3213 // CTRL_X_THESAURUS
3214 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3215}
3216
3217/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003218 * Execute user defined complete function 'completefunc', 'omnifunc' or
3219 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003220 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3221 * Callback function "cb" is set if triggered by a function in the 'cpt'
3222 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003223 */
3224 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003225expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003226{
3227 list_T *matchlist = NULL;
3228 dict_T *matchdict = NULL;
3229 typval_T args[3];
3230 char_u *funcname;
3231 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003232 typval_T rettv;
3233 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003234 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003235 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003236
Girish Palyacbe53192025-04-14 22:13:15 +02003237 if (!is_cpt_function)
3238 {
3239 funcname = get_complete_funcname(type);
3240 if (*funcname == NUL)
3241 return;
3242 cb = get_insert_callback(type);
3243 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003244
3245 // Call 'completefunc' to obtain the list of matches.
3246 args[0].v_type = VAR_NUMBER;
3247 args[0].vval.v_number = 0;
3248 args[1].v_type = VAR_STRING;
3249 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3250 args[2].v_type = VAR_UNKNOWN;
3251
3252 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003253 // Lock the text to avoid weird things from happening. Also disallow
3254 // switching to another window, it should not be needed and may end up in
3255 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003256 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003257
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003258 retval = call_callback(cb, 0, &rettv, 2, args);
3259
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003260 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003261 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003262 {
3263 switch (rettv.v_type)
3264 {
3265 case VAR_LIST:
3266 matchlist = rettv.vval.v_list;
3267 break;
3268 case VAR_DICT:
3269 matchdict = rettv.vval.v_dict;
3270 break;
3271 case VAR_SPECIAL:
3272 if (rettv.vval.v_number == VVAL_NONE)
3273 compl_opt_suppress_empty = TRUE;
3274 // FALLTHROUGH
3275 default:
3276 // TODO: Give error message?
3277 clear_tv(&rettv);
3278 break;
3279 }
3280 }
zeertzjqcfe45652022-05-27 17:26:55 +01003281 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003282
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003283 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003284 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003285 validate_cursor();
3286 if (!EQUAL_POS(curwin->w_cursor, pos))
3287 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003288 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003289 goto theend;
3290 }
3291
3292 if (matchlist != NULL)
3293 ins_compl_add_list(matchlist);
3294 else if (matchdict != NULL)
3295 ins_compl_add_dict(matchdict);
3296
3297theend:
3298 // Restore State, it might have been changed.
3299 State = save_State;
3300
3301 if (matchdict != NULL)
3302 dict_unref(matchdict);
3303 if (matchlist != NULL)
3304 list_unref(matchlist);
3305}
3306#endif // FEAT_COMPL_FUNC
3307
3308#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003309
3310 static inline int
3311get_user_highlight_attr(char_u *hlname)
3312{
3313 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003314 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003315 return -1;
3316}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003317/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003318 * Add a match to the list of matches from a typeval_T.
3319 * If the given string is already in the list of completions, then return
3320 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3321 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003322 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003323 */
3324 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003325ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003326{
3327 char_u *word;
3328 int dup = FALSE;
3329 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003330 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003331 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003332 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003333 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003334 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003335 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003336 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003337
Bram Moolenaar08928322020-01-04 14:32:48 +01003338 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003339 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3340 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003341 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3342 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3343 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3344 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3345 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003346
glepnir0fe17f82024-10-08 22:26:44 +02003347 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003348 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003349
3350 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003351 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003352
Bram Moolenaard61efa52022-07-23 09:52:04 +01003353 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3354 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3355 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003356 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003357 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3358 dup = dict_get_number(tv->vval.v_dict, "dup");
3359 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3360 empty = dict_get_number(tv->vval.v_dict, "empty");
3361 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3362 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003363 flags |= CP_EQUAL;
3364 }
3365 else
3366 {
3367 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003368 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003369 }
3370 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003371 {
3372 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003373 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003374 }
glepnir508e7852024-07-25 21:39:08 +02003375 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003376 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003377 if (status != OK)
3378 clear_tv(&user_data);
3379 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003380}
3381
3382/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003383 * Add completions from a list.
3384 */
3385 static void
3386ins_compl_add_list(list_T *list)
3387{
3388 listitem_T *li;
3389 int dir = compl_direction;
3390
3391 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003392 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003393 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003394 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003395 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003396 // if dir was BACKWARD then honor it just once
3397 dir = FORWARD;
3398 else if (did_emsg)
3399 break;
3400 }
3401}
3402
3403/*
3404 * Add completions from a dict.
3405 */
3406 static void
3407ins_compl_add_dict(dict_T *dict)
3408{
3409 dictitem_T *di_refresh;
3410 dictitem_T *di_words;
3411
3412 // Check for optional "refresh" item.
3413 compl_opt_refresh_always = FALSE;
3414 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3415 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3416 {
3417 char_u *v = di_refresh->di_tv.vval.v_string;
3418
3419 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3420 compl_opt_refresh_always = TRUE;
3421 }
3422
3423 // Add completions from a "words" list.
3424 di_words = dict_find(dict, (char_u *)"words", 5);
3425 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3426 ins_compl_add_list(di_words->di_tv.vval.v_list);
3427}
3428
3429/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003430 * Start completion for the complete() function.
3431 * "startcol" is where the matched text starts (1 is first column).
3432 * "list" is the list of matches.
3433 */
3434 static void
3435set_completion(colnr_T startcol, list_T *list)
3436{
3437 int save_w_wrow = curwin->w_wrow;
3438 int save_w_leftcol = curwin->w_leftcol;
3439 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003440 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003441 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3442 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3443 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003444
3445 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003446 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003447 ins_compl_prep(' ');
3448 ins_compl_clear();
3449 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003450 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003451
3452 compl_direction = FORWARD;
3453 if (startcol > curwin->w_cursor.col)
3454 startcol = curwin->w_cursor.col;
3455 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003456 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003457 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3458 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003459 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3460 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003461 if (p_ic)
3462 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003463 if (compl_orig_text.string == NULL)
3464 {
3465 compl_orig_text.length = 0;
3466 return;
3467 }
3468 compl_orig_text.length = (size_t)compl_length;
3469 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003470 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3471 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003472 return;
3473
3474 ctrl_x_mode = CTRL_X_EVAL;
3475
3476 ins_compl_add_list(list);
3477 compl_matches = ins_compl_make_cyclic();
3478 compl_started = TRUE;
3479 compl_used_match = TRUE;
3480 compl_cont_status = 0;
3481
3482 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003483 int no_select = compl_no_select || compl_longest;
3484 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003485 {
3486 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003487 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003488 // Down/Up has no real effect.
3489 ins_complete(K_UP, FALSE);
3490 }
3491 else
3492 ins_complete(Ctrl_N, FALSE);
3493 compl_enter_selects = compl_no_insert;
3494
3495 // Lazily show the popup menu, unless we got interrupted.
3496 if (!compl_interrupted)
3497 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003498 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003499 out_flush();
3500}
3501
3502/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003503 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003504 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003505 void
3506f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003507{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003508 if (in_vim9script()
3509 && (check_for_number_arg(argvars, 0) == FAIL
3510 || check_for_list_arg(argvars, 1) == FAIL))
3511 return;
3512
Bram Moolenaar24959102022-05-07 20:01:16 +01003513 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003514 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003515 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003516 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003517 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003518
3519 // Check for undo allowed here, because if something was already inserted
3520 // the line was already saved for undo and this check isn't done.
3521 if (!undo_allowed())
3522 return;
3523
Bram Moolenaard83392a2022-09-01 12:22:46 +01003524 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003525 {
glepnir19e1dd62025-05-08 22:50:38 +02003526 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003527 if (startcol > 0)
3528 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003529 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003530}
3531
3532/*
3533 * "complete_add()" function
3534 */
3535 void
3536f_complete_add(typval_T *argvars, typval_T *rettv)
3537{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003538 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003539 return;
3540
Bram Moolenaar440cf092021-04-03 20:13:30 +02003541 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003542}
3543
3544/*
3545 * "complete_check()" function
3546 */
3547 void
3548f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3549{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003550 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003551 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003552
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003553 ins_compl_check_keys(0, TRUE);
3554 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003555
3556 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003557}
3558
3559/*
glepnirbcd59952025-04-24 21:48:35 +02003560 * Add match item to the return list.
3561 * Returns FAIL if out of memory, OK otherwise.
3562 */
3563 static int
3564add_match_to_list(
3565 typval_T *rettv,
3566 char_u *str,
3567 int len,
3568 int pos)
3569{
3570 list_T *match;
3571 int ret;
3572
3573 match = list_alloc();
3574 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003575 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003576
3577 if ((ret = list_append_number(match, pos + 1)) == FAIL
3578 || (ret = list_append_string(match, str, len)) == FAIL
3579 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3580 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003581 vim_free(match);
3582 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003583 }
3584
3585 return OK;
3586}
3587
3588/*
3589 * "complete_match()" function
3590 */
3591 void
3592f_complete_match(typval_T *argvars, typval_T *rettv)
3593{
3594 linenr_T lnum;
3595 colnr_T col;
3596 char_u *line = NULL;
3597 char_u *ise = NULL;
3598 regmatch_T regmatch;
3599 char_u *before_cursor = NULL;
3600 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003601 int bytepos = 0;
3602 char_u part[MAXPATHL];
3603 int ret;
3604
3605 if (rettv_list_alloc(rettv) == FAIL)
3606 return;
3607
3608 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3609
3610 if (argvars[0].v_type == VAR_UNKNOWN)
3611 {
3612 lnum = curwin->w_cursor.lnum;
3613 col = curwin->w_cursor.col;
3614 }
3615 else if (argvars[1].v_type == VAR_UNKNOWN)
3616 {
3617 emsg(_(e_invalid_argument));
3618 return;
3619 }
3620 else
3621 {
3622 lnum = (linenr_T)tv_get_number(&argvars[0]);
3623 col = (colnr_T)tv_get_number(&argvars[1]);
3624 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3625 {
3626 semsg(_(e_invalid_line_number_nr), lnum);
3627 return;
3628 }
3629 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3630 {
3631 semsg(_(e_invalid_column_number_nr), col + 1);
3632 return;
3633 }
3634 }
3635
3636 line = ml_get_buf(curbuf, lnum, FALSE);
3637 if (line == NULL)
3638 return;
3639
3640 before_cursor = vim_strnsave(line, col);
3641 if (before_cursor == NULL)
3642 return;
3643
3644 if (ise == NULL || *ise == NUL)
3645 {
3646 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3647 if (regmatch.regprog != NULL)
3648 {
3649 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3650 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003651 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003652 regmatch.endp[0] - regmatch.startp[0]);
3653 if (trig == NULL)
3654 {
3655 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003656 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003657 return;
3658 }
3659
Christian Brabandt3accf042025-04-25 19:01:06 +02003660 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003661 ret = add_match_to_list(rettv, trig, -1, bytepos);
3662 vim_free(trig);
3663 if (ret == FAIL)
3664 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003665 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003666 vim_regfree(regmatch.regprog);
3667 return;
3668 }
3669 }
3670 vim_regfree(regmatch.regprog);
3671 }
3672 }
3673 else
3674 {
glepnir08db2f42025-05-14 20:26:19 +02003675 char_u *p = ise;
3676 char_u *p_space = NULL;
3677
glepnirbcd59952025-04-24 21:48:35 +02003678 cur_end = before_cursor + (int)STRLEN(before_cursor);
3679
3680 while (*p != NUL)
3681 {
glepnir8d0e42b2025-05-12 20:28:28 +02003682 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003683 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003684 {
glepnir08db2f42025-05-14 20:26:19 +02003685 len = p - p_space - 1;
3686 memcpy(part, p_space + 1, len);
3687 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003688 }
3689 else
glepnir08db2f42025-05-14 20:26:19 +02003690 {
3691 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3692 if (next_comma && *(next_comma + 1) == ' ')
3693 p_space = next_comma;
3694
glepnir8d0e42b2025-05-12 20:28:28 +02003695 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003696 }
glepnirbcd59952025-04-24 21:48:35 +02003697
3698 if (len > 0 && len <= col)
3699 {
3700 if (STRNCMP(cur_end - len, part, len) == 0)
3701 {
3702 bytepos = col - len;
3703 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3704 {
3705 vim_free(before_cursor);
3706 return;
3707 }
3708 }
3709 }
3710 }
3711 }
3712
3713 vim_free(before_cursor);
3714}
3715
3716/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003717 * Return Insert completion mode name string
3718 */
3719 static char_u *
3720ins_compl_mode(void)
3721{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003722 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003723 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3724
3725 return (char_u *)"";
3726}
3727
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003728/*
3729 * Assign the sequence number to all the completion matches which don't have
3730 * one assigned yet.
3731 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003732 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003733ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003734{
3735 int number = 0;
3736 compl_T *match;
3737
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003738 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003739 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003740 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003741 // This should normally succeed already at the first loop
3742 // cycle, so it's fast!
3743 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003744 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003745 if (match->cp_number != -1)
3746 {
3747 number = match->cp_number;
3748 break;
3749 }
3750 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003751 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003752 for (match = match->cp_next;
3753 match != NULL && match->cp_number == -1;
3754 match = match->cp_next)
3755 match->cp_number = ++number;
3756 }
3757 else // BACKWARD
3758 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003759 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003760 // number. This should normally succeed already at the
3761 // first loop cycle, so it's fast!
3762 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003763 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003764 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003765 if (match->cp_number != -1)
3766 {
3767 number = match->cp_number;
3768 break;
3769 }
glepnir40891ba2025-02-10 22:18:00 +01003770 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003771 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003772 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003773 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003774 for (match = match->cp_prev; match
3775 && match->cp_number == -1;
3776 match = match->cp_prev)
3777 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003778 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003779 }
3780}
3781
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003782/*
glepnir037b0282025-01-16 14:37:44 +01003783 * Fill the dict of complete_info
3784 */
3785 static void
3786fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3787{
3788 dict_add_string(di, "word", match->cp_str.string);
3789 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3790 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3791 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3792 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3793 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003794 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003795 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003796 // Add an empty string for backwards compatibility
3797 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003798 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003799 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003800}
3801
3802/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003803 * Get complete information
3804 */
3805 static void
3806get_complete_info(list_T *what_list, dict_T *retdict)
3807{
3808 int ret = OK;
3809 listitem_T *item;
3810#define CI_WHAT_MODE 0x01
3811#define CI_WHAT_PUM_VISIBLE 0x02
3812#define CI_WHAT_ITEMS 0x04
3813#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003814#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003815#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003816#define CI_WHAT_ALL 0xff
3817 int what_flag;
3818
3819 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003820 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003821 else
3822 {
3823 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003824 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003825 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003826 {
3827 char_u *what = tv_get_string(&item->li_tv);
3828
3829 if (STRCMP(what, "mode") == 0)
3830 what_flag |= CI_WHAT_MODE;
3831 else if (STRCMP(what, "pum_visible") == 0)
3832 what_flag |= CI_WHAT_PUM_VISIBLE;
3833 else if (STRCMP(what, "items") == 0)
3834 what_flag |= CI_WHAT_ITEMS;
3835 else if (STRCMP(what, "selected") == 0)
3836 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003837 else if (STRCMP(what, "completed") == 0)
3838 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003839 else if (STRCMP(what, "matches") == 0)
3840 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003841 }
3842 }
3843
3844 if (ret == OK && (what_flag & CI_WHAT_MODE))
3845 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3846
3847 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3848 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3849
glepnir037b0282025-01-16 14:37:44 +01003850 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3851 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003852 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003853 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003854 dict_T *di;
3855 compl_T *match;
3856 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003857 int has_items = what_flag & CI_WHAT_ITEMS;
3858 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003859 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003860
glepnird4088ed2024-12-31 10:55:22 +01003861 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003862 {
3863 li = list_alloc();
3864 if (li == NULL)
3865 return;
glepnird4088ed2024-12-31 10:55:22 +01003866 ret = dict_add_list(retdict, (has_matches && !has_items)
3867 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003868 }
3869 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3870 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3871 ins_compl_update_sequence_numbers();
3872 if (ret == OK && compl_first_match != NULL)
3873 {
3874 int list_idx = 0;
3875 match = compl_first_match;
3876 do
3877 {
3878 if (!match_at_original_text(match))
3879 {
glepnird4088ed2024-12-31 10:55:22 +01003880 if (has_items
3881 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003882 {
3883 di = dict_alloc();
3884 if (di == NULL)
3885 return;
3886 ret = list_append_dict(li, di);
3887 if (ret != OK)
3888 return;
glepnir037b0282025-01-16 14:37:44 +01003889 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003890 }
glepnird4088ed2024-12-31 10:55:22 +01003891 if (compl_curr_match != NULL
3892 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003893 selected_idx = list_idx;
Girish Palya8cd42a52025-06-05 21:04:29 +02003894 if (match->cp_in_match_array)
Girish Palya0ac1eb32025-04-16 20:18:33 +02003895 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003896 }
3897 match = match->cp_next;
3898 }
3899 while (match != NULL && !is_first_match(match));
3900 }
3901 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3902 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003903
glepnir037b0282025-01-16 14:37:44 +01003904 if (ret == OK && selected_idx != -1 && has_completed)
3905 {
3906 di = dict_alloc();
3907 if (di == NULL)
3908 return;
3909 fill_complete_info_dict(di, compl_curr_match, FALSE);
3910 ret = dict_add_dict(retdict, "completed", di);
3911 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003912 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003913}
3914
3915/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003916 * "complete_info()" function
3917 */
3918 void
3919f_complete_info(typval_T *argvars, typval_T *rettv)
3920{
3921 list_T *what_list = NULL;
3922
Bram Moolenaar93a10962022-06-16 11:42:09 +01003923 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003924 return;
3925
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003926 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3927 return;
3928
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003929 if (argvars[0].v_type != VAR_UNKNOWN)
3930 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003931 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003932 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003933 what_list = argvars[0].vval.v_list;
3934 }
3935 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003936}
3937#endif
3938
3939/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003940 * Returns TRUE when using a user-defined function for thesaurus completion.
3941 */
3942 static int
3943thesaurus_func_complete(int type UNUSED)
3944{
3945#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003946 return type == CTRL_X_THESAURUS
3947 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003948#else
3949 return FALSE;
3950#endif
3951}
3952
3953/*
Girish Palya7c621052025-05-26 19:41:59 +02003954 * Check if 'cpt' list index can be advanced to the next completion source.
3955 */
3956 static int
3957may_advance_cpt_index(char_u *cpt)
3958{
3959 char_u *p = cpt;
3960
Girish Palya98c29db2025-06-01 19:40:00 +02003961 if (cpt_sources_index == -1)
3962 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02003963 while (*p == ',' || *p == ' ') // Skip delimiters
3964 p++;
3965 return (*p != NUL);
3966}
3967
3968/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003969 * Return value of process_next_cpt_value()
3970 */
3971enum
3972{
3973 INS_COMPL_CPT_OK = 1,
3974 INS_COMPL_CPT_CONT,
3975 INS_COMPL_CPT_END
3976};
3977
3978/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003979 * state information used for getting the next set of insert completion
3980 * matches.
3981 */
3982typedef struct
3983{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003984 char_u *e_cpt_copy; // copy of 'complete'
3985 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003986 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003987 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003988 pos_T prev_match_pos; // previous match position
3989 int set_match_pos; // save first_match_pos/last_match_pos
3990 pos_T first_match_pos; // first match position
3991 pos_T last_match_pos; // last match position
3992 int found_all; // found all matches of a certain type.
3993 char_u *dict; // dictionary file to search
3994 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003995 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003996} ins_compl_next_state_T;
3997
3998/*
3999 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004000 *
4001 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004002 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004003 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004004 * st->found_all - all matches of this type are found
4005 * st->ins_buf - search for completions in this buffer
4006 * st->first_match_pos - position of the first completion match
4007 * st->last_match_pos - position of the last completion match
4008 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004009 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004010 * st->dict - name of the dictionary or thesaurus file to search
4011 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004012 *
4013 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004014 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4015 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004016 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004017 */
4018 static int
4019process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004020 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004021 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004022 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004023 int fuzzy_collect,
4024 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004025{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004026 int compl_type = -1;
4027 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004028
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004029 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004030 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004031
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004032 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4033 st->e_cpt++;
4034
4035 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004036 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004037 st->ins_buf = curbuf;
4038 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004039 // Move the cursor back one character so that ^N can match the
4040 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004041 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004042 {
4043 // Move the cursor to after the last character in the
4044 // buffer, so that word at start of buffer is found
4045 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004046 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004047 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004048 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004049 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004050 compl_type = 0;
4051
4052 // Remember the first match so that the loop stops when we
4053 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004054 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004055 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004056 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004057 && (st->ins_buf = ins_compl_next_buf(
4058 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004059 {
4060 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004061 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004062 {
4063 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004064 st->first_match_pos.col = st->last_match_pos.col = 0;
4065 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4066 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004067 compl_type = 0;
4068 }
4069 else // unloaded buffer, scan like dictionary
4070 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071 st->found_all = TRUE;
4072 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004073 {
4074 status = INS_COMPL_CPT_CONT;
4075 goto done;
4076 }
4077 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004078 st->dict = st->ins_buf->b_fname;
4079 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004080 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004081 if (!shortmess(SHM_COMPLETIONSCAN))
4082 {
4083 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4084 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4085 st->ins_buf->b_fname == NULL
4086 ? buf_spname(st->ins_buf)
4087 : st->ins_buf->b_sfname == NULL
4088 ? st->ins_buf->b_fname
4089 : st->ins_buf->b_sfname);
4090 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4091 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004092 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004093 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004094 status = INS_COMPL_CPT_END;
4095 else
4096 {
4097 if (ctrl_x_mode_line_or_eval())
4098 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004099 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004100 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004101 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004102 compl_type = CTRL_X_DICTIONARY;
4103 else
4104 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004105 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004106 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004107 st->dict = st->e_cpt;
4108 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004109 }
4110 }
Girish Palyacbe53192025-04-14 22:13:15 +02004111#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004112 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004113 {
4114 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004115 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004116 if (!st->func_cb)
4117 compl_type = -1;
4118 }
4119#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004120#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004121 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004122 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004123 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124 compl_type = CTRL_X_PATH_DEFINES;
4125#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004126 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004127 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004128 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004129 if (!shortmess(SHM_COMPLETIONSCAN))
4130 {
4131 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4132 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4133 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4134 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004135 }
4136 else
4137 compl_type = -1;
4138
4139 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004140 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004141 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004142
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004143 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004144 if (compl_type == -1)
4145 status = INS_COMPL_CPT_CONT;
4146 }
4147
4148done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004149 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004150 return status;
4151}
4152
4153#ifdef FEAT_FIND_ID
4154/*
4155 * Get the next set of identifiers or defines matching "compl_pattern" in
4156 * included files.
4157 */
4158 static void
4159get_next_include_file_completion(int compl_type)
4160{
John Marriott5e6ea922024-11-23 14:01:57 +01004161 find_pattern_in_path(compl_pattern.string, compl_direction,
4162 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004163 (compl_type == CTRL_X_PATH_DEFINES
4164 && !(compl_cont_status & CONT_SOL))
4165 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004166 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004167}
4168#endif
4169
4170/*
4171 * Get the next set of words matching "compl_pattern" in dictionary or
4172 * thesaurus files.
4173 */
4174 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004175get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004176{
4177#ifdef FEAT_COMPL_FUNC
4178 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004179 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004180 else
4181#endif
4182 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004183 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004184 : (compl_type == CTRL_X_THESAURUS
4185 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4186 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004187 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004188 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004189 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004190}
4191
4192/*
4193 * Get the next set of tag names matching "compl_pattern".
4194 */
4195 static void
4196get_next_tag_completion(void)
4197{
4198 int save_p_ic;
4199 char_u **matches;
4200 int num_matches;
4201
4202 // set p_ic according to p_ic, p_scs and pat for find_tags().
4203 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004204 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004205
4206 // Find up to TAG_MANY matches. Avoids that an enormous number
4207 // of matches is found when compl_pattern is empty
4208 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004209 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004210 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004211 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004212 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4213 ins_compl_add_matches(num_matches, matches, p_ic);
4214 g_tag_at_cursor = FALSE;
4215 p_ic = save_p_ic;
4216}
4217
4218/*
glepnir8159fb12024-07-17 20:32:54 +02004219 * Compare function for qsort
4220 */
glepnirf31cfa22025-03-06 21:59:13 +01004221 static int
4222compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004223{
4224 int idx_a = *(const int *)a;
4225 int idx_b = *(const int *)b;
4226 int score_a = compl_fuzzy_scores[idx_a];
4227 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004228 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4229 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004230}
4231
4232/*
glepnirf31cfa22025-03-06 21:59:13 +01004233 * insert prefix with redraw
4234 */
4235 static void
4236ins_compl_longest_insert(char_u *prefix)
4237{
4238 ins_compl_delete();
4239 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4240 ins_redraw(FALSE);
4241}
4242
4243/*
4244 * Calculate the longest common prefix among the best fuzzy matches
4245 * stored in compl_best_matches, and insert it as the longest.
4246 */
4247 static void
4248fuzzy_longest_match(void)
4249{
4250 char_u *prefix = NULL;
4251 int prefix_len = 0;
4252 int i = 0;
4253 int j = 0;
4254 char_u *match_str = NULL;
4255 char_u *prefix_ptr = NULL;
4256 char_u *match_ptr = NULL;
4257 char_u *leader = NULL;
4258 size_t leader_len = 0;
4259 compl_T *compl = NULL;
4260 int more_candidates = FALSE;
4261 compl_T *nn_compl = NULL;
4262
4263 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004264 return;
glepnirf31cfa22025-03-06 21:59:13 +01004265
4266 nn_compl = compl_first_match->cp_next->cp_next;
4267 if (nn_compl && nn_compl != compl_first_match)
4268 more_candidates = TRUE;
4269
4270 compl = ctrl_x_mode_whole_line() ? compl_first_match
4271 : compl_first_match->cp_next;
4272 if (compl_num_bests == 1)
4273 {
4274 // no more candidates insert the match str
4275 if (!more_candidates)
4276 {
4277 ins_compl_longest_insert(compl->cp_str.string);
4278 compl_num_bests = 0;
4279 }
4280 compl_num_bests = 0;
4281 return;
4282 }
4283
4284 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4285 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004286 return;
glepnirf31cfa22025-03-06 21:59:13 +01004287 while (compl != NULL && i < compl_num_bests)
4288 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004289 compl_best_matches[i] = compl;
4290 compl = compl->cp_next;
4291 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004292 }
4293
4294 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004295 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004296
4297 for (i = 1; i < compl_num_bests; i++)
4298 {
4299 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004300 prefix_ptr = prefix;
4301 match_ptr = match_str;
4302 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004303
4304 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4305 {
4306 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4307 break;
4308
4309 MB_PTR_ADV(prefix_ptr);
4310 MB_PTR_ADV(match_ptr);
4311 j++;
4312 }
4313
4314 if (j > 0)
4315 prefix_len = j;
4316 }
4317
4318 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004319 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004320
4321 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004322 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004323 goto end;
4324
zeertzjq4422de62025-03-07 19:06:02 +01004325 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004326 if (prefix != NULL)
4327 {
4328 ins_compl_longest_insert(prefix);
4329 compl_cfc_longest_ins = TRUE;
4330 vim_free(prefix);
4331 }
4332
4333end:
4334 vim_free(compl_best_matches);
4335 compl_best_matches = NULL;
4336 compl_num_bests = 0;
4337}
4338
4339/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004340 * Get the next set of filename matching "compl_pattern".
4341 */
4342 static void
4343get_next_filename_completion(void)
4344{
4345 char_u **matches;
4346 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004347 char_u *ptr;
4348 garray_T fuzzy_indices;
4349 int i;
4350 int score;
4351 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004352 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004353 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004354 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004355 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004356 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4357 int max_score = 0;
4358 int current_score = 0;
4359 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004360
glepnirb9de1a02024-08-02 19:14:38 +02004361#ifdef BACKSLASH_IN_FILENAME
4362 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4363 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4364#else
4365 char pathsep = PATHSEP;
4366#endif
4367
glepnirf31cfa22025-03-06 21:59:13 +01004368 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004369 {
glepnirb9de1a02024-08-02 19:14:38 +02004370#ifdef BACKSLASH_IN_FILENAME
4371 if (curbuf->b_p_csl[0] == 's')
4372 {
John Marriott5e6ea922024-11-23 14:01:57 +01004373 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004374 {
4375 if (leader[i] == '\\')
4376 leader[i] = '/';
4377 }
4378 }
4379 else if (curbuf->b_p_csl[0] == 'b')
4380 {
John Marriott5e6ea922024-11-23 14:01:57 +01004381 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004382 {
4383 if (leader[i] == '/')
4384 leader[i] = '\\';
4385 }
4386 }
4387#endif
4388 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004389 if (last_sep == NULL)
4390 {
4391 // No path separator or separator is the last character,
4392 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004393 VIM_CLEAR_STRING(compl_pattern);
4394 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4395 if (compl_pattern.string == NULL)
4396 return;
4397 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004398 }
4399 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004400 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004401 else
4402 {
4403 // Split leader into path and file parts
4404 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004405 char_u *path_with_wildcard;
4406
4407 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004408 if (path_with_wildcard != NULL)
4409 {
John Marriott5e6ea922024-11-23 14:01:57 +01004410 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4411 VIM_CLEAR_STRING(compl_pattern);
4412 compl_pattern.string = path_with_wildcard;
4413 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004414
4415 // Move leader to the file part
4416 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004417 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004418 }
4419 }
glepnir8159fb12024-07-17 20:32:54 +02004420 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004421
John Marriott5e6ea922024-11-23 14:01:57 +01004422 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004423 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4424 return;
4425
4426 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004427 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004428#ifdef BACKSLASH_IN_FILENAME
4429 if (curbuf->b_p_csl[0] != NUL)
4430 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004431 for (i = 0; i < num_matches; ++i)
4432 {
glepnir8159fb12024-07-17 20:32:54 +02004433 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004434 while (*ptr != NUL)
4435 {
4436 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4437 *ptr = '/';
4438 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4439 *ptr = '\\';
4440 ptr += (*mb_ptr2len)(ptr);
4441 }
4442 }
4443 }
4444#endif
glepnir8159fb12024-07-17 20:32:54 +02004445
glepnirf31cfa22025-03-06 21:59:13 +01004446 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004447 {
4448 ga_init2(&fuzzy_indices, sizeof(int), 10);
4449 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4450
4451 for (i = 0; i < num_matches; i++)
4452 {
4453 ptr = matches[i];
4454 score = fuzzy_match_str(ptr, leader);
4455 if (score > 0)
4456 {
4457 if (ga_grow(&fuzzy_indices, 1) == OK)
4458 {
4459 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4460 compl_fuzzy_scores[i] = score;
4461 fuzzy_indices.ga_len++;
4462 }
4463 }
4464 }
4465
Christian Brabandt220474d2024-07-20 13:26:44 +02004466 // prevent qsort from deref NULL pointer
4467 if (fuzzy_indices.ga_len > 0)
4468 {
glepnirf31cfa22025-03-06 21:59:13 +01004469 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004470 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4471 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004472
Christian Brabandt220474d2024-07-20 13:26:44 +02004473 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004474 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004475 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004476 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4477 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004478 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4479 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004480 dir = FORWARD;
4481
4482 if (need_collect_bests)
4483 {
4484 if (i == 0 || current_score == max_score)
4485 {
4486 compl_num_bests++;
4487 max_score = current_score;
4488 }
4489 }
4490 }
glepnir8159fb12024-07-17 20:32:54 +02004491
Christian Brabandt220474d2024-07-20 13:26:44 +02004492 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004493 }
glepnir6b6280c2024-07-27 16:25:45 +02004494 else if (leader_len > 0)
4495 {
4496 FreeWild(num_matches, matches);
4497 num_matches = 0;
4498 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004499
glepnir8159fb12024-07-17 20:32:54 +02004500 vim_free(compl_fuzzy_scores);
4501 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004502
4503 if (compl_num_bests > 0 && compl_get_longest)
4504 fuzzy_longest_match();
4505 return;
glepnir8159fb12024-07-17 20:32:54 +02004506 }
4507
glepnir6b6280c2024-07-27 16:25:45 +02004508 if (num_matches > 0)
4509 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004510}
4511
4512/*
4513 * Get the next set of command-line completions matching "compl_pattern".
4514 */
4515 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004516get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004517{
4518 char_u **matches;
4519 int num_matches;
4520
John Marriott5e6ea922024-11-23 14:01:57 +01004521 if (expand_cmdline(&compl_xp, compl_pattern.string,
4522 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004523 ins_compl_add_matches(num_matches, matches, FALSE);
4524}
4525
4526/*
4527 * Get the next set of spell suggestions matching "compl_pattern".
4528 */
4529 static void
4530get_next_spell_completion(linenr_T lnum UNUSED)
4531{
4532#ifdef FEAT_SPELL
4533 char_u **matches;
4534 int num_matches;
4535
John Marriott5e6ea922024-11-23 14:01:57 +01004536 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004537 if (num_matches > 0)
4538 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004539 else
4540 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004541#endif
4542}
4543
4544/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004545 * Return the next word or line from buffer "ins_buf" at position
4546 * "cur_match_pos" for completion. The length of the match is set in "len".
4547 */
4548 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004549ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004550 buf_T *ins_buf, // buffer being scanned
4551 pos_T *cur_match_pos, // current match position
4552 int *match_len,
4553 int *cont_s_ipos) // next ^X<> will set initial_pos
4554{
4555 char_u *ptr;
4556 int len;
4557
4558 *match_len = 0;
4559 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4560 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004561 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004562 if (ctrl_x_mode_line_or_eval())
4563 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004564 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004565 {
4566 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4567 return NULL;
4568 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004569 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004570 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004571 {
4572 char_u *tmp_ptr = ptr;
4573
4574 ptr = skipwhite(tmp_ptr);
4575 len -= (int)(ptr - tmp_ptr);
4576 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004577 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004578 }
4579 else
4580 {
4581 char_u *tmp_ptr = ptr;
4582
John Marriott5e6ea922024-11-23 14:01:57 +01004583 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004584 {
4585 tmp_ptr += compl_length;
4586 // Skip if already inside a word.
4587 if (vim_iswordp(tmp_ptr))
4588 return NULL;
4589 // Find start of next word.
4590 tmp_ptr = find_word_start(tmp_ptr);
4591 }
4592 // Find end of this word.
4593 tmp_ptr = find_word_end(tmp_ptr);
4594 len = (int)(tmp_ptr - ptr);
4595
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004596 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004597 {
4598 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4599 {
4600 // Try next line, if any. the new word will be
4601 // "join" as if the normal command "J" was used.
4602 // IOSIZE is always greater than
4603 // compl_length, so the next STRNCPY always
4604 // works -- Acevedo
4605 STRNCPY(IObuff, ptr, len);
4606 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4607 tmp_ptr = ptr = skipwhite(ptr);
4608 // Find start of next word.
4609 tmp_ptr = find_word_start(tmp_ptr);
4610 // Find end of next word.
4611 tmp_ptr = find_word_end(tmp_ptr);
4612 if (tmp_ptr > ptr)
4613 {
4614 if (*ptr != ')' && IObuff[len - 1] != TAB)
4615 {
4616 if (IObuff[len - 1] != ' ')
4617 IObuff[len++] = ' ';
4618 // IObuf =~ "\k.* ", thus len >= 2
4619 if (p_js
4620 && (IObuff[len - 2] == '.'
4621 || (vim_strchr(p_cpo, CPO_JOINSP)
4622 == NULL
4623 && (IObuff[len - 2] == '?'
4624 || IObuff[len - 2] == '!'))))
4625 IObuff[len++] = ' ';
4626 }
4627 // copy as much as possible of the new word
4628 if (tmp_ptr - ptr >= IOSIZE - len)
4629 tmp_ptr = ptr + IOSIZE - len - 1;
4630 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4631 len += (int)(tmp_ptr - ptr);
4632 *cont_s_ipos = TRUE;
4633 }
4634 IObuff[len] = NUL;
4635 ptr = IObuff;
4636 }
4637 if (len == compl_length)
4638 return NULL;
4639 }
4640 }
4641
4642 *match_len = len;
4643 return ptr;
4644}
4645
4646/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004647 * Get the next set of words matching "compl_pattern" for default completion(s)
4648 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004649 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4650 * position "st->start_pos" in the "compl_direction" direction. If
4651 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4652 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004653 * Returns OK if a new next match is found, otherwise returns FAIL.
4654 */
4655 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004656get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004657{
4658 int found_new_match = FAIL;
4659 int save_p_scs;
4660 int save_p_ws;
4661 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004662 char_u *ptr = NULL;
4663 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004664 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004665 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004666 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004667 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004668
4669 // If 'infercase' is set, don't use 'smartcase' here
4670 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004671 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004672 p_scs = FALSE;
4673
4674 // Buffers other than curbuf are scanned from the beginning or the
4675 // end but never from the middle, thus setting nowrapscan in this
4676 // buffer is a good idea, on the other hand, we always set
4677 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4678 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004679 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004680 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004681 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004682 p_ws = TRUE;
4683 looped_around = FALSE;
4684 for (;;)
4685 {
4686 int cont_s_ipos = FALSE;
4687
4688 ++msg_silent; // Don't want messages for wrapscan.
4689
glepnirf31cfa22025-03-06 21:59:13 +01004690 if (in_collect)
4691 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004692 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004693 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004694 start_pos, &len, &ptr, &score);
4695 }
4696 // ctrl_x_mode_line_or_eval() || word-wise search that
4697 // has added a word that was at the beginning of the line
4698 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4699 found_new_match = search_for_exact_line(st->ins_buf,
4700 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004701 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004702 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004703 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004704 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004705 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004706 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004707 {
4708 // set "compl_started" even on fail
4709 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004710 st->first_match_pos = *st->cur_match_pos;
4711 st->last_match_pos = *st->cur_match_pos;
4712 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004713 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004714 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4715 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004716 {
4717 found_new_match = FAIL;
4718 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004719 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004720 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4721 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4722 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004723 {
4724 if (looped_around)
4725 found_new_match = FAIL;
4726 else
4727 looped_around = TRUE;
4728 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004729 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004730 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4731 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4732 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004733 {
4734 if (looped_around)
4735 found_new_match = FAIL;
4736 else
4737 looped_around = TRUE;
4738 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004739 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004740 if (found_new_match == FAIL)
4741 break;
4742
4743 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004744 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004745 && start_pos->lnum == st->cur_match_pos->lnum
4746 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004747 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004748
glepnirf31cfa22025-03-06 21:59:13 +01004749 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004750 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4751 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004752 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004753 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004754
Girish Palyab1565882025-04-15 20:16:00 +02004755 if (is_nearest_active() && in_curbuf)
4756 {
4757 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4758 if (score < 0)
4759 score = -score;
4760 score++;
4761 }
4762
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004763 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004764 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004765 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004766 {
glepnirf31cfa22025-03-06 21:59:13 +01004767 if (in_collect && score == compl_first_match->cp_next->cp_score)
4768 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004769 found_new_match = OK;
4770 break;
4771 }
4772 }
4773 p_scs = save_p_scs;
4774 p_ws = save_p_ws;
4775
4776 return found_new_match;
4777}
4778
Girish Palyacbe53192025-04-14 22:13:15 +02004779#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004780/*
4781 * Return the callback function associated with "p" if it points to a
4782 * userfunc.
4783 */
Girish Palyacbe53192025-04-14 22:13:15 +02004784 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004785get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004786{
4787 static callback_T cb;
4788 char_u buf[LSIZE];
4789 int slen;
4790
Girish Palya98c29db2025-06-01 19:40:00 +02004791 if (*p == 'o')
4792 return &curbuf->b_ofu_cb;
4793 if (*p == 'F')
4794 {
4795 if (*++p != ',' && *p != NUL)
4796 {
4797 free_callback(&cb);
4798 slen = copy_option_part(&p, buf, LSIZE, ",");
4799 if (slen > 0 && option_set_callback_func(buf, &cb))
4800 return &cb;
4801 return NULL;
4802 }
4803 else
4804 return &curbuf->b_cfu_cb;
4805 }
Girish Palyacbe53192025-04-14 22:13:15 +02004806 return NULL;
4807}
4808
4809/*
4810 * Retrieve new completion matches by invoking callback "cb".
4811 */
4812 static void
4813expand_cpt_function(callback_T *cb)
4814{
4815 // Re-insert the text removed by ins_compl_delete().
4816 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4817 // Get matches
4818 get_cpt_func_completion_matches(cb);
4819 // Undo insertion
4820 ins_compl_delete();
4821}
4822#endif
4823
4824/*
glepnir05460682025-05-26 18:23:27 +02004825 * Get completion matches from register contents.
4826 * Extracts words from all available registers and adds them to the completion list.
4827 */
4828 static void
4829get_register_completion(void)
4830{
4831 int dir = compl_direction;
4832 yankreg_T *reg = NULL;
4833 void *reg_ptr = NULL;
glepnir86d46a72025-06-03 21:04:44 +02004834 int adding_mode = compl_status_adding();
glepnir05460682025-05-26 18:23:27 +02004835
4836 for (int i = 0; i < NUM_REGISTERS; i++)
4837 {
4838 int regname = 0;
glepnir05460682025-05-26 18:23:27 +02004839 if (i == 0)
4840 regname = '"'; // unnamed register
4841 else if (i < 10)
4842 regname = '0' + i;
4843 else if (i == DELETION_REGISTER)
4844 regname = '-';
4845#ifdef FEAT_CLIPBOARD
4846 else if (i == STAR_REGISTER)
4847 regname = '*';
4848 else if (i == PLUS_REGISTER)
4849 regname = '+';
4850#endif
4851 else
4852 regname = 'a' + i - 10;
4853
4854 // Skip invalid or black hole register
4855 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4856 continue;
4857
4858 reg_ptr = get_register(regname, FALSE);
4859 if (reg_ptr == NULL)
4860 continue;
4861
4862 reg = (yankreg_T *)reg_ptr;
4863
glepnir86d46a72025-06-03 21:04:44 +02004864 for (int j = 0; j < reg->y_size; j++)
glepnir05460682025-05-26 18:23:27 +02004865 {
glepnir86d46a72025-06-03 21:04:44 +02004866 char_u *str = reg->y_array[j].string;
4867 if (str == NULL)
4868 continue;
glepnir05460682025-05-26 18:23:27 +02004869
glepnir86d46a72025-06-03 21:04:44 +02004870 if (adding_mode)
4871 {
glepnird5fdfa52025-06-02 19:45:41 +02004872 int str_len = (int)STRLEN(str);
4873 if (str_len == 0)
4874 continue;
glepnir05460682025-05-26 18:23:27 +02004875
glepnird5fdfa52025-06-02 19:45:41 +02004876 if (!compl_orig_text.string
4877 || (p_ic ? STRNICMP(str, compl_orig_text.string,
4878 compl_orig_text.length) == 0
4879 : STRNCMP(str, compl_orig_text.string,
4880 compl_orig_text.length) == 0))
glepnir05460682025-05-26 18:23:27 +02004881 {
glepnir86d46a72025-06-03 21:04:44 +02004882 if (ins_compl_add_infercase(str, str_len, p_ic, NULL,
4883 dir, FALSE, 0) == OK)
glepnir05460682025-05-26 18:23:27 +02004884 dir = FORWARD;
4885 }
glepnird5fdfa52025-06-02 19:45:41 +02004886 }
glepnir86d46a72025-06-03 21:04:44 +02004887 else
glepnird5fdfa52025-06-02 19:45:41 +02004888 {
glepnird5fdfa52025-06-02 19:45:41 +02004889 // Calculate the safe end of string to avoid null byte issues
4890 char_u *str_end = str + STRLEN(str);
4891 char_u *p = str;
4892
4893 // Safely iterate through the string
4894 while (p < str_end && *p != NUL)
4895 {
4896 char_u *old_p = p;
4897 p = find_word_start(p);
4898 if (p >= str_end || *p == NUL)
4899 break;
4900
4901 char_u *word_end = find_word_end(p);
4902
4903 if (word_end <= p)
4904 {
4905 if (has_mbyte)
4906 word_end = p + (*mb_ptr2len)(p);
4907 else
4908 word_end = p + 1;
4909 }
4910
4911 if (word_end > str_end)
4912 word_end = str_end;
4913
4914 int len = (int)(word_end - p);
4915 if (len > 0 && (!compl_orig_text.string
4916 || (p_ic ? STRNICMP(p, compl_orig_text.string,
4917 compl_orig_text.length) == 0
4918 : STRNCMP(p, compl_orig_text.string,
4919 compl_orig_text.length) == 0)))
4920 {
4921 if (ins_compl_add_infercase(p, len, p_ic, NULL,
4922 dir, FALSE, 0) == OK)
4923 dir = FORWARD;
4924 }
4925
4926 p = word_end;
4927
4928 if (p <= old_p)
4929 {
4930 p = old_p + 1;
4931 if (has_mbyte && p < str_end)
4932 p = old_p + (*mb_ptr2len)(old_p);
4933 }
4934 }
glepnir05460682025-05-26 18:23:27 +02004935 }
4936 }
4937
4938 // Free the register copy
4939 put_register(regname, reg_ptr);
4940 }
4941}
4942
4943/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004944 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004945 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004946 */
4947 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004948get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004949{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004950 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004951
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004952 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004953 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004954 case -1:
4955 break;
4956#ifdef FEAT_FIND_ID
4957 case CTRL_X_PATH_PATTERNS:
4958 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004959 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004960 break;
4961#endif
4962
4963 case CTRL_X_DICTIONARY:
4964 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004965 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4966 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004967 break;
4968
4969 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004970 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004971 break;
4972
4973 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004974 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004975 break;
4976
4977 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004978 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004979 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004980 break;
4981
4982#ifdef FEAT_COMPL_FUNC
4983 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004984 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4985 expand_cpt_function(st->func_cb);
4986 else
4987 expand_by_function(type, compl_pattern.string, NULL);
4988 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004989 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004990 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004991 break;
4992#endif
4993
4994 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004995 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004996 break;
4997
glepnir05460682025-05-26 18:23:27 +02004998 case CTRL_X_REGISTER:
4999 get_register_completion();
5000 break;
5001
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005002 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005003 found_new_match = get_next_default_completion(st, ini);
5004 if (found_new_match == FAIL && st->ins_buf == curbuf)
5005 st->found_all = TRUE;
5006 }
5007
5008 // check if compl_curr_match has changed, (e.g. other type of
5009 // expansion added something)
5010 if (type != 0 && compl_curr_match != compl_old_match)
5011 found_new_match = OK;
5012
5013 return found_new_match;
5014}
5015
5016/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005017 * Strips carets followed by numbers. This suffix typically represents the
5018 * max_matches setting.
5019 */
5020 static void
5021strip_caret_numbers_in_place(char_u *str)
5022{
5023 char_u *read = str, *write = str, *p;
5024
5025 if (str == NULL)
5026 return;
5027
5028 while (*read)
5029 {
5030 if (*read == '^')
5031 {
5032 p = read + 1;
5033 while (vim_isdigit(*p))
5034 p++;
5035 if ((*p == ',' || *p == '\0') && p != read + 1)
5036 {
5037 read = p;
5038 continue;
5039 }
5040 else
5041 *write++ = *read++;
5042 }
5043 else
5044 *write++ = *read++;
5045 }
5046 *write = '\0';
5047}
5048
5049/*
Girish Palya98c29db2025-06-01 19:40:00 +02005050 * Call functions specified in the 'cpt' option with findstart=1,
5051 * and retrieve the startcol.
5052 */
5053 static void
5054prepare_cpt_compl_funcs(void)
5055{
5056#ifdef FEAT_COMPL_FUNC
5057 char_u *cpt;
5058 char_u *p;
5059 callback_T *cb = NULL;
5060 int idx = 0;
5061 int startcol;
5062
5063 // Make a copy of 'cpt' in case the buffer gets wiped out
5064 cpt = vim_strsave(curbuf->b_p_cpt);
5065 strip_caret_numbers_in_place(cpt);
5066
5067 // Re-insert the text removed by ins_compl_delete().
5068 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5069
5070 for (p = cpt; *p;)
5071 {
5072 while (*p == ',' || *p == ' ') // Skip delimiters
5073 p++;
5074 cb = get_callback_if_cpt_func(p);
5075 if (cb)
5076 {
5077 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5078 == FAIL)
5079 {
5080 if (startcol == -3)
5081 cpt_sources_array[idx].cs_refresh_always = FALSE;
5082 else
5083 startcol = -2;
5084 }
5085 cpt_sources_array[idx].cs_startcol = startcol;
5086 }
5087 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5088 idx++;
5089 }
5090
5091 // Undo insertion
5092 ins_compl_delete();
5093
5094 vim_free(cpt);
5095#endif
5096}
5097
5098/*
Girish Palya7c621052025-05-26 19:41:59 +02005099 * Safely advance the cpt_sources_index by one.
5100 */
5101 static int
5102advance_cpt_sources_index_safe(void)
5103{
5104 if (cpt_sources_index < cpt_sources_count - 1)
5105 {
5106 cpt_sources_index++;
5107 return OK;
5108 }
5109#ifdef FEAT_EVAL
5110 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5111#endif
5112 return FAIL;
5113}
5114
5115/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005116 * Get the next expansion(s), using "compl_pattern".
5117 * The search starts at position "ini" in curbuf and in the direction
5118 * compl_direction.
5119 * When "compl_started" is FALSE start at that position, otherwise continue
5120 * where we stopped searching before.
5121 * This may return before finding all the matches.
5122 * Return the total number of matches or -1 if still unknown -- Acevedo
5123 */
5124 static int
5125ins_compl_get_exp(pos_T *ini)
5126{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005127 static ins_compl_next_state_T st;
5128 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005129 int i;
5130 int found_new_match;
5131 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005132 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005133
5134 if (!compl_started)
5135 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005136 buf_T *buf;
5137
5138 FOR_ALL_BUFFERS(buf)
5139 buf->b_scanned = 0;
5140 if (!st_cleared)
5141 {
5142 CLEAR_FIELD(st);
5143 st_cleared = TRUE;
5144 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005145 st.found_all = FALSE;
5146 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005147 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005148 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005149 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5150 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005151 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005152 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005153 st.last_match_pos = st.first_match_pos = *ini;
5154 }
5155 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5156 st.ins_buf = curbuf; // In case the buffer was wiped out.
5157
5158 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005159 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005160 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005161
Girish Palya98c29db2025-06-01 19:40:00 +02005162 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5163 !(compl_cont_status & CONT_LOCAL))
5164 {
5165 // ^N completion, not ^X^L or complete() or ^X^N
5166 if (!compl_started) // Before showing menu the first time
5167 {
5168 if (setup_cpt_sources() == FAIL)
5169 return FAIL;
5170 }
5171 prepare_cpt_compl_funcs();
5172 cpt_sources_index = 0;
5173 }
5174
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005175 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005176 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005177 {
5178 found_new_match = FAIL;
5179 st.set_match_pos = FALSE;
5180
5181 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5182 // or if found_all says this entry is done. For ^X^L only use the
5183 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005184 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005185 && (!compl_started || st.found_all))
5186 {
Girish Palya7c621052025-05-26 19:41:59 +02005187 int status = process_next_cpt_value(&st, &type, ini,
5188 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005189
5190 if (status == INS_COMPL_CPT_END)
5191 break;
5192 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005193 {
Girish Palya7c621052025-05-26 19:41:59 +02005194 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5195 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005196 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005197 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005198 }
5199
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005200 // If complete() was called then compl_pattern has been reset. The
5201 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005202 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005203 break;
5204
5205 // get the next set of completion matches
5206 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005207
Girish Palya7c621052025-05-26 19:41:59 +02005208 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5209 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005210
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005211 // break the loop for specialized modes (use 'complete' just for the
5212 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5213 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005214 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5215 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005216 {
5217 if (got_int)
5218 break;
5219 // Fill the popup menu as soon as possible.
5220 if (type != -1)
5221 ins_compl_check_keys(0, FALSE);
5222
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005223 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005224 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5225 break;
5226 compl_started = TRUE;
5227 }
5228 else
5229 {
5230 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005231 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005232 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005233
5234 compl_started = FALSE;
5235 }
5236 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005237 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005238 compl_started = TRUE;
5239
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005240 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005241 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005242 found_new_match = FAIL;
5243
5244 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005245 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005246 && !ctrl_x_mode_line_or_eval()))
5247 i = ins_compl_make_cyclic();
5248
glepnirf31cfa22025-03-06 21:59:13 +01005249 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5250 fuzzy_longest_match();
5251
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005252 if (compl_old_match != NULL)
5253 {
5254 // If several matches were added (FORWARD) or the search failed and has
5255 // just been made cyclic then we have to move compl_curr_match to the
5256 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005257 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005258 : compl_old_match->cp_prev;
5259 if (compl_curr_match == NULL)
5260 compl_curr_match = compl_old_match;
5261 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005262 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005263
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005264 if (is_nearest_active())
5265 sort_compl_match_list(cp_compare_nearest);
5266
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005267 return i;
5268}
5269
5270/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005271 * Update "compl_shown_match" to the actually shown match, it may differ when
5272 * "compl_leader" is used to omit some of the matches.
5273 */
5274 static void
5275ins_compl_update_shown_match(void)
5276{
5277 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005278 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005279 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005280 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005281 compl_shown_match = compl_shown_match->cp_next;
5282
5283 // If we didn't find it searching forward, and compl_shows_dir is
5284 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005285 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005286 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005287 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005288 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005289 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005290 {
5291 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005292 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005293 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005294 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005295 compl_shown_match = compl_shown_match->cp_prev;
5296 }
5297}
5298
5299/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005300 * Delete the old text being completed.
5301 */
5302 void
5303ins_compl_delete(void)
5304{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005305 // In insert mode: Delete the typed part.
5306 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005307 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005308 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005309 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005310 int has_preinsert = ins_compl_preinsert_effect();
5311 if (has_preinsert)
5312 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005313 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005314 curwin->w_cursor.col = compl_ins_end_col;
5315 }
5316
glepnir76bdb822025-02-08 19:04:51 +01005317 if (curwin->w_cursor.lnum > compl_lnum)
5318 {
5319 if (curwin->w_cursor.col < ml_get_curline_len())
5320 {
John Marriottf4b36412025-02-23 09:09:59 +01005321 char_u *line = ml_get_cursor();
5322 remaining.length = ml_get_cursor_len();
5323 remaining.string = vim_strnsave(line, remaining.length);
5324 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005325 return;
5326 }
5327 while (curwin->w_cursor.lnum > compl_lnum)
5328 {
5329 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5330 {
John Marriottf4b36412025-02-23 09:09:59 +01005331 if (remaining.string)
5332 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005333 return;
5334 }
zeertzjq060e6552025-02-21 20:06:26 +01005335 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005336 curwin->w_cursor.lnum--;
5337 }
5338 // move cursor to end of line
5339 curwin->w_cursor.col = ml_get_curline_len();
5340 }
5341
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005342 if ((int)curwin->w_cursor.col > col)
5343 {
5344 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005345 {
John Marriottf4b36412025-02-23 09:09:59 +01005346 if (remaining.string)
5347 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005348 return;
glepnire3647c82025-02-10 21:16:32 +01005349 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005350 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005351 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005352 }
5353
John Marriottf4b36412025-02-23 09:09:59 +01005354 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005355 {
5356 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005357 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005358 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005359 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005360 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005361 // TODO: is this sufficient for redrawing? Redrawing everything causes
5362 // flicker, thus we can't do that.
5363 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005364#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005365 // clear v:completed_item
5366 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005367#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005368}
5369
5370/*
glepnir76bdb822025-02-08 19:04:51 +01005371 * Insert a completion string that contains newlines.
5372 * The string is split and inserted line by line.
5373 */
5374 static void
5375ins_compl_expand_multiple(char_u *str)
5376{
5377 char_u *start = str;
5378 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005379 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005380
5381 while (*curr != NUL)
5382 {
5383 if (*curr == '\n')
5384 {
5385 // Insert the text chunk before newline
5386 if (curr > start)
5387 ins_char_bytes(start, (int)(curr - start));
5388
5389 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005390 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005391 start = curr + 1;
5392 }
5393 curr++;
5394 }
5395
5396 // Handle remaining text after last newline (if any)
5397 if (curr > start)
5398 ins_char_bytes(start, (int)(curr - start));
5399
5400 compl_ins_end_col = curwin->w_cursor.col;
5401}
5402
5403/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005404 * Insert the new text being completed.
5405 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005406 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5407 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005408 */
5409 void
glepniredd4ac32025-01-29 18:53:51 +01005410ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005411{
glepnir76bdb822025-02-08 19:04:51 +01005412 int compl_len = get_compl_len();
5413 int preinsert = ins_compl_has_preinsert();
5414 char_u *cp_str = compl_shown_match->cp_str.string;
5415 size_t cp_str_len = compl_shown_match->cp_str.length;
5416 size_t leader_len = ins_compl_leader_len();
5417 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005418
5419 // Make sure we don't go over the end of the string, this can happen with
5420 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005421 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005422 {
glepnir76bdb822025-02-08 19:04:51 +01005423 if (has_multiple)
5424 ins_compl_expand_multiple(cp_str + compl_len);
5425 else
5426 {
5427 ins_compl_insert_bytes(cp_str + compl_len, -1);
5428 if (preinsert && move_cursor)
5429 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5430 }
glepniredd4ac32025-01-29 18:53:51 +01005431 }
5432 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005433 compl_used_match = FALSE;
5434 else
5435 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005436#ifdef FEAT_EVAL
5437 {
5438 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5439
5440 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5441 }
5442#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005443 if (!in_compl_func)
5444 compl_curr_match = compl_shown_match;
5445}
5446
5447/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005448 * show the file name for the completion match (if any). Truncate the file
5449 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005450 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005451 static void
5452ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005453{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005454 char *lead = _("match in file");
5455 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5456 char_u *s;
5457 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005458
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005459 if (space <= 0)
5460 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005461
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005462 // We need the tail that fits. With double-byte encoding going
5463 // back from the end is very slow, thus go from the start and keep
5464 // the text that fits in "space" between "s" and "e".
5465 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005466 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005467 space -= ptr2cells(e);
5468 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005469 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005470 space += ptr2cells(s);
5471 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005472 }
5473 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005474 msg_hist_off = TRUE;
5475 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5476 s > compl_shown_match->cp_fname ? "<" : "", s);
5477 msg((char *)IObuff);
5478 msg_hist_off = FALSE;
5479 redraw_cmdline = FALSE; // don't overwrite!
5480}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005481
glepnirdca57fb2024-06-04 22:01:21 +02005482/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005483 * Find the appropriate completion item when 'complete' ('cpt') includes
5484 * a 'max_matches' postfix. In this case, we search for a match where
5485 * 'cp_in_match_array' is set, indicating that the match is also present
5486 * in 'compl_match_array'.
5487 */
5488 static compl_T *
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005489find_next_match_in_menu(void)
Girish Palya0ac1eb32025-04-16 20:18:33 +02005490{
5491 int is_forward = compl_shows_dir_forward();
5492 compl_T *match = compl_shown_match;
5493
5494 do
5495 match = is_forward ? match->cp_next : match->cp_prev;
5496 while (match->cp_next && !match->cp_in_match_array
5497 && !match_at_original_text(match));
5498 return match;
5499}
5500
5501/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005502 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005503 * times. The number of matches found is returned in 'num_matches'.
5504 *
5505 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5506 * get more completions. If it is FALSE, then do nothing when there are no more
5507 * completions in the given direction.
5508 *
5509 * If "advance" is TRUE, then completion will move to the first match.
5510 * Otherwise, the original text will be shown.
5511 *
5512 * Returns OK on success and -1 if the number of matches are unknown.
5513 */
5514 static int
5515find_next_completion_match(
5516 int allow_get_expansion,
5517 int todo, // repeat completion this many times
5518 int advance,
5519 int *num_matches)
5520{
5521 int found_end = FALSE;
5522 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005523 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005524 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5525 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005526
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005527 while (--todo >= 0)
5528 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005529 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005530 {
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005531 if (compl_match_array != NULL)
5532 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005533 else
5534 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005535 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005536 && (is_first_match(compl_shown_match->cp_next)
5537 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005538 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005539 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005540 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005541 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005542 found_end = is_first_match(compl_shown_match);
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005543 if (compl_match_array != NULL)
5544 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005545 else
5546 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005547 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005548 }
5549 else
5550 {
5551 if (!allow_get_expansion)
5552 {
5553 if (advance)
5554 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005555 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005556 compl_pending -= todo + 1;
5557 else
5558 compl_pending += todo + 1;
5559 }
5560 return -1;
5561 }
5562
5563 if (!compl_no_select && advance)
5564 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005565 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005566 --compl_pending;
5567 else
5568 ++compl_pending;
5569 }
5570
5571 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005572 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005573
5574 // handle any pending completions
5575 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005576 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005577 {
5578 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5579 {
5580 compl_shown_match = compl_shown_match->cp_next;
5581 --compl_pending;
5582 }
5583 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5584 {
5585 compl_shown_match = compl_shown_match->cp_prev;
5586 ++compl_pending;
5587 }
5588 else
5589 break;
5590 }
5591 found_end = FALSE;
5592 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005593 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005594 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005595 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005596 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005597 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005598 ++todo;
5599 else
5600 // Remember a matching item.
5601 found_compl = compl_shown_match;
5602
5603 // Stop at the end of the list when we found a usable match.
5604 if (found_end)
5605 {
5606 if (found_compl != NULL)
5607 {
5608 compl_shown_match = found_compl;
5609 break;
5610 }
5611 todo = 1; // use first usable match after wrapping around
5612 }
5613 }
5614
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005615 return OK;
5616}
5617
5618/*
5619 * Fill in the next completion in the current direction.
5620 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5621 * get more completions. If it is FALSE, then we just do nothing when there
5622 * are no more completions in a given direction. The latter case is used when
5623 * we are still in the middle of finding completions, to allow browsing
5624 * through the ones found so far.
5625 * Return the total number of matches, or -1 if still unknown -- webb.
5626 *
5627 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5628 * compl_shown_match here.
5629 *
5630 * Note that this function may be called recursively once only. First with
5631 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5632 * calls this function with "allow_get_expansion" FALSE.
5633 */
5634 static int
5635ins_compl_next(
5636 int allow_get_expansion,
5637 int count, // repeat completion this many times; should
5638 // be at least 1
5639 int insert_match, // Insert the newly selected match
5640 int in_compl_func) // called from complete_check()
5641{
5642 int num_matches = -1;
5643 int todo = count;
5644 int advance;
5645 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005646 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005647 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005648 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5649 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005650 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005651
5652 // When user complete function return -1 for findstart which is next
5653 // time of 'always', compl_shown_match become NULL.
5654 if (compl_shown_match == NULL)
5655 return -1;
5656
John Marriott5e6ea922024-11-23 14:01:57 +01005657 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005658 && !match_at_original_text(compl_shown_match)
5659 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005660 // Update "compl_shown_match" to the actually shown match
5661 ins_compl_update_shown_match();
5662
5663 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005664 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005665 // Delete old text to be replaced
5666 ins_compl_delete();
5667
5668 // When finding the longest common text we stick at the original text,
5669 // don't let CTRL-N or CTRL-P move to the first match.
5670 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5671
5672 // When restarting the search don't insert the first match either.
5673 if (compl_restarting)
5674 {
5675 advance = FALSE;
5676 compl_restarting = FALSE;
5677 }
5678
5679 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5680 // around.
5681 if (find_next_completion_match(allow_get_expansion, todo, advance,
5682 &num_matches) == -1)
5683 return -1;
5684
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005685 if (curbuf != orig_curbuf)
5686 {
5687 // In case some completion function switched buffer, don't want to
5688 // insert the completion elsewhere.
5689 return -1;
5690 }
5691
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005692 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005693 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005694 {
glepnir6a38aff2024-12-16 21:56:16 +01005695 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005696 compl_used_match = FALSE;
5697 }
5698 else if (insert_match)
5699 {
5700 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005701 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005702 else
glepnir6a38aff2024-12-16 21:56:16 +01005703 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005704 }
5705 else
5706 compl_used_match = FALSE;
5707
5708 if (!allow_get_expansion)
5709 {
5710 // may undisplay the popup menu first
5711 ins_compl_upd_pum();
5712
5713 if (pum_enough_matches())
5714 // Will display the popup menu, don't redraw yet to avoid flicker.
5715 pum_call_update_screen();
5716 else
5717 // Not showing the popup menu yet, redraw to show the user what was
5718 // inserted.
5719 update_screen(0);
5720
5721 // display the updated popup menu
5722 ins_compl_show_pum();
5723#ifdef FEAT_GUI
5724 if (gui.in_use)
5725 {
5726 // Show the cursor after the match, not after the redrawn text.
5727 setcursor();
5728 out_flush_cursor(FALSE, FALSE);
5729 }
5730#endif
5731
5732 // Delete old text to be replaced, since we're still searching and
5733 // don't want to match ourselves!
5734 ins_compl_delete();
5735 }
5736
5737 // Enter will select a match when the match wasn't inserted and the popup
5738 // menu is visible.
5739 if (compl_no_insert && !started)
5740 compl_enter_selects = TRUE;
5741 else
5742 compl_enter_selects = !insert_match && compl_match_array != NULL;
5743
5744 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005745 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005746 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005747
5748 return num_matches;
5749}
5750
5751/*
5752 * Call this while finding completions, to check whether the user has hit a key
5753 * that should change the currently displayed completion, or exit completion
5754 * mode. Also, when compl_pending is not zero, show a completion as soon as
5755 * possible. -- webb
5756 * "frequency" specifies out of how many calls we actually check.
5757 * "in_compl_func" is TRUE when called from complete_check(), don't set
5758 * compl_curr_match.
5759 */
5760 void
5761ins_compl_check_keys(int frequency, int in_compl_func)
5762{
5763 static int count = 0;
5764 int c;
5765
5766 // Don't check when reading keys from a script, :normal or feedkeys().
5767 // That would break the test scripts. But do check for keys when called
5768 // from complete_check().
5769 if (!in_compl_func && (using_script() || ex_normal_busy))
5770 return;
5771
5772 // Only do this at regular intervals
5773 if (++count < frequency)
5774 return;
5775 count = 0;
5776
5777 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5778 // can't do its work correctly.
5779 c = vpeekc_any();
5780 if (c != NUL)
5781 {
5782 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5783 {
5784 c = safe_vgetc(); // Eat the character
5785 compl_shows_dir = ins_compl_key2dir(c);
5786 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5787 c != K_UP && c != K_DOWN, in_compl_func);
5788 }
5789 else
5790 {
5791 // Need to get the character to have KeyTyped set. We'll put it
5792 // back with vungetc() below. But skip K_IGNORE.
5793 c = safe_vgetc();
5794 if (c != K_IGNORE)
5795 {
5796 // Don't interrupt completion when the character wasn't typed,
5797 // e.g., when doing @q to replay keys.
5798 if (c != Ctrl_R && KeyTyped)
5799 compl_interrupted = TRUE;
5800
5801 vungetc(c);
5802 }
5803 }
5804 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005805 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005806 {
5807 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5808
5809 compl_pending = 0;
5810 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5811 }
5812}
5813
5814/*
5815 * Decide the direction of Insert mode complete from the key typed.
5816 * Returns BACKWARD or FORWARD.
5817 */
5818 static int
5819ins_compl_key2dir(int c)
5820{
5821 if (c == Ctrl_P || c == Ctrl_L
5822 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5823 return BACKWARD;
5824 return FORWARD;
5825}
5826
5827/*
5828 * Return TRUE for keys that are used for completion only when the popup menu
5829 * is visible.
5830 */
5831 static int
5832ins_compl_pum_key(int c)
5833{
5834 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5835 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5836 || c == K_UP || c == K_DOWN);
5837}
5838
5839/*
5840 * Decide the number of completions to move forward.
5841 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5842 */
5843 static int
5844ins_compl_key2count(int c)
5845{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005846 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5847 {
glepnir19e1dd62025-05-08 22:50:38 +02005848 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005849 if (h > 3)
5850 h -= 2; // keep some context
5851 return h;
5852 }
5853 return 1;
5854}
5855
5856/*
5857 * Return TRUE if completion with "c" should insert the match, FALSE if only
5858 * to change the currently selected completion.
5859 */
5860 static int
5861ins_compl_use_match(int c)
5862{
5863 switch (c)
5864 {
5865 case K_UP:
5866 case K_DOWN:
5867 case K_PAGEDOWN:
5868 case K_KPAGEDOWN:
5869 case K_S_DOWN:
5870 case K_PAGEUP:
5871 case K_KPAGEUP:
5872 case K_S_UP:
5873 return FALSE;
5874 }
5875 return TRUE;
5876}
5877
5878/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005879 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5880 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005881 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005882 * Uses the global variables: compl_cont_status and ctrl_x_mode
5883 */
5884 static int
5885get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5886{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005887 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005888 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005889 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005890 {
5891 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5892 ;
5893 compl_col += ++startcol;
5894 compl_length = curs_col - startcol;
5895 }
5896 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005897 {
John Marriott5e6ea922024-11-23 14:01:57 +01005898 compl_pattern.string = str_foldcase(line + compl_col,
5899 compl_length, NULL, 0);
5900 if (compl_pattern.string == NULL)
5901 {
5902 compl_pattern.length = 0;
5903 return FAIL;
5904 }
5905 compl_pattern.length = STRLEN(compl_pattern.string);
5906 }
5907 else
5908 {
5909 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5910 if (compl_pattern.string == NULL)
5911 {
5912 compl_pattern.length = 0;
5913 return FAIL;
5914 }
5915 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005916 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005917 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005918 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005919 {
5920 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005921 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005922 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005923
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005924 if (!vim_iswordp(line + compl_col)
5925 || (compl_col > 0
5926 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005927 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005928 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005929 prefixlen = 0;
5930 }
John Marriott5e6ea922024-11-23 14:01:57 +01005931
5932 // we need up to 2 extra chars for the prefix
5933 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5934 compl_pattern.string = alloc(n);
5935 if (compl_pattern.string == NULL)
5936 {
5937 compl_pattern.length = 0;
5938 return FAIL;
5939 }
5940 STRCPY((char *)compl_pattern.string, prefix);
5941 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005942 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005943 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005944 }
5945 else if (--startcol < 0
5946 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5947 {
John Marriott5e6ea922024-11-23 14:01:57 +01005948 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5949
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005950 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005951 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5952 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005953 {
John Marriott5e6ea922024-11-23 14:01:57 +01005954 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005955 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005956 }
John Marriott5e6ea922024-11-23 14:01:57 +01005957 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005958 compl_col += curs_col;
5959 compl_length = 0;
5960 }
5961 else
5962 {
5963 // Search the point of change class of multibyte character
5964 // or not a word single byte character backward.
5965 if (has_mbyte)
5966 {
5967 int base_class;
5968 int head_off;
5969
5970 startcol -= (*mb_head_off)(line, line + startcol);
5971 base_class = mb_get_class(line + startcol);
5972 while (--startcol >= 0)
5973 {
5974 head_off = (*mb_head_off)(line, line + startcol);
5975 if (base_class != mb_get_class(line + startcol
5976 - head_off))
5977 break;
5978 startcol -= head_off;
5979 }
5980 }
5981 else
glepnir19e1dd62025-05-08 22:50:38 +02005982 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005983 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5984 ;
glepnir19e1dd62025-05-08 22:50:38 +02005985 }
5986
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005987 compl_col += ++startcol;
5988 compl_length = (int)curs_col - startcol;
5989 if (compl_length == 1)
5990 {
5991 // Only match word with at least two chars -- webb
5992 // there's no need to call quote_meta,
5993 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005994 compl_pattern.string = alloc(7);
5995 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005996 {
John Marriott5e6ea922024-11-23 14:01:57 +01005997 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005998 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005999 }
John Marriott5e6ea922024-11-23 14:01:57 +01006000 STRCPY((char *)compl_pattern.string, "\\<");
6001 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
6002 STRCAT((char *)compl_pattern.string, "\\k");
6003 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006004 }
6005 else
6006 {
John Marriott5e6ea922024-11-23 14:01:57 +01006007 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6008
6009 compl_pattern.string = alloc(n);
6010 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006011 {
John Marriott5e6ea922024-11-23 14:01:57 +01006012 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006013 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006014 }
John Marriott5e6ea922024-11-23 14:01:57 +01006015 STRCPY((char *)compl_pattern.string, "\\<");
6016 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006017 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006018 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006019 }
6020 }
6021
6022 return OK;
6023}
6024
6025/*
6026 * Get the pattern, column and length for whole line completion or for the
6027 * complete() function.
6028 * Sets the global variables: compl_col, compl_length and compl_pattern.
6029 */
6030 static int
6031get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6032{
6033 compl_col = (colnr_T)getwhitecols(line);
6034 compl_length = (int)curs_col - (int)compl_col;
6035 if (compl_length < 0) // cursor in indent: empty pattern
6036 compl_length = 0;
6037 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006038 {
John Marriott5e6ea922024-11-23 14:01:57 +01006039 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6040 NULL, 0);
6041 if (compl_pattern.string == NULL)
6042 {
6043 compl_pattern.length = 0;
6044 return FAIL;
6045 }
6046 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006047 }
John Marriott5e6ea922024-11-23 14:01:57 +01006048 else
6049 {
6050 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6051 if (compl_pattern.string == NULL)
6052 {
6053 compl_pattern.length = 0;
6054 return FAIL;
6055 }
6056 compl_pattern.length = (size_t)compl_length;
6057 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006058
6059 return OK;
6060}
6061
6062/*
6063 * Get the pattern, column and length for filename completion.
6064 * Sets the global variables: compl_col, compl_length and compl_pattern.
6065 */
6066 static int
6067get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6068{
6069 // Go back to just before the first filename character.
6070 if (startcol > 0)
6071 {
6072 char_u *p = line + startcol;
6073
6074 MB_PTR_BACK(line, p);
6075 while (p > line && vim_isfilec(PTR2CHAR(p)))
6076 MB_PTR_BACK(line, p);
6077 if (p == line && vim_isfilec(PTR2CHAR(p)))
6078 startcol = 0;
6079 else
6080 startcol = (int)(p - line) + 1;
6081 }
6082
6083 compl_col += startcol;
6084 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006085 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6086 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006087 {
John Marriott5e6ea922024-11-23 14:01:57 +01006088 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006089 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006090 }
6091
John Marriott5e6ea922024-11-23 14:01:57 +01006092 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006093
6094 return OK;
6095}
6096
6097/*
6098 * Get the pattern, column and length for command-line completion.
6099 * Sets the global variables: compl_col, compl_length and compl_pattern.
6100 */
6101 static int
6102get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6103{
John Marriott5e6ea922024-11-23 14:01:57 +01006104 compl_pattern.string = vim_strnsave(line, curs_col);
6105 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006106 {
John Marriott5e6ea922024-11-23 14:01:57 +01006107 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006108 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006109 }
John Marriott5e6ea922024-11-23 14:01:57 +01006110 compl_pattern.length = curs_col;
6111 set_cmd_context(&compl_xp, compl_pattern.string,
6112 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006113 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6114 || compl_xp.xp_context == EXPAND_NOTHING)
6115 // No completion possible, use an empty pattern to get a
6116 // "pattern not found" message.
6117 compl_col = curs_col;
6118 else
John Marriott5e6ea922024-11-23 14:01:57 +01006119 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006120 compl_length = curs_col - compl_col;
6121
6122 return OK;
6123}
6124
Girish Palya98c29db2025-06-01 19:40:00 +02006125#ifdef FEAT_COMPL_FUNC
6126/*
6127 * Set global variables related to completion:
6128 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6129 */
6130 static int
6131set_compl_globals(
6132 int startcol UNUSED,
6133 colnr_T curs_col UNUSED,
6134 int is_cpt_compl UNUSED)
6135{
6136 char_u *line = NULL;
6137 string_T *pattern = NULL;
6138 int len;
6139
6140 if (startcol < 0 || startcol > curs_col)
6141 startcol = curs_col;
6142 len = curs_col - startcol;
6143
6144 // Re-obtain line in case it has changed
6145 line = ml_get(curwin->w_cursor.lnum);
6146
6147 pattern = is_cpt_compl ? &cpt_compl_pattern : &compl_pattern;
6148 pattern->string = vim_strnsave(line + startcol, (size_t)len);
6149 if (pattern->string == NULL)
6150 {
6151 pattern->length = 0;
6152 return FAIL;
6153 }
6154 pattern->length = (size_t)len;
6155 if (!is_cpt_compl)
6156 {
6157 compl_col = startcol;
6158 compl_length = len;
6159 }
6160 return OK;
6161}
6162#endif
6163
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006164/*
6165 * Get the pattern, column and length for user defined completion ('omnifunc',
6166 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006167 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006168 * Callback function "cb" is set if triggered by a function in the 'cpt'
6169 * option; otherwise, it is NULL.
6170 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006171 */
6172 static int
glepnir19e1dd62025-05-08 22:50:38 +02006173get_userdefined_compl_info(
6174 colnr_T curs_col UNUSED,
6175 callback_T *cb UNUSED,
6176 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006177{
6178 int ret = FAIL;
6179
6180#ifdef FEAT_COMPL_FUNC
6181 // Call user defined function 'completefunc' with "a:findstart"
6182 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006183 typval_T args[3];
6184 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006185 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006186 pos_T pos;
6187 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006188 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006189
Girish Palyacbe53192025-04-14 22:13:15 +02006190 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006191 {
Girish Palyacbe53192025-04-14 22:13:15 +02006192 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6193 // length as a string
6194 funcname = get_complete_funcname(ctrl_x_mode);
6195 if (*funcname == NUL)
6196 {
6197 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6198 ? "completefunc" : "omnifunc");
6199 return FAIL;
6200 }
6201 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006202 }
6203
6204 args[0].v_type = VAR_NUMBER;
6205 args[0].vval.v_number = 1;
6206 args[1].v_type = VAR_STRING;
6207 args[1].vval.v_string = (char_u *)"";
6208 args[2].v_type = VAR_UNKNOWN;
6209 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006210 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006211 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006212 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006213
6214 State = save_State;
6215 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006216 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006217 validate_cursor();
6218 if (!EQUAL_POS(curwin->w_cursor, pos))
6219 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006220 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006221 return FAIL;
6222 }
6223
Girish Palyacbe53192025-04-14 22:13:15 +02006224 if (startcol != NULL)
6225 *startcol = col;
6226
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006227 // Return value -2 means the user complete function wants to cancel the
6228 // complete without an error, do the same if the function did not execute
6229 // successfully.
6230 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006231 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006232
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006233 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006234 if (col == -3)
6235 {
Girish Palyacbe53192025-04-14 22:13:15 +02006236 if (is_cpt_function)
6237 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006238 ctrl_x_mode = CTRL_X_NORMAL;
6239 edit_submode = NULL;
6240 if (!shortmess(SHM_COMPLETIONMENU))
6241 msg_clr_cmdline();
6242 return FAIL;
6243 }
6244
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006245 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006246 // completion.
6247 compl_opt_refresh_always = FALSE;
6248 compl_opt_suppress_empty = FALSE;
6249
Girish Palya98c29db2025-06-01 19:40:00 +02006250 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006251#endif
6252
6253 return ret;
6254}
6255
6256/*
6257 * Get the pattern, column and length for spell completion.
6258 * Sets the global variables: compl_col, compl_length and compl_pattern.
6259 * Uses the global variable: spell_bad_len
6260 */
6261 static int
6262get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6263{
6264 int ret = FAIL;
6265#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006266 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006267
6268 if (spell_bad_len > 0)
6269 compl_col = curs_col - spell_bad_len;
6270 else
6271 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006272
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006273 if (compl_col >= (colnr_T)startcol)
6274 {
6275 compl_length = 0;
6276 compl_col = curs_col;
6277 }
6278 else
6279 {
6280 spell_expand_check_cap(compl_col);
6281 compl_length = (int)curs_col - compl_col;
6282 }
6283 // Need to obtain "line" again, it may have become invalid.
6284 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006285 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6286 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006287 {
John Marriott5e6ea922024-11-23 14:01:57 +01006288 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006289 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006290 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006291
John Marriott5e6ea922024-11-23 14:01:57 +01006292 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006293 ret = OK;
6294#endif
6295
6296 return ret;
6297}
6298
6299/*
6300 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006301 * "startcol" - start column number of the completion pattern/text
6302 * "cur_col" - current cursor column
6303 * On return, "line_invalid" is set to TRUE, if the current line may have
6304 * become invalid and needs to be fetched again.
6305 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006306 */
6307 static int
6308compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6309{
glepnird5fdfa52025-06-02 19:45:41 +02006310 if (ctrl_x_mode_normal() || ctrl_x_mode_register()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006311 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6312 && !thesaurus_func_complete(ctrl_x_mode)))
6313 {
6314 return get_normal_compl_info(line, startcol, curs_col);
6315 }
6316 else if (ctrl_x_mode_line_or_eval())
6317 {
6318 return get_wholeline_compl_info(line, curs_col);
6319 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006320 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006321 {
6322 return get_filename_compl_info(line, startcol, curs_col);
6323 }
6324 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6325 {
6326 return get_cmdline_compl_info(line, curs_col);
6327 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006328 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006329 || thesaurus_func_complete(ctrl_x_mode))
6330 {
Girish Palyacbe53192025-04-14 22:13:15 +02006331 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006332 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006333 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006334 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006335 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006336 {
6337 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6338 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006339 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006340 }
6341 else
6342 {
6343 internal_error("ins_complete()");
6344 return FAIL;
6345 }
6346
6347 return OK;
6348}
6349
6350/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006351 * Continue an interrupted completion mode search in "line".
6352 *
6353 * If this same ctrl_x_mode has been interrupted use the text from
6354 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6355 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6356 * the same line as the cursor then fix it (the line has been split because it
6357 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6358 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006359 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006360 static void
6361ins_compl_continue_search(char_u *line)
6362{
6363 // it is a continued search
6364 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006365 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6366 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006367 {
6368 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6369 {
6370 // line (probably) wrapped, set compl_startpos to the
6371 // first non_blank in the line, if it is not a wordchar
6372 // include it to get a better pattern, but then we don't
6373 // want the "\\<" prefix, check it below
6374 compl_col = (colnr_T)getwhitecols(line);
6375 compl_startpos.col = compl_col;
6376 compl_startpos.lnum = curwin->w_cursor.lnum;
6377 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6378 }
6379 else
6380 {
6381 // S_IPOS was set when we inserted a word that was at the
6382 // beginning of the line, which means that we'll go to SOL
6383 // mode but first we need to redefine compl_startpos
6384 if (compl_cont_status & CONT_S_IPOS)
6385 {
6386 compl_cont_status |= CONT_SOL;
6387 compl_startpos.col = (colnr_T)(skipwhite(
6388 line + compl_length
6389 + compl_startpos.col) - line);
6390 }
6391 compl_col = compl_startpos.col;
6392 }
6393 compl_length = curwin->w_cursor.col - (int)compl_col;
6394 // IObuff is used to add a "word from the next line" would we
6395 // have enough space? just being paranoid
6396#define MIN_SPACE 75
6397 if (compl_length > (IOSIZE - MIN_SPACE))
6398 {
6399 compl_cont_status &= ~CONT_SOL;
6400 compl_length = (IOSIZE - MIN_SPACE);
6401 compl_col = curwin->w_cursor.col - compl_length;
6402 }
6403 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6404 if (compl_length < 1)
6405 compl_cont_status &= CONT_LOCAL;
6406 }
glepnird5fdfa52025-06-02 19:45:41 +02006407 else if (ctrl_x_mode_line_or_eval() || ctrl_x_mode_register())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006408 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6409 else
6410 compl_cont_status = 0;
6411}
6412
6413/*
6414 * start insert mode completion
6415 */
6416 static int
6417ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006418{
glepnir19e1dd62025-05-08 22:50:38 +02006419 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006420 int startcol = 0; // column where searched text starts
6421 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006422 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006423 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006424 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006425
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006426 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006427 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006428 did_si = FALSE;
6429 can_si = FALSE;
6430 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006431 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006432 return FAIL;
6433
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006434 line = ml_get(curwin->w_cursor.lnum);
6435 curs_col = curwin->w_cursor.col;
6436 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006437 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006438
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006439 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6440 && compl_cont_mode == ctrl_x_mode)
6441 // this same ctrl-x_mode was interrupted previously. Continue the
6442 // completion.
6443 ins_compl_continue_search(line);
6444 else
6445 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006446
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006447 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006448 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006449 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006450 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006451 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6452 compl_cont_status = 0;
6453 compl_cont_status |= CONT_N_ADDS;
6454 compl_startpos = curwin->w_cursor;
6455 startcol = (int)curs_col;
6456 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006457 }
6458
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006459 // Work out completion pattern and original text -- webb
6460 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6461 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006462 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6463 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006464 // restore did_ai, so that adding comment leader works
6465 did_ai = save_did_ai;
6466 return FAIL;
6467 }
6468 // If "line" was changed while getting completion info get it again.
6469 if (line_invalid)
6470 line = ml_get(curwin->w_cursor.lnum);
6471
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006472 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006473 {
6474 edit_submode_pre = (char_u *)_(" Adding");
6475 if (ctrl_x_mode_line_or_eval())
6476 {
6477 // Insert a new line, keep indentation but ignore 'comments'.
6478 char_u *old = curbuf->b_p_com;
6479
6480 curbuf->b_p_com = (char_u *)"";
6481 compl_startpos.lnum = curwin->w_cursor.lnum;
6482 compl_startpos.col = compl_col;
6483 ins_eol('\r');
6484 curbuf->b_p_com = old;
6485 compl_length = 0;
6486 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006487 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006488 }
glepnircfe502c2025-04-17 20:17:53 +02006489 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006490 {
6491 compl_startpos = curwin->w_cursor;
6492 compl_cont_status &= CONT_S_IPOS;
6493 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006494 }
6495 else
6496 {
6497 edit_submode_pre = NULL;
6498 compl_startpos.col = compl_col;
6499 }
6500
6501 if (compl_cont_status & CONT_LOCAL)
6502 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6503 else
6504 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6505
6506 // If any of the original typed text has been changed we need to fix
6507 // the redo buffer.
6508 ins_compl_fixRedoBufForLeader(NULL);
6509
6510 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006511 VIM_CLEAR_STRING(compl_orig_text);
6512 compl_orig_text.length = (size_t)compl_length;
6513 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006514 if (p_ic)
6515 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006516 if (compl_orig_text.string == NULL
6517 || ins_compl_add(compl_orig_text.string,
6518 (int)compl_orig_text.length,
6519 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006520 {
John Marriott5e6ea922024-11-23 14:01:57 +01006521 VIM_CLEAR_STRING(compl_pattern);
6522 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006523 return FAIL;
6524 }
6525
6526 // showmode might reset the internal line pointers, so it must
6527 // be called before line = ml_get(), or when this address is no
6528 // longer needed. -- Acevedo.
6529 edit_submode_extra = (char_u *)_("-- Searching...");
6530 edit_submode_highl = HLF_COUNT;
6531 showmode();
6532 edit_submode_extra = NULL;
6533 out_flush();
6534
6535 return OK;
6536}
6537
6538/*
6539 * display the completion status message
6540 */
6541 static void
6542ins_compl_show_statusmsg(void)
6543{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006544 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006545 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006546 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006547 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006548 ? (char_u *)_("Hit end of paragraph")
6549 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006550 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006551 }
6552
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006553 if (edit_submode_extra == NULL)
6554 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006555 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006556 {
6557 edit_submode_extra = (char_u *)_("Back at original");
6558 edit_submode_highl = HLF_W;
6559 }
6560 else if (compl_cont_status & CONT_S_IPOS)
6561 {
6562 edit_submode_extra = (char_u *)_("Word from other line");
6563 edit_submode_highl = HLF_COUNT;
6564 }
6565 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6566 {
6567 edit_submode_extra = (char_u *)_("The only match");
6568 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006569 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006570 }
6571 else
6572 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006573#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006574 // Update completion sequence number when needed.
6575 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006576 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006577#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006578 // The match should always have a sequence number now, this is
6579 // just a safety check.
6580 if (compl_curr_match->cp_number != -1)
6581 {
6582 // Space for 10 text chars. + 2x10-digit no.s = 31.
6583 // Translations may need more than twice that.
6584 static char_u match_ref[81];
6585
6586 if (compl_matches > 0)
6587 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006588 _("match %d of %d"),
6589 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006590 else
6591 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006592 _("match %d"),
6593 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006594 edit_submode_extra = match_ref;
6595 edit_submode_highl = HLF_R;
6596 if (dollar_vcol >= 0)
6597 curs_columns(FALSE);
6598 }
6599 }
6600 }
6601
6602 // Show a message about what (completion) mode we're in.
6603 if (!compl_opt_suppress_empty)
6604 {
6605 showmode();
6606 if (!shortmess(SHM_COMPLETIONMENU))
6607 {
6608 if (edit_submode_extra != NULL)
6609 {
6610 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006611 {
6612 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006613 msg_attr((char *)edit_submode_extra,
6614 edit_submode_highl < HLF_COUNT
6615 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006616 msg_hist_off = FALSE;
6617 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006618 }
6619 else
6620 msg_clr_cmdline(); // necessary for "noshowmode"
6621 }
6622 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006623}
6624
6625/*
6626 * Do Insert mode completion.
6627 * Called when character "c" was typed, which has a meaning for completion.
6628 * Returns OK if completion was done, FAIL if something failed (out of mem).
6629 */
6630 int
6631ins_complete(int c, int enable_pum)
6632{
6633 int n;
6634 int save_w_wrow;
6635 int save_w_leftcol;
6636 int insert_match;
6637
6638 compl_direction = ins_compl_key2dir(c);
6639 insert_match = ins_compl_use_match(c);
6640
6641 if (!compl_started)
6642 {
6643 if (ins_compl_start() == FAIL)
6644 return FAIL;
6645 }
6646 else if (insert_match && stop_arrow() == FAIL)
6647 return FAIL;
6648
glepnircf7f0122025-04-15 19:02:00 +02006649 compl_curr_win = curwin;
6650 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006651 compl_shown_match = compl_curr_match;
6652 compl_shows_dir = compl_direction;
6653
6654 // Find next match (and following matches).
6655 save_w_wrow = curwin->w_wrow;
6656 save_w_leftcol = curwin->w_leftcol;
6657 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6658
6659 // may undisplay the popup menu
6660 ins_compl_upd_pum();
6661
6662 if (n > 1) // all matches have been found
6663 compl_matches = n;
6664 compl_curr_match = compl_shown_match;
6665 compl_direction = compl_shows_dir;
6666
6667 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6668 // mode.
6669 if (got_int && !global_busy)
6670 {
6671 (void)vgetc();
6672 got_int = FALSE;
6673 }
6674
6675 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006676 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006677 {
6678 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6679 // because we couldn't expand anything at first place, but if we used
6680 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6681 // (such as M in M'exico) if not tried already. -- Acevedo
6682 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006683 || compl_status_adding()
6684 || (ctrl_x_mode_not_default()
6685 && !ctrl_x_mode_path_patterns()
6686 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006687 compl_cont_status &= ~CONT_N_ADDS;
6688 }
6689
6690 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6691 compl_cont_status |= CONT_S_IPOS;
6692 else
6693 compl_cont_status &= ~CONT_S_IPOS;
6694
6695 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006696
6697 // Show the popup menu, unless we got interrupted.
6698 if (enable_pum && !compl_interrupted)
6699 show_pum(save_w_wrow, save_w_leftcol);
6700
6701 compl_was_interrupted = compl_interrupted;
6702 compl_interrupted = FALSE;
6703
6704 return OK;
6705}
6706
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006707/*
6708 * Remove (if needed) and show the popup menu
6709 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006710 static void
6711show_pum(int prev_w_wrow, int prev_w_leftcol)
6712{
6713 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006714 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006715 RedrawingDisabled = 0;
6716
6717 // If the cursor moved or the display scrolled we need to remove the pum
6718 // first.
6719 setcursor();
6720 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6721 ins_compl_del_pum();
6722
6723 ins_compl_show_pum();
6724 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006725
6726 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006727}
6728
6729/*
6730 * Looks in the first "len" chars. of "src" for search-metachars.
6731 * If dest is not NULL the chars. are copied there quoting (with
6732 * a backslash) the metachars, and dest would be NUL terminated.
6733 * Returns the length (needed) of dest
6734 */
6735 static unsigned
6736quote_meta(char_u *dest, char_u *src, int len)
6737{
6738 unsigned m = (unsigned)len + 1; // one extra for the NUL
6739
6740 for ( ; --len >= 0; src++)
6741 {
6742 switch (*src)
6743 {
6744 case '.':
6745 case '*':
6746 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006747 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006748 break;
6749 // FALLTHROUGH
6750 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006751 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006752 break;
6753 // FALLTHROUGH
6754 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006755 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006756 break;
6757 // FALLTHROUGH
6758 case '^': // currently it's not needed.
6759 case '$':
6760 m++;
6761 if (dest != NULL)
6762 *dest++ = '\\';
6763 break;
6764 }
6765 if (dest != NULL)
6766 *dest++ = *src;
6767 // Copy remaining bytes of a multibyte character.
6768 if (has_mbyte)
6769 {
glepnir19e1dd62025-05-08 22:50:38 +02006770 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006771 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006772 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006773 {
6774 --len;
6775 ++src;
6776 if (dest != NULL)
6777 *dest++ = *src;
6778 }
6779 }
6780 }
6781 if (dest != NULL)
6782 *dest = NUL;
6783
6784 return m;
6785}
6786
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006787#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006788 void
6789free_insexpand_stuff(void)
6790{
John Marriott5e6ea922024-11-23 14:01:57 +01006791 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006792# ifdef FEAT_EVAL
6793 free_callback(&cfu_cb);
6794 free_callback(&ofu_cb);
6795 free_callback(&tsrfu_cb);
6796# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006797}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006798#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006799
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006800#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006801/*
6802 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6803 * spelled word, if there is one.
6804 */
6805 static void
6806spell_back_to_badword(void)
6807{
6808 pos_T tpos = curwin->w_cursor;
6809
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006810 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006811 if (curwin->w_cursor.col != tpos.col)
6812 start_arrow(&tpos);
6813}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006814#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006815
6816/*
6817 * Reset the info associated with completion sources.
6818 */
6819 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006820cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006821{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006822 VIM_CLEAR(cpt_sources_array);
6823 cpt_sources_index = -1;
6824 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006825}
6826
6827/*
Girish Palya98c29db2025-06-01 19:40:00 +02006828 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006829 */
6830 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006831setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006832{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006833 char_u buf[LSIZE];
6834 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006835 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006836 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006837
Girish Palya0ac1eb32025-04-16 20:18:33 +02006838 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006839 {
6840 while (*p == ',' || *p == ' ') // Skip delimiters
6841 p++;
6842 if (*p) // If not end of string, count this segment
6843 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006844 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006845 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006846 }
6847 }
Girish Palya98c29db2025-06-01 19:40:00 +02006848 if (count == 0)
6849 return OK;
6850
Girish Palya0ac1eb32025-04-16 20:18:33 +02006851 cpt_sources_clear();
6852 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006853 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6854 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006855 {
Girish Palya98c29db2025-06-01 19:40:00 +02006856 cpt_sources_count = 0;
6857 return FAIL;
6858 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006859
Girish Palya98c29db2025-06-01 19:40:00 +02006860 for (p = curbuf->b_p_cpt; *p;)
6861 {
6862 while (*p == ',' || *p == ' ') // Skip delimiters
6863 p++;
6864 if (*p) // If not end of string, count this segment
6865 {
6866 char_u *t;
6867
6868 vim_memset(buf, 0, LSIZE);
6869 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6870 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6871 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
6872 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006873 }
Girish Palyacbe53192025-04-14 22:13:15 +02006874 }
6875 return OK;
6876}
6877
6878/*
6879 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6880 */
6881 static int
6882is_cpt_func_refresh_always(void)
6883{
6884#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006885 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02006886 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006887 return TRUE;
6888#endif
6889 return FALSE;
6890}
6891
6892/*
6893 * Make the completion list non-cyclic.
6894 */
Girish Palyacbe53192025-04-14 22:13:15 +02006895 static void
6896ins_compl_make_linear(void)
6897{
6898 compl_T *m;
6899
6900 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6901 return;
6902 m = compl_first_match->cp_prev;
6903 m->cp_next = NULL;
6904 compl_first_match->cp_prev = NULL;
6905}
Girish Palyacbe53192025-04-14 22:13:15 +02006906
6907/*
6908 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006909 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006910 */
6911#ifdef FEAT_COMPL_FUNC
6912 static compl_T *
6913remove_old_matches(void)
6914{
6915 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6916 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006917 int compl_shown_removed = FALSE;
6918 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6919
6920 compl_direction = forward ? FORWARD : BACKWARD;
6921 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006922
6923 // Identify the sublist of old matches that needs removal
6924 for (current = compl_first_match; current != NULL; current = current->cp_next)
6925 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006926 if (current->cp_cpt_source_idx < cpt_sources_index &&
6927 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006928 insert_at = current;
6929
Girish Palya0ac1eb32025-04-16 20:18:33 +02006930 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006931 {
6932 if (!sublist_start)
6933 sublist_start = current;
6934 sublist_end = current;
6935 if (!compl_shown_removed && compl_shown_match == current)
6936 compl_shown_removed = TRUE;
6937 }
6938
Girish Palya0ac1eb32025-04-16 20:18:33 +02006939 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6940 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006941 break;
6942 }
6943
6944 // Re-assign compl_shown_match if necessary
6945 if (compl_shown_removed)
6946 {
6947 if (forward)
6948 compl_shown_match = compl_first_match;
6949 else
6950 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006951 for (current = compl_first_match; current->cp_next != NULL;
6952 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006953 ;
6954 compl_shown_match = current;
6955 }
6956 }
6957
6958 if (!sublist_start) // No nodes to remove
6959 return insert_at;
6960
6961 // Update links to remove sublist
6962 if (sublist_start->cp_prev)
6963 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6964 else
6965 compl_first_match = sublist_end->cp_next;
6966
6967 if (sublist_end->cp_next)
6968 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6969
6970 // Free all nodes in the sublist
6971 sublist_end->cp_next = NULL;
6972 for (current = sublist_start; current != NULL; current = next)
6973 {
6974 next = current->cp_next;
6975 ins_compl_item_free(current);
6976 }
6977
6978 return insert_at;
6979}
6980#endif
6981
6982/*
6983 * Retrieve completion matches using the callback function "cb" and store the
6984 * 'refresh:always' flag.
6985 */
6986#ifdef FEAT_COMPL_FUNC
6987 static void
6988get_cpt_func_completion_matches(callback_T *cb UNUSED)
6989{
Girish Palya98c29db2025-06-01 19:40:00 +02006990 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02006991
6992 VIM_CLEAR_STRING(cpt_compl_pattern);
Girish Palya98c29db2025-06-01 19:40:00 +02006993
6994 if (startcol == -2 || startcol == -3)
6995 return;
6996
6997 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02006998 {
6999 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02007000 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02007001 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02007002 compl_opt_refresh_always = FALSE;
7003 }
7004}
7005#endif
7006
7007/*
7008 * Retrieve completion matches from functions in the 'cpt' option where the
7009 * 'refresh:always' flag is set.
7010 */
7011 static void
7012cpt_compl_refresh(void)
7013{
7014#ifdef FEAT_COMPL_FUNC
7015 char_u *cpt;
7016 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007017 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007018 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007019
7020 // Make the completion list linear (non-cyclic)
7021 ins_compl_make_linear();
7022 // Make a copy of 'cpt' in case the buffer gets wiped out
7023 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007024 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007025
Girish Palya0ac1eb32025-04-16 20:18:33 +02007026 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007027 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007028 {
7029 while (*p == ',' || *p == ' ') // Skip delimiters
7030 p++;
7031
Girish Palya98c29db2025-06-01 19:40:00 +02007032 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007033 {
Girish Palya98c29db2025-06-01 19:40:00 +02007034 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007035 if (cb)
7036 {
7037 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007038 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7039 &startcol);
7040 if (ret == FAIL)
7041 {
7042 if (startcol == -3)
7043 cpt_sources_array[cpt_sources_index].cs_refresh_always
7044 = FALSE;
7045 else
7046 startcol = -2;
7047 }
7048 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7049 if (ret == OK)
7050 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007051 }
7052 }
7053
Girish Palya7c621052025-05-26 19:41:59 +02007054 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7055 if (may_advance_cpt_index(p))
7056 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007057 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007058 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007059
7060 vim_free(cpt);
7061 // Make the list cyclic
7062 compl_matches = ins_compl_make_cyclic();
7063#endif
7064}