blob: ff8e87e4e9ec7c345950100d9a950d79842fa71b [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{
1418 compl_T *compl = compl_first_match->cp_prev;
1419
1420 if (compl_leader.string != NULL && compl_leader.length > 0)
1421 {
1422 compl = compl_first_match;
1423 do
1424 {
1425 compl->cp_score = fuzzy_match_str(compl->cp_str.string,
1426 compl_leader.string);
1427 compl = compl->cp_next;
1428 } while (compl != NULL && !is_first_match(compl));
1429 }
1430}
1431
1432/*
1433 * Sort completion matches, excluding the node that contains the leader.
1434 */
1435 static void
1436sort_compl_match_list(int (*compare)(const void *, const void *))
1437{
1438 compl_T *compl = compl_first_match->cp_prev;
1439
1440 if (!compl_first_match || is_first_match(compl_first_match->cp_next))
1441 return;
1442
1443 ins_compl_make_linear();
1444 if (compl_shows_dir_forward())
1445 {
1446 compl_first_match->cp_next->cp_prev = NULL;
1447 compl_first_match->cp_next = mergesort_list(compl_first_match->cp_next,
1448 cp_get_next, cp_set_next, cp_get_prev, cp_set_prev, compare);
1449 compl_first_match->cp_next->cp_prev = compl_first_match;
1450 }
1451 else
1452 {
1453 compl->cp_prev->cp_next = NULL;
1454 compl_first_match = mergesort_list(compl_first_match, cp_get_next,
1455 cp_set_next, cp_get_prev, cp_set_prev, compare);
1456 compl_T *tail = compl_first_match;
1457 while (tail->cp_next != NULL)
1458 tail = tail->cp_next;
1459 tail->cp_next = compl;
1460 compl->cp_prev = tail;
1461 }
1462 (void)ins_compl_make_cyclic();
1463}
1464
glepnira218cc62024-06-03 19:32:39 +02001465/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001466 * Build a popup menu to show the completion matches.
1467 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1468 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001469 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001470 static int
1471ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001472{
1473 compl_T *compl;
1474 compl_T *shown_compl = NULL;
1475 int did_find_shown_match = FALSE;
1476 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001477 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001478 int cur = -1;
zeertzjqaa925ee2024-06-09 18:24:05 +02001479 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001480 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001481 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
glepnir80b66202024-11-27 21:53:53 +01001482 compl_T *match_head = NULL;
1483 compl_T *match_tail = NULL;
1484 compl_T *match_next = NULL;
Girish Palya8cd42a52025-06-05 21:04:29 +02001485 int *match_count = NULL;
Girish Palya19ef6b02025-05-28 20:28:21 +02001486 int is_forward = compl_shows_dir_forward();
Girish Palya8cd42a52025-06-05 21:04:29 +02001487 int is_cpt_completion = (cpt_sources_array != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001488
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001489 // Need to build the popup menu list.
1490 compl_match_arraysize = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001491
glepnira49c0772024-11-30 10:56:30 +01001492 // If the current match is the original text don't find the first
1493 // match after it, don't highlight anything.
1494 if (match_at_original_text(compl_shown_match))
1495 shown_match_ok = TRUE;
1496
1497 if (compl_leader.string != NULL
1498 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1499 && shown_match_ok == FALSE)
1500 compl_shown_match = compl_no_select ? compl_first_match
1501 : compl_first_match->cp_next;
1502
Girish Palya8cd42a52025-06-05 21:04:29 +02001503 if (is_cpt_completion)
1504 {
1505 match_count = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1506 if (match_count == NULL)
1507 return -1;
1508 }
1509
1510 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001511 do
1512 {
glepnird4088ed2024-12-31 10:55:22 +01001513 compl->cp_in_match_array = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001514
Girish Palyadc314052025-05-08 23:28:52 +02001515 // Apply 'smartcase' behavior during normal mode
1516 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1517 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1518 compl->cp_flags &= ~CP_ICASE;
1519
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001520 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001521 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001522 || ins_compl_equal(compl, compl_leader.string,
1523 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001524 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001525 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001526 // Limit number of items from each source if max_items is set.
1527 int match_limit_exceeded = FALSE;
1528 int cur_source = compl->cp_cpt_source_idx;
1529 if (is_forward && cur_source != -1 && is_cpt_completion)
glepnira49c0772024-11-30 10:56:30 +01001530 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001531 match_count[cur_source]++;
1532 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
1533 if (max_matches > 0 && match_count[cur_source] > max_matches)
1534 match_limit_exceeded = TRUE;
1535 }
1536
1537 if (!match_limit_exceeded)
1538 {
1539 ++compl_match_arraysize;
1540 compl->cp_in_match_array = TRUE;
1541 if (match_head == NULL)
1542 match_head = compl;
glepnira49c0772024-11-30 10:56:30 +01001543 else
Girish Palya8cd42a52025-06-05 21:04:29 +02001544 match_tail->cp_match_next = compl;
1545 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001546
Girish Palya8cd42a52025-06-05 21:04:29 +02001547 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001548 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001549 if (compl == compl_shown_match || did_find_shown_match)
1550 {
1551 // This item is the shown match or this is the
1552 // first displayed item after the shown match.
1553 compl_shown_match = compl;
1554 did_find_shown_match = TRUE;
1555 shown_match_ok = TRUE;
1556 }
1557 else
1558 // Remember this displayed match for when the
1559 // shown match is just below it.
1560 shown_compl = compl;
glepnira49c0772024-11-30 10:56:30 +01001561 cur = i;
glepnira49c0772024-11-30 10:56:30 +01001562 }
Girish Palya8cd42a52025-06-05 21:04:29 +02001563 else if (fuzzy_filter)
1564 {
1565 if (i == 0)
1566 shown_compl = compl;
1567
1568 if (!shown_match_ok && compl == compl_shown_match)
1569 {
1570 cur = i;
1571 shown_match_ok = TRUE;
1572 }
1573 }
1574 i++;
glepnira49c0772024-11-30 10:56:30 +01001575 }
glepnir80b66202024-11-27 21:53:53 +01001576 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001577
glepnirf400a0c2025-01-23 19:55:14 +01001578 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001579 {
1580 did_find_shown_match = TRUE;
1581
1582 // When the original text is the shown match don't set
1583 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001584 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001585 shown_match_ok = TRUE;
1586
1587 if (!shown_match_ok && shown_compl != NULL)
1588 {
1589 // The shown match isn't displayed, set it to the
1590 // previously displayed match.
1591 compl_shown_match = shown_compl;
1592 shown_match_ok = TRUE;
1593 }
1594 }
glepnira49c0772024-11-30 10:56:30 +01001595 compl = compl->cp_next;
1596 } while (compl != NULL && !is_first_match(compl));
1597
Girish Palya8cd42a52025-06-05 21:04:29 +02001598 vim_free(match_count);
1599
glepnira49c0772024-11-30 10:56:30 +01001600 if (compl_match_arraysize == 0)
1601 return -1;
1602
Girish Palya8cd42a52025-06-05 21:04:29 +02001603 if (fuzzy_filter && !compl_no_select && !shown_match_ok)
glepnirc0b7ca42025-02-13 20:27:44 +01001604 {
1605 compl_shown_match = shown_compl;
1606 shown_match_ok = TRUE;
1607 cur = 0;
1608 }
1609
glepnira49c0772024-11-30 10:56:30 +01001610 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1611 if (compl_match_array == NULL)
1612 return -1;
1613
1614 compl = match_head;
1615 i = 0;
1616 while (compl != NULL)
1617 {
glepnir6e199932024-12-14 21:13:27 +01001618 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1619 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001620 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1621 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
Girish Palya19ef6b02025-05-28 20:28:21 +02001622 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001623 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1624 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001625 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1626 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001627 match_next = compl->cp_match_next;
1628 compl->cp_match_next = NULL;
1629 compl = match_next;
1630 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001631
1632 if (!shown_match_ok) // no displayed match at all
1633 cur = -1;
1634
1635 return cur;
1636}
1637
1638/*
1639 * Show the popup menu for the list of matches.
1640 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1641 */
1642 void
1643ins_compl_show_pum(void)
1644{
1645 int i;
1646 int cur = -1;
1647 colnr_T col;
1648
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001649 if (!pum_wanted() || !pum_enough_matches())
1650 return;
1651
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001652 // Update the screen later, before drawing the popup menu over it.
1653 pum_call_update_screen();
1654
1655 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001656 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001657 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001658 else
1659 {
1660 // popup menu already exists, only need to find the current item.
1661 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001662 {
John Marriott5e6ea922024-11-23 14:01:57 +01001663 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001664 || compl_match_array[i].pum_text
1665 == compl_shown_match->cp_text[CPT_ABBR])
1666 {
1667 cur = i;
1668 break;
1669 }
glepnir19e1dd62025-05-08 22:50:38 +02001670 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001671 }
1672
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001673 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001674 {
1675#ifdef FEAT_EVAL
1676 if (compl_started && has_completechanged())
1677 trigger_complete_changed_event(cur);
1678#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001679 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001680 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001681
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001682 // In Replace mode when a $ is displayed at the end of the line only
1683 // part of the screen would be updated. We do need to redraw here.
1684 dollar_vcol = -1;
1685
1686 // Compute the screen column of the start of the completed text.
1687 // Use the cursor to get all wrapping and other settings right.
1688 col = curwin->w_cursor.col;
1689 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001690 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001691 pum_display(compl_match_array, compl_match_arraysize, cur);
1692 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001693
glepnircbb46b42024-02-03 18:11:13 +01001694 // After adding leader, set the current match to shown match.
1695 if (compl_started && compl_curr_match != compl_shown_match)
1696 compl_curr_match = compl_shown_match;
1697
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001698#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001699 if (has_completechanged())
1700 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001701#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001702}
1703
1704#define DICT_FIRST (1) // use just first element in "dict"
1705#define DICT_EXACT (2) // "dict" is the exact name of a file
1706
1707/*
glepnir40c1c332024-06-11 19:37:04 +02001708 * Get current completion leader
1709 */
1710 char_u *
1711ins_compl_leader(void)
1712{
John Marriott5e6ea922024-11-23 14:01:57 +01001713 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1714}
1715
1716/*
1717 * Get current completion leader length
1718 */
1719 size_t
1720ins_compl_leader_len(void)
1721{
1722 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001723}
1724
1725/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001726 * Add any identifiers that match the given pattern "pat" in the list of
1727 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001728 */
1729 static void
1730ins_compl_dictionaries(
1731 char_u *dict_start,
1732 char_u *pat,
1733 int flags, // DICT_FIRST and/or DICT_EXACT
1734 int thesaurus) // Thesaurus completion
1735{
1736 char_u *dict = dict_start;
1737 char_u *ptr;
1738 char_u *buf;
1739 regmatch_T regmatch;
1740 char_u **files;
1741 int count;
1742 int save_p_scs;
1743 int dir = compl_direction;
1744
1745 if (*dict == NUL)
1746 {
1747#ifdef FEAT_SPELL
1748 // When 'dictionary' is empty and spell checking is enabled use
1749 // "spell".
1750 if (!thesaurus && curwin->w_p_spell)
1751 dict = (char_u *)"spell";
1752 else
1753#endif
1754 return;
1755 }
1756
1757 buf = alloc(LSIZE);
1758 if (buf == NULL)
1759 return;
1760 regmatch.regprog = NULL; // so that we can goto theend
1761
1762 // If 'infercase' is set, don't use 'smartcase' here
1763 save_p_scs = p_scs;
1764 if (curbuf->b_p_inf)
1765 p_scs = FALSE;
1766
1767 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1768 // to only match at the start of a line. Otherwise just match the
1769 // pattern. Also need to double backslashes.
1770 if (ctrl_x_mode_line_or_eval())
1771 {
1772 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001773
1774 if (pat_esc == NULL)
1775 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001776 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001777 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001778 if (ptr == NULL)
1779 {
1780 vim_free(pat_esc);
1781 goto theend;
1782 }
1783 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1784 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1785 vim_free(pat_esc);
1786 vim_free(ptr);
1787 }
1788 else
1789 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001790 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001791 if (regmatch.regprog == NULL)
1792 goto theend;
1793 }
1794
1795 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1796 regmatch.rm_ic = ignorecase(pat);
1797 while (*dict != NUL && !got_int && !compl_interrupted)
1798 {
1799 // copy one dictionary file name into buf
1800 if (flags == DICT_EXACT)
1801 {
1802 count = 1;
1803 files = &dict;
1804 }
1805 else
1806 {
1807 // Expand wildcards in the dictionary name, but do not allow
1808 // backticks (for security, the 'dict' option may have been set in
1809 // a modeline).
1810 copy_option_part(&dict, buf, LSIZE, ",");
1811# ifdef FEAT_SPELL
1812 if (!thesaurus && STRCMP(buf, "spell") == 0)
1813 count = -1;
1814 else
1815# endif
1816 if (vim_strchr(buf, '`') != NULL
1817 || expand_wildcards(1, &buf, &count, &files,
1818 EW_FILE|EW_SILENT) != OK)
1819 count = 0;
1820 }
1821
1822# ifdef FEAT_SPELL
1823 if (count == -1)
1824 {
1825 // Complete from active spelling. Skip "\<" in the pattern, we
1826 // don't use it as a RE.
1827 if (pat[0] == '\\' && pat[1] == '<')
1828 ptr = pat + 2;
1829 else
1830 ptr = pat;
1831 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1832 }
1833 else
1834# endif
1835 if (count > 0) // avoid warning for using "files" uninit
1836 {
1837 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001838 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001839 if (flags != DICT_EXACT)
1840 FreeWild(count, files);
1841 }
1842 if (flags != 0)
1843 break;
1844 }
1845
1846theend:
1847 p_scs = save_p_scs;
1848 vim_regfree(regmatch.regprog);
1849 vim_free(buf);
1850}
1851
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001852/*
1853 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1854 * skipping the word at 'skip_word'. Returns OK on success.
1855 */
1856 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001857thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001858 char_u *fname,
1859 char_u **buf_arg,
1860 int dir,
1861 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001862{
1863 int status = OK;
1864 char_u *ptr;
1865 char_u *wstart;
1866
1867 // Add the other matches on the line
1868 ptr = *buf_arg;
1869 while (!got_int)
1870 {
1871 // Find start of the next word. Skip white
1872 // space and punctuation.
1873 ptr = find_word_start(ptr);
1874 if (*ptr == NUL || *ptr == NL)
1875 break;
1876 wstart = ptr;
1877
1878 // Find end of the word.
1879 if (has_mbyte)
1880 // Japanese words may have characters in
1881 // different classes, only separate words
1882 // with single-byte non-word characters.
1883 while (*ptr != NUL)
1884 {
1885 int l = (*mb_ptr2len)(ptr);
1886
1887 if (l < 2 && !vim_iswordc(*ptr))
1888 break;
1889 ptr += l;
1890 }
1891 else
1892 ptr = find_word_end(ptr);
1893
1894 // Add the word. Skip the regexp match.
1895 if (wstart != skip_word)
1896 {
1897 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001898 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001899 if (status == FAIL)
1900 break;
1901 }
1902 }
1903
1904 *buf_arg = ptr;
1905 return status;
1906}
1907
1908/*
1909 * Process "count" dictionary/thesaurus "files" and add the text matching
1910 * "regmatch".
1911 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001912 static void
1913ins_compl_files(
1914 int count,
1915 char_u **files,
1916 int thesaurus,
1917 int flags,
1918 regmatch_T *regmatch,
1919 char_u *buf,
1920 int *dir)
1921{
1922 char_u *ptr;
1923 int i;
1924 FILE *fp;
1925 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001926 char_u *leader = NULL;
1927 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001928 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001929 int score = 0;
1930 int len = 0;
1931 char_u *line_end = NULL;
1932
1933 if (in_fuzzy_collect)
1934 {
1935 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001936 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001937 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001938
1939 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1940 {
1941 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001942 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001943 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001944 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001945 vim_snprintf((char *)IObuff, IOSIZE,
1946 _("Scanning dictionary: %s"), (char *)files[i]);
1947 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1948 }
1949
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001950 if (fp == NULL)
1951 continue;
1952
1953 // Read dictionary file line by line.
1954 // Check each line for a match.
1955 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001956 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001957 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001958 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001959 {
glepnirf31cfa22025-03-06 21:59:13 +01001960 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001961 {
glepnirf31cfa22025-03-06 21:59:13 +01001962 ptr = regmatch->startp[0];
1963 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1964 : find_word_end(ptr);
1965 add_r = ins_compl_add_infercase(regmatch->startp[0],
1966 (int)(ptr - regmatch->startp[0]),
1967 p_ic, files[i], *dir, FALSE, 0);
1968 if (thesaurus)
1969 {
1970 // For a thesaurus, add all the words in the line
1971 ptr = buf;
1972 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1973 regmatch->startp[0]);
1974 }
1975 if (add_r == OK)
1976 // if dir was BACKWARD then honor it just once
1977 *dir = FORWARD;
1978 else if (add_r == FAIL)
1979 break;
1980 // avoid expensive call to vim_regexec() when at end
1981 // of line
1982 if (*ptr == '\n' || got_int)
1983 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001984 }
glepnirf31cfa22025-03-06 21:59:13 +01001985 }
1986 else if (in_fuzzy_collect && leader_len > 0)
1987 {
1988 line_end = find_line_end(ptr);
1989 while (ptr < line_end)
1990 {
1991 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1992 {
1993 char_u *end_ptr = ctrl_x_mode_line_or_eval()
1994 ? find_line_end(ptr) : find_word_end(ptr);
1995 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
1996 p_ic, files[i], *dir, FALSE, score);
1997 if (add_r == FAIL)
1998 break;
1999 ptr = end_ptr; // start from next word
2000 if (compl_get_longest && ctrl_x_mode_normal()
2001 && compl_first_match->cp_next
2002 && score == compl_first_match->cp_next->cp_score)
2003 compl_num_bests++;
2004 }
glepnirf31cfa22025-03-06 21:59:13 +01002005 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002006 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002007 line_breakcheck();
2008 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002009 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002010 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002011 }
2012}
2013
2014/*
2015 * Find the start of the next word.
2016 * Returns a pointer to the first char of the word. Also stops at a NUL.
2017 */
2018 char_u *
2019find_word_start(char_u *ptr)
2020{
2021 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002022 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002023 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2024 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002025 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002026 else
glepnir19e1dd62025-05-08 22:50:38 +02002027 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002028 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2029 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002030 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002031 return ptr;
2032}
2033
2034/*
2035 * Find the end of the word. Assumes it starts inside a word.
2036 * Returns a pointer to just after the word.
2037 */
2038 char_u *
2039find_word_end(char_u *ptr)
2040{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002041 if (has_mbyte)
2042 {
glepnir19e1dd62025-05-08 22:50:38 +02002043 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002044 if (start_class > 1)
2045 while (*ptr != NUL)
2046 {
2047 ptr += (*mb_ptr2len)(ptr);
2048 if (mb_get_class(ptr) != start_class)
2049 break;
2050 }
2051 }
2052 else
2053 while (vim_iswordc(*ptr))
2054 ++ptr;
2055 return ptr;
2056}
2057
2058/*
2059 * Find the end of the line, omitting CR and NL at the end.
2060 * Returns a pointer to just after the line.
2061 */
glepnirdd42b052025-03-08 16:52:55 +01002062 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002063find_line_end(char_u *ptr)
2064{
glepnir19e1dd62025-05-08 22:50:38 +02002065 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002066 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2067 --s;
2068 return s;
2069}
2070
2071/*
Girish Palyacbe53192025-04-14 22:13:15 +02002072 * Free a completion item in the list
2073 */
2074 static void
2075ins_compl_item_free(compl_T *match)
2076{
Girish Palyacbe53192025-04-14 22:13:15 +02002077 VIM_CLEAR_STRING(match->cp_str);
2078 // several entries may use the same fname, free it just once.
2079 if (match->cp_flags & CP_FREE_FNAME)
2080 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002081 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002082 vim_free(match->cp_text[i]);
2083#ifdef FEAT_EVAL
2084 clear_tv(&match->cp_user_data);
2085#endif
2086 vim_free(match);
2087}
2088
2089/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002090 * Free the list of completions
2091 */
2092 static void
2093ins_compl_free(void)
2094{
2095 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002096
John Marriott5e6ea922024-11-23 14:01:57 +01002097 VIM_CLEAR_STRING(compl_pattern);
2098 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002099
2100 if (compl_first_match == NULL)
2101 return;
2102
2103 ins_compl_del_pum();
2104 pum_clear();
2105
2106 compl_curr_match = compl_first_match;
2107 do
2108 {
2109 match = compl_curr_match;
2110 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002111 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002112 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002113 compl_first_match = compl_curr_match = NULL;
2114 compl_shown_match = NULL;
2115 compl_old_match = NULL;
2116}
2117
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002118/*
2119 * Reset/clear the completion state.
2120 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002121 void
2122ins_compl_clear(void)
2123{
2124 compl_cont_status = 0;
2125 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002126 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002127 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002128 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002129 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002130 compl_curr_win = NULL;
2131 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002132 VIM_CLEAR_STRING(compl_pattern);
2133 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002134 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002135 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002136 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002137 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002138#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002139 // clear v:completed_item
2140 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002141#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002142}
2143
2144/*
2145 * Return TRUE when Insert completion is active.
2146 */
2147 int
2148ins_compl_active(void)
2149{
2150 return compl_started;
2151}
2152
2153/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002154 * Return True when wp is the actual completion window
2155 */
2156 int
glepnircf7f0122025-04-15 19:02:00 +02002157ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002158{
glepnircf7f0122025-04-15 19:02:00 +02002159 return ins_compl_active() && wp == compl_curr_win
2160 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002161}
2162
2163/*
Girish Palyacbe53192025-04-14 22:13:15 +02002164 * Selected one of the matches. When FALSE, the match was either edited or
2165 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002166 */
2167 int
2168ins_compl_used_match(void)
2169{
2170 return compl_used_match;
2171}
2172
2173/*
2174 * Initialize get longest common string.
2175 */
2176 void
2177ins_compl_init_get_longest(void)
2178{
2179 compl_get_longest = FALSE;
2180}
2181
2182/*
2183 * Returns TRUE when insert completion is interrupted.
2184 */
2185 int
2186ins_compl_interrupted(void)
2187{
2188 return compl_interrupted;
2189}
2190
2191/*
2192 * Returns TRUE if the <Enter> key selects a match in the completion popup
2193 * menu.
2194 */
2195 int
2196ins_compl_enter_selects(void)
2197{
2198 return compl_enter_selects;
2199}
2200
2201/*
2202 * Return the column where the text starts that is being completed
2203 */
2204 colnr_T
2205ins_compl_col(void)
2206{
2207 return compl_col;
2208}
2209
2210/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002211 * Return the length in bytes of the text being completed
2212 */
2213 int
2214ins_compl_len(void)
2215{
2216 return compl_length;
2217}
2218
2219/*
glepnir94a045e2025-03-01 16:12:23 +01002220 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2221 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002222 */
2223 static int
2224ins_compl_has_preinsert(void)
2225{
glepnira2c55592025-02-28 17:43:42 +01002226 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002227 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2228 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002229}
2230
2231/*
2232 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2233 * the `compl_ins_end_col` range.
2234 */
2235 int
2236ins_compl_preinsert_effect(void)
2237{
2238 if (!ins_compl_has_preinsert())
2239 return FALSE;
2240
2241 return curwin->w_cursor.col < compl_ins_end_col;
2242}
2243
2244/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002245 * Delete one character before the cursor and show the subset of the matches
2246 * that match the word that is now before the cursor.
2247 * Returns the character to be used, NUL if the work is done and another char
2248 * to be got from the user.
2249 */
2250 int
2251ins_compl_bs(void)
2252{
2253 char_u *line;
2254 char_u *p;
2255
glepniredd4ac32025-01-29 18:53:51 +01002256 if (ins_compl_preinsert_effect())
2257 ins_compl_delete();
2258
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002259 line = ml_get_curline();
2260 p = line + curwin->w_cursor.col;
2261 MB_PTR_BACK(line, p);
2262
2263 // Stop completion when the whole word was deleted. For Omni completion
2264 // allow the word to be deleted, we won't match everything.
2265 // Respect the 'backspace' option.
2266 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002267 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2268 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002269 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2270 - compl_length < 0))
2271 return K_BS;
2272
2273 // Deleted more than what was used to find matches or didn't finish
2274 // finding all matches: need to look for matches all over again.
2275 if (curwin->w_cursor.col <= compl_col + compl_length
2276 || ins_compl_need_restart())
2277 ins_compl_restart();
2278
John Marriott5e6ea922024-11-23 14:01:57 +01002279 VIM_CLEAR_STRING(compl_leader);
2280 compl_leader.length = (size_t)((p - line) - compl_col);
2281 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2282 if (compl_leader.string == NULL)
2283 {
2284 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002285 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002286 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002287
2288 ins_compl_new_leader();
2289 if (compl_shown_match != NULL)
2290 // Make sure current match is not a hidden item.
2291 compl_curr_match = compl_shown_match;
2292 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002293}
2294
2295/*
2296 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2297 * be called.
2298 */
2299 static int
2300ins_compl_need_restart(void)
2301{
2302 // Return TRUE if we didn't complete finding matches or when the
2303 // 'completefunc' returned "always" in the "refresh" dictionary item.
2304 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002305 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002306 && compl_opt_refresh_always);
2307}
2308
2309/*
2310 * Called after changing "compl_leader".
2311 * Show the popup menu with a different set of matches.
2312 * May also search for matches again if the previous search was interrupted.
2313 */
2314 static void
2315ins_compl_new_leader(void)
2316{
2317 ins_compl_del_pum();
2318 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002319 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002320 compl_used_match = FALSE;
2321
2322 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002323 {
John Marriott5e6ea922024-11-23 14:01:57 +01002324 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002325 if (is_cpt_func_refresh_always())
2326 cpt_compl_refresh();
2327 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002328 else
2329 {
2330#ifdef FEAT_SPELL
2331 spell_bad_len = 0; // need to redetect bad word
2332#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002333 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002334 // the popup menu display the changed text before the cursor. Set
2335 // "compl_restarting" to avoid that the first match is inserted.
2336 pum_call_update_screen();
2337#ifdef FEAT_GUI
2338 if (gui.in_use)
2339 {
2340 // Show the cursor after the match, not after the redrawn text.
2341 setcursor();
2342 out_flush_cursor(FALSE, FALSE);
2343 }
2344#endif
2345 compl_restarting = TRUE;
2346 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2347 compl_cont_status = 0;
2348 compl_restarting = FALSE;
2349 }
2350
Girish Palyab8ee1cf2025-06-08 16:20:06 +02002351 // When 'cot' contains "fuzzy" set the cp_score
2352 if (get_cot_flags() & COT_FUZZY)
2353 set_fuzzy_score();
2354 // Sort the matches linked list based on fuzzy score
2355 int cur_cot_flags = get_cot_flags();
2356 if ((cur_cot_flags & COT_FUZZY) && !(cur_cot_flags & COT_NOSORT))
2357 {
2358 sort_compl_match_list(cp_compare_fuzzy);
2359 if ((cur_cot_flags & COT_NOINSERT) && !(cur_cot_flags & COT_NOSELECT)
2360 && compl_first_match)
2361 {
2362 compl_shown_match = compl_first_match;
2363 if (compl_shows_dir_forward())
2364 compl_shown_match = compl_first_match->cp_next;
2365 }
2366 }
2367
glepnir44180412025-02-20 22:09:48 +01002368 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002369
2370 // Show the popup menu with a different set of matches.
2371 ins_compl_show_pum();
2372
2373 // Don't let Enter select the original text when there is no popup menu.
2374 if (compl_match_array == NULL)
2375 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002376 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2377 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002378}
2379
2380/*
2381 * Return the length of the completion, from the completion start column to
2382 * the cursor column. Making sure it never goes below zero.
2383 */
2384 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002385get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002386{
2387 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002388 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002389}
2390
2391/*
2392 * Append one character to the match leader. May reduce the number of
2393 * matches.
2394 */
2395 void
2396ins_compl_addleader(int c)
2397{
glepnir19e1dd62025-05-08 22:50:38 +02002398 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002399
glepniredd4ac32025-01-29 18:53:51 +01002400 if (ins_compl_preinsert_effect())
2401 ins_compl_delete();
2402
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002403 if (stop_arrow() == FAIL)
2404 return;
2405 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2406 {
2407 char_u buf[MB_MAXBYTES + 1];
2408
2409 (*mb_char2bytes)(c, buf);
2410 buf[cc] = NUL;
2411 ins_char_bytes(buf, cc);
2412 if (compl_opt_refresh_always)
2413 AppendToRedobuff(buf);
2414 }
2415 else
2416 {
2417 ins_char(c);
2418 if (compl_opt_refresh_always)
2419 AppendCharToRedobuff(c);
2420 }
2421
2422 // If we didn't complete finding matches we must search again.
2423 if (ins_compl_need_restart())
2424 ins_compl_restart();
2425
2426 // When 'always' is set, don't reset compl_leader. While completing,
2427 // cursor doesn't point original position, changing compl_leader would
2428 // break redo.
2429 if (!compl_opt_refresh_always)
2430 {
John Marriott5e6ea922024-11-23 14:01:57 +01002431 VIM_CLEAR_STRING(compl_leader);
2432 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2433 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2434 compl_leader.length);
2435 if (compl_leader.string == NULL)
2436 {
2437 compl_leader.length = 0;
2438 return;
2439 }
2440
2441 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002442 }
2443}
2444
2445/*
2446 * Setup for finding completions again without leaving CTRL-X mode. Used when
2447 * BS or a key was typed while still searching for matches.
2448 */
2449 static void
2450ins_compl_restart(void)
2451{
2452 ins_compl_free();
2453 compl_started = FALSE;
2454 compl_matches = 0;
2455 compl_cont_status = 0;
2456 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002457 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002458}
2459
2460/*
2461 * Set the first match, the original text.
2462 */
2463 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002464ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002465{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002466 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002467 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2468 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002469 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002470 {
John Marriott5e6ea922024-11-23 14:01:57 +01002471 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002472 if (p != NULL)
2473 {
John Marriott5e6ea922024-11-23 14:01:57 +01002474 VIM_CLEAR_STRING(compl_first_match->cp_str);
2475 compl_first_match->cp_str.string = p;
2476 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002477 }
2478 }
2479 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002480 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002481 {
John Marriott5e6ea922024-11-23 14:01:57 +01002482 char_u *p = vim_strnsave(str, len);
2483 if (p != NULL)
2484 {
2485 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2486 compl_first_match->cp_prev->cp_str.string = p;
2487 compl_first_match->cp_prev->cp_str.length = len;
2488 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002489 }
2490}
2491
2492/*
2493 * Append one character to the match leader. May reduce the number of
2494 * matches.
2495 */
2496 void
2497ins_compl_addfrommatch(void)
2498{
2499 char_u *p;
2500 int len = (int)curwin->w_cursor.col - (int)compl_col;
2501 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002502
John Marriott5e6ea922024-11-23 14:01:57 +01002503 p = compl_shown_match->cp_str.string;
2504 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002505 {
John Marriott5e6ea922024-11-23 14:01:57 +01002506 size_t plen;
2507 compl_T *cp;
2508
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002509 // When still at the original match use the first entry that matches
2510 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002511 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002512 return;
2513
2514 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002515 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002516 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002517 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002518 {
John Marriott5e6ea922024-11-23 14:01:57 +01002519 if (compl_leader.string == NULL
2520 || ins_compl_equal(cp, compl_leader.string,
2521 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002522 {
John Marriott5e6ea922024-11-23 14:01:57 +01002523 p = cp->cp_str.string;
2524 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002525 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002526 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002527 }
John Marriott5e6ea922024-11-23 14:01:57 +01002528 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002529 return;
2530 }
2531 p += len;
2532 c = PTR2CHAR(p);
2533 ins_compl_addleader(c);
2534}
2535
2536/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002537 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002538 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2539 * compl_cont_mode and compl_cont_status.
2540 * Returns TRUE when the character is not to be inserted.
2541 */
2542 static int
2543set_ctrl_x_mode(int c)
2544{
glepnir05460682025-05-26 18:23:27 +02002545 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002546
2547 switch (c)
2548 {
2549 case Ctrl_E:
2550 case Ctrl_Y:
2551 // scroll the window one line up or down
2552 ctrl_x_mode = CTRL_X_SCROLL;
2553 if (!(State & REPLACE_FLAG))
2554 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2555 else
2556 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2557 edit_submode_pre = NULL;
2558 showmode();
2559 break;
2560 case Ctrl_L:
2561 // complete whole line
2562 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2563 break;
2564 case Ctrl_F:
2565 // complete filenames
2566 ctrl_x_mode = CTRL_X_FILES;
2567 break;
2568 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002569 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002570 ctrl_x_mode = CTRL_X_DICTIONARY;
2571 break;
2572 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002573 // When CTRL-R is followed by '=', don't trigger register completion
2574 // This allows expressions like <C-R>=func()<CR> to work normally
2575 if (vpeekc() == '=')
2576 break;
2577 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002578 break;
2579 case Ctrl_T:
2580 // complete words from a thesaurus
2581 ctrl_x_mode = CTRL_X_THESAURUS;
2582 break;
2583#ifdef FEAT_COMPL_FUNC
2584 case Ctrl_U:
2585 // user defined completion
2586 ctrl_x_mode = CTRL_X_FUNCTION;
2587 break;
2588 case Ctrl_O:
2589 // omni completion
2590 ctrl_x_mode = CTRL_X_OMNI;
2591 break;
2592#endif
2593 case 's':
2594 case Ctrl_S:
2595 // complete spelling suggestions
2596 ctrl_x_mode = CTRL_X_SPELL;
2597#ifdef FEAT_SPELL
2598 ++emsg_off; // Avoid getting the E756 error twice.
2599 spell_back_to_badword();
2600 --emsg_off;
2601#endif
2602 break;
2603 case Ctrl_RSB:
2604 // complete tag names
2605 ctrl_x_mode = CTRL_X_TAGS;
2606 break;
2607#ifdef FEAT_FIND_ID
2608 case Ctrl_I:
2609 case K_S_TAB:
2610 // complete keywords from included files
2611 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2612 break;
2613 case Ctrl_D:
2614 // complete definitions from included files
2615 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2616 break;
2617#endif
2618 case Ctrl_V:
2619 case Ctrl_Q:
2620 // complete vim commands
2621 ctrl_x_mode = CTRL_X_CMDLINE;
2622 break;
2623 case Ctrl_Z:
2624 // stop completion
2625 ctrl_x_mode = CTRL_X_NORMAL;
2626 edit_submode = NULL;
2627 showmode();
2628 retval = TRUE;
2629 break;
2630 case Ctrl_P:
2631 case Ctrl_N:
2632 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2633 // just started ^X mode, or there were enough ^X's to cancel
2634 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2635 // do normal expansion when interrupting a different mode (say
2636 // ^X^F^X^P or ^P^X^X^P, see below)
2637 // nothing changes if interrupting mode 0, (eg, the flag
2638 // doesn't change when going to ADDING mode -- Acevedo
2639 if (!(compl_cont_status & CONT_INTRPT))
2640 compl_cont_status |= CONT_LOCAL;
2641 else if (compl_cont_mode != 0)
2642 compl_cont_status &= ~CONT_LOCAL;
2643 // FALLTHROUGH
2644 default:
2645 // If we have typed at least 2 ^X's... for modes != 0, we set
2646 // compl_cont_status = 0 (eg, as if we had just started ^X
2647 // mode).
2648 // For mode 0, we set "compl_cont_mode" to an impossible
2649 // value, in both cases ^X^X can be used to restart the same
2650 // mode (avoiding ADDING mode).
2651 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2652 // 'complete' and local ^P expansions respectively.
2653 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2654 // mode -- Acevedo
2655 if (c == Ctrl_X)
2656 {
2657 if (compl_cont_mode != 0)
2658 compl_cont_status = 0;
2659 else
2660 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2661 }
2662 ctrl_x_mode = CTRL_X_NORMAL;
2663 edit_submode = NULL;
2664 showmode();
2665 break;
2666 }
2667
2668 return retval;
2669}
2670
2671/*
glepnir1c5a1202024-12-04 20:27:34 +01002672 * Trigger CompleteDone event and adds relevant information to v:event
2673 */
2674 static void
2675trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2676{
2677#if defined(FEAT_EVAL)
2678 save_v_event_T save_v_event;
2679 dict_T *v_event = get_v_event(&save_v_event);
2680 char_u *mode_str = NULL;
2681
2682 mode = mode & ~CTRL_X_WANT_IDENT;
2683 if (ctrl_x_mode_names[mode])
2684 mode_str = (char_u *)ctrl_x_mode_names[mode];
2685
2686 (void)dict_add_string(v_event, "complete_word",
2687 word == NULL ? (char_u *)"" : word);
2688 (void)dict_add_string(v_event, "complete_type",
2689 mode_str != NULL ? mode_str : (char_u *)"");
2690
2691 dict_set_items_ro(v_event);
2692#endif
2693 ins_apply_autocmds(EVENT_COMPLETEDONE);
2694
2695#if defined(FEAT_EVAL)
2696 restore_v_event(v_event, &save_v_event);
2697#endif
2698}
2699
2700/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002701 * Stop insert completion mode
2702 */
2703 static int
2704ins_compl_stop(int c, int prev_mode, int retval)
2705{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002706 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002707 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002708
glepnir84a75032025-03-15 09:59:22 +01002709 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002710 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002711 ins_compl_delete();
2712
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002713 // Get here when we have finished typing a sequence of ^N and
2714 // ^P or other completion characters in CTRL-X mode. Free up
2715 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002716 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002717 {
glepnir40891ba2025-02-10 22:18:00 +01002718 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002719
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002720 // If any of the original typed text has been changed, eg when
2721 // ignorecase is set, we must add back-spaces to the redo
2722 // buffer. We add as few as necessary to delete just the part
2723 // of the original text that has changed.
2724 // When using the longest match, edited the match or used
2725 // CTRL-E then don't use the current match.
2726 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002727 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002728 ins_compl_fixRedoBufForLeader(ptr);
2729 }
2730
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002731 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002732
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002733 // When completing whole lines: fix indent for 'cindent'.
2734 // Otherwise, break line if it's too long.
2735 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2736 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002737 // re-indent the current line
2738 if (want_cindent)
2739 {
2740 do_c_expr_indent();
2741 want_cindent = FALSE; // don't do it again
2742 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002743 }
2744 else
2745 {
2746 int prev_col = curwin->w_cursor.col;
2747
2748 // put the cursor on the last char, for 'tw' formatting
2749 if (prev_col > 0)
2750 dec_cursor();
2751 // only format when something was inserted
2752 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2753 insertchar(NUL, 0, -1);
2754 if (prev_col > 0
2755 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2756 inc_cursor();
2757 }
2758
2759 // If the popup menu is displayed pressing CTRL-Y means accepting
2760 // the selection without inserting anything. When
2761 // compl_enter_selects is set the Enter key does the same.
2762 if ((c == Ctrl_Y || (compl_enter_selects
2763 && (c == CAR || c == K_KENTER || c == NL)))
2764 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002765 {
2766 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002767 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002768 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002769
2770 // CTRL-E means completion is Ended, go back to the typed text.
2771 // but only do this, if the Popup is still visible
2772 if (c == Ctrl_E)
2773 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002774 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002775 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002776
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002777 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002778 if (compl_leader.string != NULL)
2779 {
2780 p = compl_leader.string;
2781 plen = compl_leader.length;
2782 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002783 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002784 {
2785 p = compl_orig_text.string;
2786 plen = compl_orig_text.length;
2787 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002788 if (p != NULL)
2789 {
2790 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002791
John Marriott5e6ea922024-11-23 14:01:57 +01002792 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002793 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002794 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002795 retval = TRUE;
2796 }
2797
2798 auto_format(FALSE, TRUE);
2799
2800 // Trigger the CompleteDonePre event to give scripts a chance to
2801 // act upon the completion before clearing the info, and restore
2802 // ctrl_x_mode, so that complete_info() can be used.
2803 ctrl_x_mode = prev_mode;
2804 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2805
2806 ins_compl_free();
2807 compl_started = FALSE;
2808 compl_matches = 0;
2809 if (!shortmess(SHM_COMPLETIONMENU))
2810 msg_clr_cmdline(); // necessary for "noshowmode"
2811 ctrl_x_mode = CTRL_X_NORMAL;
2812 compl_enter_selects = FALSE;
2813 if (edit_submode != NULL)
2814 {
2815 edit_submode = NULL;
2816 showmode();
2817 }
2818
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002819 if (c == Ctrl_C && cmdwin_type != 0)
2820 // Avoid the popup menu remains displayed when leaving the
2821 // command line window.
2822 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002823 // Indent now if a key was typed that is in 'cinkeys'.
2824 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2825 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002826 // Trigger the CompleteDone event to give scripts a chance to act
2827 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002828 trigger_complete_done_event(prev_mode, word);
2829 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002830
2831 return retval;
2832}
2833
2834/*
glepnircf7f0122025-04-15 19:02:00 +02002835 * Cancel completion.
2836 */
2837 int
2838ins_compl_cancel(void)
2839{
2840 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2841}
2842
2843/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002844 * Prepare for Insert mode completion, or stop it.
2845 * Called just after typing a character in Insert mode.
2846 * Returns TRUE when the character is not to be inserted;
2847 */
2848 int
2849ins_compl_prep(int c)
2850{
glepnir19e1dd62025-05-08 22:50:38 +02002851 int retval = FALSE;
2852 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002853
2854 // Forget any previous 'special' messages if this is actually
2855 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2856 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2857 edit_submode_extra = NULL;
2858
zeertzjq440d4cb2023-03-02 17:51:32 +00002859 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002860 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002861 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002862 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002863 return retval;
2864
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002865#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002866 // Ignore mouse events in a popup window
2867 if (is_mouse_key(c))
2868 {
2869 // Ignore drag and release events, the position does not need to be in
2870 // the popup and it may have just closed.
2871 if (c == K_LEFTRELEASE
2872 || c == K_LEFTRELEASE_NM
2873 || c == K_MIDDLERELEASE
2874 || c == K_RIGHTRELEASE
2875 || c == K_X1RELEASE
2876 || c == K_X2RELEASE
2877 || c == K_LEFTDRAG
2878 || c == K_MIDDLEDRAG
2879 || c == K_RIGHTDRAG
2880 || c == K_X1DRAG
2881 || c == K_X2DRAG)
2882 return retval;
2883 if (popup_visible)
2884 {
2885 int row = mouse_row;
2886 int col = mouse_col;
2887 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2888
2889 if (wp != NULL && WIN_IS_POPUP(wp))
2890 return retval;
2891 }
2892 }
2893#endif
2894
zeertzjqdca29d92021-08-31 19:12:51 +02002895 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2896 {
2897 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2898 || !vim_is_ctrl_x_key(c))
2899 {
2900 // Not starting another completion mode.
2901 ctrl_x_mode = CTRL_X_CMDLINE;
2902
2903 // CTRL-X CTRL-Z should stop completion without inserting anything
2904 if (c == Ctrl_Z)
2905 retval = TRUE;
2906 }
2907 else
2908 {
2909 ctrl_x_mode = CTRL_X_CMDLINE;
2910
2911 // Other CTRL-X keys first stop completion, then start another
2912 // completion mode.
2913 ins_compl_prep(' ');
2914 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2915 }
2916 }
2917
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002918 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002919 if (ctrl_x_mode_not_defined_yet()
2920 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002921 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002922 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002923 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002924 }
2925
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002926 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002927 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2928 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002929 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002930 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002931 {
2932 // We're already in CTRL-X mode, do we stay in it?
2933 if (!vim_is_ctrl_x_key(c))
2934 {
glepnir40891ba2025-02-10 22:18:00 +01002935 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002936 edit_submode = NULL;
2937 }
2938 showmode();
2939 }
2940
2941 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2942 {
2943 // Show error message from attempted keyword completion (probably
2944 // 'Pattern not found') until another key is hit, then go back to
2945 // showing what mode we are in.
2946 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002947 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002948 && c != Ctrl_R && !ins_compl_pum_key(c))
2949 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002950 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002951 }
2952 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2953 // Trigger the CompleteDone event to give scripts a chance to act
2954 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002955 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002956
LemonBoy2bf52dd2022-04-09 18:17:34 +01002957 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002958
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002959 // reset continue_* if we left expansion-mode, if we stay they'll be
2960 // (re)set properly in ins_complete()
2961 if (!vim_is_ctrl_x_key(c))
2962 {
2963 compl_cont_status = 0;
2964 compl_cont_mode = 0;
2965 }
2966
2967 return retval;
2968}
2969
2970/*
2971 * Fix the redo buffer for the completion leader replacing some of the typed
2972 * text. This inserts backspaces and appends the changed text.
2973 * "ptr" is the known leader text or NUL.
2974 */
2975 static void
2976ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2977{
John Marriott5e6ea922024-11-23 14:01:57 +01002978 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002979 char_u *p;
2980 char_u *ptr = ptr_arg;
2981
2982 if (ptr == NULL)
2983 {
John Marriott5e6ea922024-11-23 14:01:57 +01002984 if (compl_leader.string != NULL)
2985 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002986 else
2987 return; // nothing to do
2988 }
John Marriott5e6ea922024-11-23 14:01:57 +01002989 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002990 {
John Marriott5e6ea922024-11-23 14:01:57 +01002991 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002992 // Find length of common prefix between original text and new completion
2993 while (p[len] != NUL && p[len] == ptr[len])
2994 len++;
2995 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002996 if (len > 0)
2997 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002998 // Add backspace characters for each remaining character in
2999 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003000 for (p += len; *p != NUL; MB_PTR_ADV(p))
3001 AppendCharToRedobuff(K_BS);
3002 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003003 if (ptr != NULL)
3004 AppendToRedobuffLit(ptr + len, -1);
3005}
3006
3007/*
3008 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3009 * (depending on flag) starting from buf and looking for a non-scanned
3010 * buffer (other than curbuf). curbuf is special, if it is called with
3011 * buf=curbuf then it has to be the first call for a given flag/expansion.
3012 *
3013 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3014 */
3015 static buf_T *
3016ins_compl_next_buf(buf_T *buf, int flag)
3017{
glepnir19e1dd62025-05-08 22:50:38 +02003018 static win_T *wp = NULL;
3019 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003020
3021 if (flag == 'w') // just windows
3022 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003023 if (buf == curbuf || !win_valid(wp))
3024 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003025 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003026
3027 while (TRUE)
3028 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003029 // Move to next window (wrap to first window if at the end)
3030 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3031 // Break if we're back at start or found an unscanned buffer
3032 if (wp == curwin || !wp->w_buffer->b_scanned)
3033 break;
glepnir40891ba2025-02-10 22:18:00 +01003034 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003035 buf = wp->w_buffer;
3036 }
3037 else
glepnir40891ba2025-02-10 22:18:00 +01003038 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003039 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3040 // (unlisted buffers)
3041 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003042 while (TRUE)
3043 {
3044 // Move to next buffer (wrap to first buffer if at the end)
3045 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3046 // Break if we're back at start buffer
3047 if (buf == curbuf)
3048 break;
3049
3050 // Check buffer conditions based on flag
3051 if (flag == 'U')
3052 skip_buffer = buf->b_p_bl;
3053 else
3054 skip_buffer = !buf->b_p_bl ||
3055 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3056
3057 // Break if we found a buffer that matches our criteria
3058 if (!skip_buffer && !buf->b_scanned)
3059 break;
3060 }
3061 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003062 return buf;
3063}
3064
3065#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003066
3067# ifdef FEAT_EVAL
3068static callback_T cfu_cb; // 'completefunc' callback function
3069static callback_T ofu_cb; // 'omnifunc' callback function
3070static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3071# endif
3072
3073/*
3074 * Copy a global callback function to a buffer local callback.
3075 */
3076 static void
3077copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3078{
3079 free_callback(bufcb);
3080 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3081 copy_callback(bufcb, globcb);
3082}
3083
3084/*
3085 * Parse the 'completefunc' option value and set the callback function.
3086 * Invoked when the 'completefunc' option is set. The option value can be a
3087 * name of a function (string), or function(<name>) or funcref(<name>) or a
3088 * lambda expression.
3089 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003090 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003091did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003092{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003093 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3094 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003095
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003096 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003097
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003098 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003099}
3100
3101/*
3102 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003103 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003104 */
3105 void
3106set_buflocal_cfu_callback(buf_T *buf UNUSED)
3107{
3108# ifdef FEAT_EVAL
3109 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3110# endif
3111}
3112
3113/*
3114 * Parse the 'omnifunc' option value and set the callback function.
3115 * Invoked when the 'omnifunc' option is set. The option value can be a
3116 * name of a function (string), or function(<name>) or funcref(<name>) or a
3117 * lambda expression.
3118 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003119 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003120did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003121{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003122 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3123 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003124
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003125 set_buflocal_ofu_callback(curbuf);
3126 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003127}
3128
3129/*
3130 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003131 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003132 */
3133 void
3134set_buflocal_ofu_callback(buf_T *buf UNUSED)
3135{
3136# ifdef FEAT_EVAL
3137 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3138# endif
3139}
3140
3141/*
3142 * Parse the 'thesaurusfunc' option value and set the callback function.
3143 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3144 * name of a function (string), or function(<name>) or funcref(<name>) or a
3145 * lambda expression.
3146 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003147 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003148did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003149{
3150 int retval;
3151
zeertzjq6eda2692024-11-03 09:23:33 +01003152 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003153 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003154 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3155 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003156 else
3157 {
3158 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003159 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003160 // when using :set, free the local callback
3161 if (!(args->os_flags & OPT_GLOBAL))
3162 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003163 }
3164
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003165 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003166}
3167
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003168/*
3169 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003170 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003171 */
3172 int
3173set_ref_in_insexpand_funcs(int copyID)
3174{
glepnir19e1dd62025-05-08 22:50:38 +02003175 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003176 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3177 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3178
3179 return abort;
3180}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003181
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003182/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003183 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003184 */
3185 static char_u *
3186get_complete_funcname(int type)
3187{
3188 switch (type)
3189 {
3190 case CTRL_X_FUNCTION:
3191 return curbuf->b_p_cfu;
3192 case CTRL_X_OMNI:
3193 return curbuf->b_p_ofu;
3194 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003195 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003196 default:
3197 return (char_u *)"";
3198 }
3199}
3200
3201/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003202 * Get the callback to use for insert mode completion.
3203 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003204 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003205get_insert_callback(int type)
3206{
3207 if (type == CTRL_X_FUNCTION)
3208 return &curbuf->b_cfu_cb;
3209 if (type == CTRL_X_OMNI)
3210 return &curbuf->b_ofu_cb;
3211 // CTRL_X_THESAURUS
3212 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3213}
3214
3215/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003216 * Execute user defined complete function 'completefunc', 'omnifunc' or
3217 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003218 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3219 * Callback function "cb" is set if triggered by a function in the 'cpt'
3220 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003221 */
3222 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003223expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003224{
3225 list_T *matchlist = NULL;
3226 dict_T *matchdict = NULL;
3227 typval_T args[3];
3228 char_u *funcname;
3229 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003230 typval_T rettv;
3231 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003232 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003233 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003234
Girish Palyacbe53192025-04-14 22:13:15 +02003235 if (!is_cpt_function)
3236 {
3237 funcname = get_complete_funcname(type);
3238 if (*funcname == NUL)
3239 return;
3240 cb = get_insert_callback(type);
3241 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003242
3243 // Call 'completefunc' to obtain the list of matches.
3244 args[0].v_type = VAR_NUMBER;
3245 args[0].vval.v_number = 0;
3246 args[1].v_type = VAR_STRING;
3247 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3248 args[2].v_type = VAR_UNKNOWN;
3249
3250 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003251 // Lock the text to avoid weird things from happening. Also disallow
3252 // switching to another window, it should not be needed and may end up in
3253 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003254 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003255
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003256 retval = call_callback(cb, 0, &rettv, 2, args);
3257
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003258 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003259 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003260 {
3261 switch (rettv.v_type)
3262 {
3263 case VAR_LIST:
3264 matchlist = rettv.vval.v_list;
3265 break;
3266 case VAR_DICT:
3267 matchdict = rettv.vval.v_dict;
3268 break;
3269 case VAR_SPECIAL:
3270 if (rettv.vval.v_number == VVAL_NONE)
3271 compl_opt_suppress_empty = TRUE;
3272 // FALLTHROUGH
3273 default:
3274 // TODO: Give error message?
3275 clear_tv(&rettv);
3276 break;
3277 }
3278 }
zeertzjqcfe45652022-05-27 17:26:55 +01003279 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003280
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003281 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003282 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003283 validate_cursor();
3284 if (!EQUAL_POS(curwin->w_cursor, pos))
3285 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003286 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003287 goto theend;
3288 }
3289
3290 if (matchlist != NULL)
3291 ins_compl_add_list(matchlist);
3292 else if (matchdict != NULL)
3293 ins_compl_add_dict(matchdict);
3294
3295theend:
3296 // Restore State, it might have been changed.
3297 State = save_State;
3298
3299 if (matchdict != NULL)
3300 dict_unref(matchdict);
3301 if (matchlist != NULL)
3302 list_unref(matchlist);
3303}
3304#endif // FEAT_COMPL_FUNC
3305
3306#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003307
3308 static inline int
3309get_user_highlight_attr(char_u *hlname)
3310{
3311 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003312 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003313 return -1;
3314}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003315/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003316 * Add a match to the list of matches from a typeval_T.
3317 * If the given string is already in the list of completions, then return
3318 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3319 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003320 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003321 */
3322 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003323ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003324{
3325 char_u *word;
3326 int dup = FALSE;
3327 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003328 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003329 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003330 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003331 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003332 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003333 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003334 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003335
Bram Moolenaar08928322020-01-04 14:32:48 +01003336 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003337 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3338 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003339 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3340 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3341 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3342 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3343 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003344
glepnir0fe17f82024-10-08 22:26:44 +02003345 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003346 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003347
3348 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003349 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003350
Bram Moolenaard61efa52022-07-23 09:52:04 +01003351 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3352 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3353 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003354 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003355 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3356 dup = dict_get_number(tv->vval.v_dict, "dup");
3357 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3358 empty = dict_get_number(tv->vval.v_dict, "empty");
3359 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3360 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003361 flags |= CP_EQUAL;
3362 }
3363 else
3364 {
3365 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003366 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003367 }
3368 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003369 {
3370 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003371 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003372 }
glepnir508e7852024-07-25 21:39:08 +02003373 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003374 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003375 if (status != OK)
3376 clear_tv(&user_data);
3377 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003378}
3379
3380/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003381 * Add completions from a list.
3382 */
3383 static void
3384ins_compl_add_list(list_T *list)
3385{
3386 listitem_T *li;
3387 int dir = compl_direction;
3388
3389 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003390 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003391 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003392 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003393 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003394 // if dir was BACKWARD then honor it just once
3395 dir = FORWARD;
3396 else if (did_emsg)
3397 break;
3398 }
3399}
3400
3401/*
3402 * Add completions from a dict.
3403 */
3404 static void
3405ins_compl_add_dict(dict_T *dict)
3406{
3407 dictitem_T *di_refresh;
3408 dictitem_T *di_words;
3409
3410 // Check for optional "refresh" item.
3411 compl_opt_refresh_always = FALSE;
3412 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3413 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3414 {
3415 char_u *v = di_refresh->di_tv.vval.v_string;
3416
3417 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3418 compl_opt_refresh_always = TRUE;
3419 }
3420
3421 // Add completions from a "words" list.
3422 di_words = dict_find(dict, (char_u *)"words", 5);
3423 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3424 ins_compl_add_list(di_words->di_tv.vval.v_list);
3425}
3426
3427/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003428 * Start completion for the complete() function.
3429 * "startcol" is where the matched text starts (1 is first column).
3430 * "list" is the list of matches.
3431 */
3432 static void
3433set_completion(colnr_T startcol, list_T *list)
3434{
3435 int save_w_wrow = curwin->w_wrow;
3436 int save_w_leftcol = curwin->w_leftcol;
3437 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003438 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003439 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3440 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3441 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003442
3443 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003444 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003445 ins_compl_prep(' ');
3446 ins_compl_clear();
3447 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003448 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003449
3450 compl_direction = FORWARD;
3451 if (startcol > curwin->w_cursor.col)
3452 startcol = curwin->w_cursor.col;
3453 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003454 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003455 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3456 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003457 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3458 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003459 if (p_ic)
3460 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003461 if (compl_orig_text.string == NULL)
3462 {
3463 compl_orig_text.length = 0;
3464 return;
3465 }
3466 compl_orig_text.length = (size_t)compl_length;
3467 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003468 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3469 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003470 return;
3471
3472 ctrl_x_mode = CTRL_X_EVAL;
3473
3474 ins_compl_add_list(list);
3475 compl_matches = ins_compl_make_cyclic();
3476 compl_started = TRUE;
3477 compl_used_match = TRUE;
3478 compl_cont_status = 0;
3479
3480 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003481 int no_select = compl_no_select || compl_longest;
3482 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003483 {
3484 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003485 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003486 // Down/Up has no real effect.
3487 ins_complete(K_UP, FALSE);
3488 }
3489 else
3490 ins_complete(Ctrl_N, FALSE);
3491 compl_enter_selects = compl_no_insert;
3492
3493 // Lazily show the popup menu, unless we got interrupted.
3494 if (!compl_interrupted)
3495 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003496 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003497 out_flush();
3498}
3499
3500/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003501 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003502 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003503 void
3504f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003505{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003506 if (in_vim9script()
3507 && (check_for_number_arg(argvars, 0) == FAIL
3508 || check_for_list_arg(argvars, 1) == FAIL))
3509 return;
3510
Bram Moolenaar24959102022-05-07 20:01:16 +01003511 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003512 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003513 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003514 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003515 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003516
3517 // Check for undo allowed here, because if something was already inserted
3518 // the line was already saved for undo and this check isn't done.
3519 if (!undo_allowed())
3520 return;
3521
Bram Moolenaard83392a2022-09-01 12:22:46 +01003522 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003523 {
glepnir19e1dd62025-05-08 22:50:38 +02003524 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003525 if (startcol > 0)
3526 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003527 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003528}
3529
3530/*
3531 * "complete_add()" function
3532 */
3533 void
3534f_complete_add(typval_T *argvars, typval_T *rettv)
3535{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003536 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003537 return;
3538
Bram Moolenaar440cf092021-04-03 20:13:30 +02003539 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003540}
3541
3542/*
3543 * "complete_check()" function
3544 */
3545 void
3546f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3547{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003548 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003549 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003550
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003551 ins_compl_check_keys(0, TRUE);
3552 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003553
3554 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003555}
3556
3557/*
glepnirbcd59952025-04-24 21:48:35 +02003558 * Add match item to the return list.
3559 * Returns FAIL if out of memory, OK otherwise.
3560 */
3561 static int
3562add_match_to_list(
3563 typval_T *rettv,
3564 char_u *str,
3565 int len,
3566 int pos)
3567{
3568 list_T *match;
3569 int ret;
3570
3571 match = list_alloc();
3572 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003573 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003574
3575 if ((ret = list_append_number(match, pos + 1)) == FAIL
3576 || (ret = list_append_string(match, str, len)) == FAIL
3577 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3578 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003579 vim_free(match);
3580 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003581 }
3582
3583 return OK;
3584}
3585
3586/*
3587 * "complete_match()" function
3588 */
3589 void
3590f_complete_match(typval_T *argvars, typval_T *rettv)
3591{
3592 linenr_T lnum;
3593 colnr_T col;
3594 char_u *line = NULL;
3595 char_u *ise = NULL;
3596 regmatch_T regmatch;
3597 char_u *before_cursor = NULL;
3598 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003599 int bytepos = 0;
3600 char_u part[MAXPATHL];
3601 int ret;
3602
3603 if (rettv_list_alloc(rettv) == FAIL)
3604 return;
3605
3606 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3607
3608 if (argvars[0].v_type == VAR_UNKNOWN)
3609 {
3610 lnum = curwin->w_cursor.lnum;
3611 col = curwin->w_cursor.col;
3612 }
3613 else if (argvars[1].v_type == VAR_UNKNOWN)
3614 {
3615 emsg(_(e_invalid_argument));
3616 return;
3617 }
3618 else
3619 {
3620 lnum = (linenr_T)tv_get_number(&argvars[0]);
3621 col = (colnr_T)tv_get_number(&argvars[1]);
3622 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3623 {
3624 semsg(_(e_invalid_line_number_nr), lnum);
3625 return;
3626 }
3627 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3628 {
3629 semsg(_(e_invalid_column_number_nr), col + 1);
3630 return;
3631 }
3632 }
3633
3634 line = ml_get_buf(curbuf, lnum, FALSE);
3635 if (line == NULL)
3636 return;
3637
3638 before_cursor = vim_strnsave(line, col);
3639 if (before_cursor == NULL)
3640 return;
3641
3642 if (ise == NULL || *ise == NUL)
3643 {
3644 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3645 if (regmatch.regprog != NULL)
3646 {
3647 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3648 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003649 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003650 regmatch.endp[0] - regmatch.startp[0]);
3651 if (trig == NULL)
3652 {
3653 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003654 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003655 return;
3656 }
3657
Christian Brabandt3accf042025-04-25 19:01:06 +02003658 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003659 ret = add_match_to_list(rettv, trig, -1, bytepos);
3660 vim_free(trig);
3661 if (ret == FAIL)
3662 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003663 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003664 vim_regfree(regmatch.regprog);
3665 return;
3666 }
3667 }
3668 vim_regfree(regmatch.regprog);
3669 }
3670 }
3671 else
3672 {
glepnir08db2f42025-05-14 20:26:19 +02003673 char_u *p = ise;
3674 char_u *p_space = NULL;
3675
glepnirbcd59952025-04-24 21:48:35 +02003676 cur_end = before_cursor + (int)STRLEN(before_cursor);
3677
3678 while (*p != NUL)
3679 {
glepnir8d0e42b2025-05-12 20:28:28 +02003680 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003681 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003682 {
glepnir08db2f42025-05-14 20:26:19 +02003683 len = p - p_space - 1;
3684 memcpy(part, p_space + 1, len);
3685 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003686 }
3687 else
glepnir08db2f42025-05-14 20:26:19 +02003688 {
3689 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3690 if (next_comma && *(next_comma + 1) == ' ')
3691 p_space = next_comma;
3692
glepnir8d0e42b2025-05-12 20:28:28 +02003693 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003694 }
glepnirbcd59952025-04-24 21:48:35 +02003695
3696 if (len > 0 && len <= col)
3697 {
3698 if (STRNCMP(cur_end - len, part, len) == 0)
3699 {
3700 bytepos = col - len;
3701 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3702 {
3703 vim_free(before_cursor);
3704 return;
3705 }
3706 }
3707 }
3708 }
3709 }
3710
3711 vim_free(before_cursor);
3712}
3713
3714/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003715 * Return Insert completion mode name string
3716 */
3717 static char_u *
3718ins_compl_mode(void)
3719{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003720 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003721 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3722
3723 return (char_u *)"";
3724}
3725
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003726/*
3727 * Assign the sequence number to all the completion matches which don't have
3728 * one assigned yet.
3729 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003730 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003731ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003732{
3733 int number = 0;
3734 compl_T *match;
3735
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003736 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003737 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003738 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003739 // This should normally succeed already at the first loop
3740 // cycle, so it's fast!
3741 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003742 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003743 if (match->cp_number != -1)
3744 {
3745 number = match->cp_number;
3746 break;
3747 }
3748 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003749 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003750 for (match = match->cp_next;
3751 match != NULL && match->cp_number == -1;
3752 match = match->cp_next)
3753 match->cp_number = ++number;
3754 }
3755 else // BACKWARD
3756 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003757 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003758 // number. This should normally succeed already at the
3759 // first loop cycle, so it's fast!
3760 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003761 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003762 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003763 if (match->cp_number != -1)
3764 {
3765 number = match->cp_number;
3766 break;
3767 }
glepnir40891ba2025-02-10 22:18:00 +01003768 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003769 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003770 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003771 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003772 for (match = match->cp_prev; match
3773 && match->cp_number == -1;
3774 match = match->cp_prev)
3775 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003776 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003777 }
3778}
3779
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003780/*
glepnir037b0282025-01-16 14:37:44 +01003781 * Fill the dict of complete_info
3782 */
3783 static void
3784fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3785{
3786 dict_add_string(di, "word", match->cp_str.string);
3787 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3788 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3789 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3790 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3791 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003792 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003793 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003794 // Add an empty string for backwards compatibility
3795 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003796 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003797 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003798}
3799
3800/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003801 * Get complete information
3802 */
3803 static void
3804get_complete_info(list_T *what_list, dict_T *retdict)
3805{
3806 int ret = OK;
3807 listitem_T *item;
3808#define CI_WHAT_MODE 0x01
3809#define CI_WHAT_PUM_VISIBLE 0x02
3810#define CI_WHAT_ITEMS 0x04
3811#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003812#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003813#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003814#define CI_WHAT_ALL 0xff
3815 int what_flag;
3816
3817 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003818 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003819 else
3820 {
3821 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003822 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003823 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003824 {
3825 char_u *what = tv_get_string(&item->li_tv);
3826
3827 if (STRCMP(what, "mode") == 0)
3828 what_flag |= CI_WHAT_MODE;
3829 else if (STRCMP(what, "pum_visible") == 0)
3830 what_flag |= CI_WHAT_PUM_VISIBLE;
3831 else if (STRCMP(what, "items") == 0)
3832 what_flag |= CI_WHAT_ITEMS;
3833 else if (STRCMP(what, "selected") == 0)
3834 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003835 else if (STRCMP(what, "completed") == 0)
3836 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003837 else if (STRCMP(what, "matches") == 0)
3838 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003839 }
3840 }
3841
3842 if (ret == OK && (what_flag & CI_WHAT_MODE))
3843 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3844
3845 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3846 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3847
glepnir037b0282025-01-16 14:37:44 +01003848 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3849 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003850 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003851 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003852 dict_T *di;
3853 compl_T *match;
3854 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003855 int has_items = what_flag & CI_WHAT_ITEMS;
3856 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003857 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003858
glepnird4088ed2024-12-31 10:55:22 +01003859 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003860 {
3861 li = list_alloc();
3862 if (li == NULL)
3863 return;
glepnird4088ed2024-12-31 10:55:22 +01003864 ret = dict_add_list(retdict, (has_matches && !has_items)
3865 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003866 }
3867 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3868 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3869 ins_compl_update_sequence_numbers();
3870 if (ret == OK && compl_first_match != NULL)
3871 {
3872 int list_idx = 0;
3873 match = compl_first_match;
3874 do
3875 {
3876 if (!match_at_original_text(match))
3877 {
glepnird4088ed2024-12-31 10:55:22 +01003878 if (has_items
3879 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003880 {
3881 di = dict_alloc();
3882 if (di == NULL)
3883 return;
3884 ret = list_append_dict(li, di);
3885 if (ret != OK)
3886 return;
glepnir037b0282025-01-16 14:37:44 +01003887 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003888 }
glepnird4088ed2024-12-31 10:55:22 +01003889 if (compl_curr_match != NULL
3890 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003891 selected_idx = list_idx;
Girish Palya8cd42a52025-06-05 21:04:29 +02003892 if (match->cp_in_match_array)
Girish Palya0ac1eb32025-04-16 20:18:33 +02003893 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003894 }
3895 match = match->cp_next;
3896 }
3897 while (match != NULL && !is_first_match(match));
3898 }
3899 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3900 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003901
glepnir037b0282025-01-16 14:37:44 +01003902 if (ret == OK && selected_idx != -1 && has_completed)
3903 {
3904 di = dict_alloc();
3905 if (di == NULL)
3906 return;
3907 fill_complete_info_dict(di, compl_curr_match, FALSE);
3908 ret = dict_add_dict(retdict, "completed", di);
3909 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003910 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003911}
3912
3913/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003914 * "complete_info()" function
3915 */
3916 void
3917f_complete_info(typval_T *argvars, typval_T *rettv)
3918{
3919 list_T *what_list = NULL;
3920
Bram Moolenaar93a10962022-06-16 11:42:09 +01003921 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003922 return;
3923
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003924 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3925 return;
3926
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003927 if (argvars[0].v_type != VAR_UNKNOWN)
3928 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003929 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003930 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003931 what_list = argvars[0].vval.v_list;
3932 }
3933 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003934}
3935#endif
3936
3937/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003938 * Returns TRUE when using a user-defined function for thesaurus completion.
3939 */
3940 static int
3941thesaurus_func_complete(int type UNUSED)
3942{
3943#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003944 return type == CTRL_X_THESAURUS
3945 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003946#else
3947 return FALSE;
3948#endif
3949}
3950
3951/*
Girish Palya7c621052025-05-26 19:41:59 +02003952 * Check if 'cpt' list index can be advanced to the next completion source.
3953 */
3954 static int
3955may_advance_cpt_index(char_u *cpt)
3956{
3957 char_u *p = cpt;
3958
Girish Palya98c29db2025-06-01 19:40:00 +02003959 if (cpt_sources_index == -1)
3960 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02003961 while (*p == ',' || *p == ' ') // Skip delimiters
3962 p++;
3963 return (*p != NUL);
3964}
3965
3966/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003967 * Return value of process_next_cpt_value()
3968 */
3969enum
3970{
3971 INS_COMPL_CPT_OK = 1,
3972 INS_COMPL_CPT_CONT,
3973 INS_COMPL_CPT_END
3974};
3975
3976/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003977 * state information used for getting the next set of insert completion
3978 * matches.
3979 */
3980typedef struct
3981{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003982 char_u *e_cpt_copy; // copy of 'complete'
3983 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003984 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003985 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003986 pos_T prev_match_pos; // previous match position
3987 int set_match_pos; // save first_match_pos/last_match_pos
3988 pos_T first_match_pos; // first match position
3989 pos_T last_match_pos; // last match position
3990 int found_all; // found all matches of a certain type.
3991 char_u *dict; // dictionary file to search
3992 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003993 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003994} ins_compl_next_state_T;
3995
3996/*
3997 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003998 *
3999 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004000 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004001 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004002 * st->found_all - all matches of this type are found
4003 * st->ins_buf - search for completions in this buffer
4004 * st->first_match_pos - position of the first completion match
4005 * st->last_match_pos - position of the last completion match
4006 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004007 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004008 * st->dict - name of the dictionary or thesaurus file to search
4009 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004010 *
4011 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004012 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4013 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004014 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004015 */
4016 static int
4017process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004018 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004019 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004020 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004021 int fuzzy_collect,
4022 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004023{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004024 int compl_type = -1;
4025 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004026
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004027 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004028 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004029
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004030 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4031 st->e_cpt++;
4032
4033 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004034 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004035 st->ins_buf = curbuf;
4036 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004037 // Move the cursor back one character so that ^N can match the
4038 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004039 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004040 {
4041 // Move the cursor to after the last character in the
4042 // buffer, so that word at start of buffer is found
4043 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004044 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004045 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004046 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004047 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004048 compl_type = 0;
4049
4050 // Remember the first match so that the loop stops when we
4051 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004052 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004053 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004054 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004055 && (st->ins_buf = ins_compl_next_buf(
4056 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004057 {
4058 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004059 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004060 {
4061 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004062 st->first_match_pos.col = st->last_match_pos.col = 0;
4063 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4064 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004065 compl_type = 0;
4066 }
4067 else // unloaded buffer, scan like dictionary
4068 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004069 st->found_all = TRUE;
4070 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004071 {
4072 status = INS_COMPL_CPT_CONT;
4073 goto done;
4074 }
4075 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004076 st->dict = st->ins_buf->b_fname;
4077 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004078 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004079 if (!shortmess(SHM_COMPLETIONSCAN))
4080 {
4081 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4082 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4083 st->ins_buf->b_fname == NULL
4084 ? buf_spname(st->ins_buf)
4085 : st->ins_buf->b_sfname == NULL
4086 ? st->ins_buf->b_fname
4087 : st->ins_buf->b_sfname);
4088 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4089 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004090 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004091 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004092 status = INS_COMPL_CPT_END;
4093 else
4094 {
4095 if (ctrl_x_mode_line_or_eval())
4096 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004097 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004098 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004099 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004100 compl_type = CTRL_X_DICTIONARY;
4101 else
4102 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004103 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004104 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004105 st->dict = st->e_cpt;
4106 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004107 }
4108 }
Girish Palyacbe53192025-04-14 22:13:15 +02004109#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004110 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004111 {
4112 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004113 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004114 if (!st->func_cb)
4115 compl_type = -1;
4116 }
4117#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004118#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004119 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004120 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004121 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004122 compl_type = CTRL_X_PATH_DEFINES;
4123#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004124 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004125 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004126 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004127 if (!shortmess(SHM_COMPLETIONSCAN))
4128 {
4129 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4130 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4131 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4132 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004133 }
4134 else
4135 compl_type = -1;
4136
4137 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004138 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004139 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004140
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004141 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004142 if (compl_type == -1)
4143 status = INS_COMPL_CPT_CONT;
4144 }
4145
4146done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004147 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004148 return status;
4149}
4150
4151#ifdef FEAT_FIND_ID
4152/*
4153 * Get the next set of identifiers or defines matching "compl_pattern" in
4154 * included files.
4155 */
4156 static void
4157get_next_include_file_completion(int compl_type)
4158{
John Marriott5e6ea922024-11-23 14:01:57 +01004159 find_pattern_in_path(compl_pattern.string, compl_direction,
4160 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004161 (compl_type == CTRL_X_PATH_DEFINES
4162 && !(compl_cont_status & CONT_SOL))
4163 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004164 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004165}
4166#endif
4167
4168/*
4169 * Get the next set of words matching "compl_pattern" in dictionary or
4170 * thesaurus files.
4171 */
4172 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004173get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004174{
4175#ifdef FEAT_COMPL_FUNC
4176 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004177 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004178 else
4179#endif
4180 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004181 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004182 : (compl_type == CTRL_X_THESAURUS
4183 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4184 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004185 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004186 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004187 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004188}
4189
4190/*
4191 * Get the next set of tag names matching "compl_pattern".
4192 */
4193 static void
4194get_next_tag_completion(void)
4195{
4196 int save_p_ic;
4197 char_u **matches;
4198 int num_matches;
4199
4200 // set p_ic according to p_ic, p_scs and pat for find_tags().
4201 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004202 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004203
4204 // Find up to TAG_MANY matches. Avoids that an enormous number
4205 // of matches is found when compl_pattern is empty
4206 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004207 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004208 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004209 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004210 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4211 ins_compl_add_matches(num_matches, matches, p_ic);
4212 g_tag_at_cursor = FALSE;
4213 p_ic = save_p_ic;
4214}
4215
4216/*
glepnir8159fb12024-07-17 20:32:54 +02004217 * Compare function for qsort
4218 */
glepnirf31cfa22025-03-06 21:59:13 +01004219 static int
4220compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004221{
4222 int idx_a = *(const int *)a;
4223 int idx_b = *(const int *)b;
4224 int score_a = compl_fuzzy_scores[idx_a];
4225 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004226 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4227 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004228}
4229
4230/*
glepnirf31cfa22025-03-06 21:59:13 +01004231 * insert prefix with redraw
4232 */
4233 static void
4234ins_compl_longest_insert(char_u *prefix)
4235{
4236 ins_compl_delete();
4237 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4238 ins_redraw(FALSE);
4239}
4240
4241/*
4242 * Calculate the longest common prefix among the best fuzzy matches
4243 * stored in compl_best_matches, and insert it as the longest.
4244 */
4245 static void
4246fuzzy_longest_match(void)
4247{
4248 char_u *prefix = NULL;
4249 int prefix_len = 0;
4250 int i = 0;
4251 int j = 0;
4252 char_u *match_str = NULL;
4253 char_u *prefix_ptr = NULL;
4254 char_u *match_ptr = NULL;
4255 char_u *leader = NULL;
4256 size_t leader_len = 0;
4257 compl_T *compl = NULL;
4258 int more_candidates = FALSE;
4259 compl_T *nn_compl = NULL;
4260
4261 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004262 return;
glepnirf31cfa22025-03-06 21:59:13 +01004263
4264 nn_compl = compl_first_match->cp_next->cp_next;
4265 if (nn_compl && nn_compl != compl_first_match)
4266 more_candidates = TRUE;
4267
4268 compl = ctrl_x_mode_whole_line() ? compl_first_match
4269 : compl_first_match->cp_next;
4270 if (compl_num_bests == 1)
4271 {
4272 // no more candidates insert the match str
4273 if (!more_candidates)
4274 {
4275 ins_compl_longest_insert(compl->cp_str.string);
4276 compl_num_bests = 0;
4277 }
4278 compl_num_bests = 0;
4279 return;
4280 }
4281
4282 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4283 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004284 return;
glepnirf31cfa22025-03-06 21:59:13 +01004285 while (compl != NULL && i < compl_num_bests)
4286 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004287 compl_best_matches[i] = compl;
4288 compl = compl->cp_next;
4289 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004290 }
4291
4292 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004293 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004294
4295 for (i = 1; i < compl_num_bests; i++)
4296 {
4297 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004298 prefix_ptr = prefix;
4299 match_ptr = match_str;
4300 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004301
4302 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4303 {
4304 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4305 break;
4306
4307 MB_PTR_ADV(prefix_ptr);
4308 MB_PTR_ADV(match_ptr);
4309 j++;
4310 }
4311
4312 if (j > 0)
4313 prefix_len = j;
4314 }
4315
4316 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004317 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004318
4319 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004320 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004321 goto end;
4322
zeertzjq4422de62025-03-07 19:06:02 +01004323 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004324 if (prefix != NULL)
4325 {
4326 ins_compl_longest_insert(prefix);
4327 compl_cfc_longest_ins = TRUE;
4328 vim_free(prefix);
4329 }
4330
4331end:
4332 vim_free(compl_best_matches);
4333 compl_best_matches = NULL;
4334 compl_num_bests = 0;
4335}
4336
4337/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004338 * Get the next set of filename matching "compl_pattern".
4339 */
4340 static void
4341get_next_filename_completion(void)
4342{
4343 char_u **matches;
4344 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004345 char_u *ptr;
4346 garray_T fuzzy_indices;
4347 int i;
4348 int score;
4349 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004350 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004351 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004352 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004353 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004354 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4355 int max_score = 0;
4356 int current_score = 0;
4357 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004358
glepnirb9de1a02024-08-02 19:14:38 +02004359#ifdef BACKSLASH_IN_FILENAME
4360 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4361 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4362#else
4363 char pathsep = PATHSEP;
4364#endif
4365
glepnirf31cfa22025-03-06 21:59:13 +01004366 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004367 {
glepnirb9de1a02024-08-02 19:14:38 +02004368#ifdef BACKSLASH_IN_FILENAME
4369 if (curbuf->b_p_csl[0] == 's')
4370 {
John Marriott5e6ea922024-11-23 14:01:57 +01004371 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004372 {
4373 if (leader[i] == '\\')
4374 leader[i] = '/';
4375 }
4376 }
4377 else if (curbuf->b_p_csl[0] == 'b')
4378 {
John Marriott5e6ea922024-11-23 14:01:57 +01004379 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004380 {
4381 if (leader[i] == '/')
4382 leader[i] = '\\';
4383 }
4384 }
4385#endif
4386 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004387 if (last_sep == NULL)
4388 {
4389 // No path separator or separator is the last character,
4390 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004391 VIM_CLEAR_STRING(compl_pattern);
4392 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4393 if (compl_pattern.string == NULL)
4394 return;
4395 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004396 }
4397 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004398 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004399 else
4400 {
4401 // Split leader into path and file parts
4402 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004403 char_u *path_with_wildcard;
4404
4405 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004406 if (path_with_wildcard != NULL)
4407 {
John Marriott5e6ea922024-11-23 14:01:57 +01004408 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4409 VIM_CLEAR_STRING(compl_pattern);
4410 compl_pattern.string = path_with_wildcard;
4411 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004412
4413 // Move leader to the file part
4414 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004415 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004416 }
4417 }
glepnir8159fb12024-07-17 20:32:54 +02004418 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004419
John Marriott5e6ea922024-11-23 14:01:57 +01004420 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004421 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4422 return;
4423
4424 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004425 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004426#ifdef BACKSLASH_IN_FILENAME
4427 if (curbuf->b_p_csl[0] != NUL)
4428 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004429 for (i = 0; i < num_matches; ++i)
4430 {
glepnir8159fb12024-07-17 20:32:54 +02004431 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004432 while (*ptr != NUL)
4433 {
4434 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4435 *ptr = '/';
4436 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4437 *ptr = '\\';
4438 ptr += (*mb_ptr2len)(ptr);
4439 }
4440 }
4441 }
4442#endif
glepnir8159fb12024-07-17 20:32:54 +02004443
glepnirf31cfa22025-03-06 21:59:13 +01004444 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004445 {
4446 ga_init2(&fuzzy_indices, sizeof(int), 10);
4447 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4448
4449 for (i = 0; i < num_matches; i++)
4450 {
4451 ptr = matches[i];
4452 score = fuzzy_match_str(ptr, leader);
4453 if (score > 0)
4454 {
4455 if (ga_grow(&fuzzy_indices, 1) == OK)
4456 {
4457 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4458 compl_fuzzy_scores[i] = score;
4459 fuzzy_indices.ga_len++;
4460 }
4461 }
4462 }
4463
Christian Brabandt220474d2024-07-20 13:26:44 +02004464 // prevent qsort from deref NULL pointer
4465 if (fuzzy_indices.ga_len > 0)
4466 {
glepnirf31cfa22025-03-06 21:59:13 +01004467 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004468 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4469 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004470
Christian Brabandt220474d2024-07-20 13:26:44 +02004471 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004472 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004473 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004474 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4475 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004476 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4477 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004478 dir = FORWARD;
4479
4480 if (need_collect_bests)
4481 {
4482 if (i == 0 || current_score == max_score)
4483 {
4484 compl_num_bests++;
4485 max_score = current_score;
4486 }
4487 }
4488 }
glepnir8159fb12024-07-17 20:32:54 +02004489
Christian Brabandt220474d2024-07-20 13:26:44 +02004490 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004491 }
glepnir6b6280c2024-07-27 16:25:45 +02004492 else if (leader_len > 0)
4493 {
4494 FreeWild(num_matches, matches);
4495 num_matches = 0;
4496 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004497
glepnir8159fb12024-07-17 20:32:54 +02004498 vim_free(compl_fuzzy_scores);
4499 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004500
4501 if (compl_num_bests > 0 && compl_get_longest)
4502 fuzzy_longest_match();
4503 return;
glepnir8159fb12024-07-17 20:32:54 +02004504 }
4505
glepnir6b6280c2024-07-27 16:25:45 +02004506 if (num_matches > 0)
4507 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004508}
4509
4510/*
4511 * Get the next set of command-line completions matching "compl_pattern".
4512 */
4513 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004514get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004515{
4516 char_u **matches;
4517 int num_matches;
4518
John Marriott5e6ea922024-11-23 14:01:57 +01004519 if (expand_cmdline(&compl_xp, compl_pattern.string,
4520 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004521 ins_compl_add_matches(num_matches, matches, FALSE);
4522}
4523
4524/*
4525 * Get the next set of spell suggestions matching "compl_pattern".
4526 */
4527 static void
4528get_next_spell_completion(linenr_T lnum UNUSED)
4529{
4530#ifdef FEAT_SPELL
4531 char_u **matches;
4532 int num_matches;
4533
John Marriott5e6ea922024-11-23 14:01:57 +01004534 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004535 if (num_matches > 0)
4536 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004537 else
4538 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004539#endif
4540}
4541
4542/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004543 * Return the next word or line from buffer "ins_buf" at position
4544 * "cur_match_pos" for completion. The length of the match is set in "len".
4545 */
4546 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004547ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004548 buf_T *ins_buf, // buffer being scanned
4549 pos_T *cur_match_pos, // current match position
4550 int *match_len,
4551 int *cont_s_ipos) // next ^X<> will set initial_pos
4552{
4553 char_u *ptr;
4554 int len;
4555
4556 *match_len = 0;
4557 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4558 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004559 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004560 if (ctrl_x_mode_line_or_eval())
4561 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004562 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004563 {
4564 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4565 return NULL;
4566 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004567 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004568 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004569 {
4570 char_u *tmp_ptr = ptr;
4571
4572 ptr = skipwhite(tmp_ptr);
4573 len -= (int)(ptr - tmp_ptr);
4574 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004575 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004576 }
4577 else
4578 {
4579 char_u *tmp_ptr = ptr;
4580
John Marriott5e6ea922024-11-23 14:01:57 +01004581 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004582 {
4583 tmp_ptr += compl_length;
4584 // Skip if already inside a word.
4585 if (vim_iswordp(tmp_ptr))
4586 return NULL;
4587 // Find start of next word.
4588 tmp_ptr = find_word_start(tmp_ptr);
4589 }
4590 // Find end of this word.
4591 tmp_ptr = find_word_end(tmp_ptr);
4592 len = (int)(tmp_ptr - ptr);
4593
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004594 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004595 {
4596 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4597 {
4598 // Try next line, if any. the new word will be
4599 // "join" as if the normal command "J" was used.
4600 // IOSIZE is always greater than
4601 // compl_length, so the next STRNCPY always
4602 // works -- Acevedo
4603 STRNCPY(IObuff, ptr, len);
4604 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4605 tmp_ptr = ptr = skipwhite(ptr);
4606 // Find start of next word.
4607 tmp_ptr = find_word_start(tmp_ptr);
4608 // Find end of next word.
4609 tmp_ptr = find_word_end(tmp_ptr);
4610 if (tmp_ptr > ptr)
4611 {
4612 if (*ptr != ')' && IObuff[len - 1] != TAB)
4613 {
4614 if (IObuff[len - 1] != ' ')
4615 IObuff[len++] = ' ';
4616 // IObuf =~ "\k.* ", thus len >= 2
4617 if (p_js
4618 && (IObuff[len - 2] == '.'
4619 || (vim_strchr(p_cpo, CPO_JOINSP)
4620 == NULL
4621 && (IObuff[len - 2] == '?'
4622 || IObuff[len - 2] == '!'))))
4623 IObuff[len++] = ' ';
4624 }
4625 // copy as much as possible of the new word
4626 if (tmp_ptr - ptr >= IOSIZE - len)
4627 tmp_ptr = ptr + IOSIZE - len - 1;
4628 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4629 len += (int)(tmp_ptr - ptr);
4630 *cont_s_ipos = TRUE;
4631 }
4632 IObuff[len] = NUL;
4633 ptr = IObuff;
4634 }
4635 if (len == compl_length)
4636 return NULL;
4637 }
4638 }
4639
4640 *match_len = len;
4641 return ptr;
4642}
4643
4644/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004645 * Get the next set of words matching "compl_pattern" for default completion(s)
4646 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004647 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4648 * position "st->start_pos" in the "compl_direction" direction. If
4649 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4650 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004651 * Returns OK if a new next match is found, otherwise returns FAIL.
4652 */
4653 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004654get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004655{
4656 int found_new_match = FAIL;
4657 int save_p_scs;
4658 int save_p_ws;
4659 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004660 char_u *ptr = NULL;
4661 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004662 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004663 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004664 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004665 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004666
4667 // If 'infercase' is set, don't use 'smartcase' here
4668 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004669 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004670 p_scs = FALSE;
4671
4672 // Buffers other than curbuf are scanned from the beginning or the
4673 // end but never from the middle, thus setting nowrapscan in this
4674 // buffer is a good idea, on the other hand, we always set
4675 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4676 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004677 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004678 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004679 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004680 p_ws = TRUE;
4681 looped_around = FALSE;
4682 for (;;)
4683 {
4684 int cont_s_ipos = FALSE;
4685
4686 ++msg_silent; // Don't want messages for wrapscan.
4687
glepnirf31cfa22025-03-06 21:59:13 +01004688 if (in_collect)
4689 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004690 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004691 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004692 start_pos, &len, &ptr, &score);
4693 }
4694 // ctrl_x_mode_line_or_eval() || word-wise search that
4695 // has added a word that was at the beginning of the line
4696 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4697 found_new_match = search_for_exact_line(st->ins_buf,
4698 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004699 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004700 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004701 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004702 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004703 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004704 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004705 {
4706 // set "compl_started" even on fail
4707 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004708 st->first_match_pos = *st->cur_match_pos;
4709 st->last_match_pos = *st->cur_match_pos;
4710 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004711 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004712 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4713 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004714 {
4715 found_new_match = FAIL;
4716 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004717 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004718 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4719 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4720 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004721 {
4722 if (looped_around)
4723 found_new_match = FAIL;
4724 else
4725 looped_around = TRUE;
4726 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004727 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004728 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4729 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4730 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004731 {
4732 if (looped_around)
4733 found_new_match = FAIL;
4734 else
4735 looped_around = TRUE;
4736 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004737 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004738 if (found_new_match == FAIL)
4739 break;
4740
4741 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004742 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004743 && start_pos->lnum == st->cur_match_pos->lnum
4744 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004745 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004746
glepnirf31cfa22025-03-06 21:59:13 +01004747 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004748 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4749 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004750 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004751 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004752
Girish Palyab1565882025-04-15 20:16:00 +02004753 if (is_nearest_active() && in_curbuf)
4754 {
4755 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4756 if (score < 0)
4757 score = -score;
4758 score++;
4759 }
4760
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004761 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004762 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004763 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004764 {
glepnirf31cfa22025-03-06 21:59:13 +01004765 if (in_collect && score == compl_first_match->cp_next->cp_score)
4766 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004767 found_new_match = OK;
4768 break;
4769 }
4770 }
4771 p_scs = save_p_scs;
4772 p_ws = save_p_ws;
4773
4774 return found_new_match;
4775}
4776
Girish Palyacbe53192025-04-14 22:13:15 +02004777#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004778/*
4779 * Return the callback function associated with "p" if it points to a
4780 * userfunc.
4781 */
Girish Palyacbe53192025-04-14 22:13:15 +02004782 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004783get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004784{
4785 static callback_T cb;
4786 char_u buf[LSIZE];
4787 int slen;
4788
Girish Palya98c29db2025-06-01 19:40:00 +02004789 if (*p == 'o')
4790 return &curbuf->b_ofu_cb;
4791 if (*p == 'F')
4792 {
4793 if (*++p != ',' && *p != NUL)
4794 {
4795 free_callback(&cb);
4796 slen = copy_option_part(&p, buf, LSIZE, ",");
4797 if (slen > 0 && option_set_callback_func(buf, &cb))
4798 return &cb;
4799 return NULL;
4800 }
4801 else
4802 return &curbuf->b_cfu_cb;
4803 }
Girish Palyacbe53192025-04-14 22:13:15 +02004804 return NULL;
4805}
4806
4807/*
4808 * Retrieve new completion matches by invoking callback "cb".
4809 */
4810 static void
4811expand_cpt_function(callback_T *cb)
4812{
4813 // Re-insert the text removed by ins_compl_delete().
4814 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4815 // Get matches
4816 get_cpt_func_completion_matches(cb);
4817 // Undo insertion
4818 ins_compl_delete();
4819}
4820#endif
4821
4822/*
glepnir05460682025-05-26 18:23:27 +02004823 * Get completion matches from register contents.
4824 * Extracts words from all available registers and adds them to the completion list.
4825 */
4826 static void
4827get_register_completion(void)
4828{
4829 int dir = compl_direction;
4830 yankreg_T *reg = NULL;
4831 void *reg_ptr = NULL;
glepnir86d46a72025-06-03 21:04:44 +02004832 int adding_mode = compl_status_adding();
glepnir05460682025-05-26 18:23:27 +02004833
4834 for (int i = 0; i < NUM_REGISTERS; i++)
4835 {
4836 int regname = 0;
glepnir05460682025-05-26 18:23:27 +02004837 if (i == 0)
4838 regname = '"'; // unnamed register
4839 else if (i < 10)
4840 regname = '0' + i;
4841 else if (i == DELETION_REGISTER)
4842 regname = '-';
4843#ifdef FEAT_CLIPBOARD
4844 else if (i == STAR_REGISTER)
4845 regname = '*';
4846 else if (i == PLUS_REGISTER)
4847 regname = '+';
4848#endif
4849 else
4850 regname = 'a' + i - 10;
4851
4852 // Skip invalid or black hole register
4853 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4854 continue;
4855
4856 reg_ptr = get_register(regname, FALSE);
4857 if (reg_ptr == NULL)
4858 continue;
4859
4860 reg = (yankreg_T *)reg_ptr;
4861
glepnir86d46a72025-06-03 21:04:44 +02004862 for (int j = 0; j < reg->y_size; j++)
glepnir05460682025-05-26 18:23:27 +02004863 {
glepnir86d46a72025-06-03 21:04:44 +02004864 char_u *str = reg->y_array[j].string;
4865 if (str == NULL)
4866 continue;
glepnir05460682025-05-26 18:23:27 +02004867
glepnir86d46a72025-06-03 21:04:44 +02004868 if (adding_mode)
4869 {
glepnird5fdfa52025-06-02 19:45:41 +02004870 int str_len = (int)STRLEN(str);
4871 if (str_len == 0)
4872 continue;
glepnir05460682025-05-26 18:23:27 +02004873
glepnird5fdfa52025-06-02 19:45:41 +02004874 if (!compl_orig_text.string
4875 || (p_ic ? STRNICMP(str, compl_orig_text.string,
4876 compl_orig_text.length) == 0
4877 : STRNCMP(str, compl_orig_text.string,
4878 compl_orig_text.length) == 0))
glepnir05460682025-05-26 18:23:27 +02004879 {
glepnir86d46a72025-06-03 21:04:44 +02004880 if (ins_compl_add_infercase(str, str_len, p_ic, NULL,
4881 dir, FALSE, 0) == OK)
glepnir05460682025-05-26 18:23:27 +02004882 dir = FORWARD;
4883 }
glepnird5fdfa52025-06-02 19:45:41 +02004884 }
glepnir86d46a72025-06-03 21:04:44 +02004885 else
glepnird5fdfa52025-06-02 19:45:41 +02004886 {
glepnird5fdfa52025-06-02 19:45:41 +02004887 // Calculate the safe end of string to avoid null byte issues
4888 char_u *str_end = str + STRLEN(str);
4889 char_u *p = str;
4890
4891 // Safely iterate through the string
4892 while (p < str_end && *p != NUL)
4893 {
4894 char_u *old_p = p;
4895 p = find_word_start(p);
4896 if (p >= str_end || *p == NUL)
4897 break;
4898
4899 char_u *word_end = find_word_end(p);
4900
4901 if (word_end <= p)
4902 {
4903 if (has_mbyte)
4904 word_end = p + (*mb_ptr2len)(p);
4905 else
4906 word_end = p + 1;
4907 }
4908
4909 if (word_end > str_end)
4910 word_end = str_end;
4911
4912 int len = (int)(word_end - p);
4913 if (len > 0 && (!compl_orig_text.string
4914 || (p_ic ? STRNICMP(p, compl_orig_text.string,
4915 compl_orig_text.length) == 0
4916 : STRNCMP(p, compl_orig_text.string,
4917 compl_orig_text.length) == 0)))
4918 {
4919 if (ins_compl_add_infercase(p, len, p_ic, NULL,
4920 dir, FALSE, 0) == OK)
4921 dir = FORWARD;
4922 }
4923
4924 p = word_end;
4925
4926 if (p <= old_p)
4927 {
4928 p = old_p + 1;
4929 if (has_mbyte && p < str_end)
4930 p = old_p + (*mb_ptr2len)(old_p);
4931 }
4932 }
glepnir05460682025-05-26 18:23:27 +02004933 }
4934 }
4935
4936 // Free the register copy
4937 put_register(regname, reg_ptr);
4938 }
4939}
4940
4941/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004942 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004943 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004944 */
4945 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004946get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004947{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004948 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004949
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004950 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004951 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004952 case -1:
4953 break;
4954#ifdef FEAT_FIND_ID
4955 case CTRL_X_PATH_PATTERNS:
4956 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004957 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004958 break;
4959#endif
4960
4961 case CTRL_X_DICTIONARY:
4962 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004963 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4964 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004965 break;
4966
4967 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004968 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004969 break;
4970
4971 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004972 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004973 break;
4974
4975 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004976 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004977 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004978 break;
4979
4980#ifdef FEAT_COMPL_FUNC
4981 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004982 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4983 expand_cpt_function(st->func_cb);
4984 else
4985 expand_by_function(type, compl_pattern.string, NULL);
4986 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004988 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004989 break;
4990#endif
4991
4992 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004993 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004994 break;
4995
glepnir05460682025-05-26 18:23:27 +02004996 case CTRL_X_REGISTER:
4997 get_register_completion();
4998 break;
4999
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005000 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005001 found_new_match = get_next_default_completion(st, ini);
5002 if (found_new_match == FAIL && st->ins_buf == curbuf)
5003 st->found_all = TRUE;
5004 }
5005
5006 // check if compl_curr_match has changed, (e.g. other type of
5007 // expansion added something)
5008 if (type != 0 && compl_curr_match != compl_old_match)
5009 found_new_match = OK;
5010
5011 return found_new_match;
5012}
5013
5014/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005015 * Strips carets followed by numbers. This suffix typically represents the
5016 * max_matches setting.
5017 */
5018 static void
5019strip_caret_numbers_in_place(char_u *str)
5020{
5021 char_u *read = str, *write = str, *p;
5022
5023 if (str == NULL)
5024 return;
5025
5026 while (*read)
5027 {
5028 if (*read == '^')
5029 {
5030 p = read + 1;
5031 while (vim_isdigit(*p))
5032 p++;
5033 if ((*p == ',' || *p == '\0') && p != read + 1)
5034 {
5035 read = p;
5036 continue;
5037 }
5038 else
5039 *write++ = *read++;
5040 }
5041 else
5042 *write++ = *read++;
5043 }
5044 *write = '\0';
5045}
5046
5047/*
Girish Palya98c29db2025-06-01 19:40:00 +02005048 * Call functions specified in the 'cpt' option with findstart=1,
5049 * and retrieve the startcol.
5050 */
5051 static void
5052prepare_cpt_compl_funcs(void)
5053{
5054#ifdef FEAT_COMPL_FUNC
5055 char_u *cpt;
5056 char_u *p;
5057 callback_T *cb = NULL;
5058 int idx = 0;
5059 int startcol;
5060
5061 // Make a copy of 'cpt' in case the buffer gets wiped out
5062 cpt = vim_strsave(curbuf->b_p_cpt);
5063 strip_caret_numbers_in_place(cpt);
5064
5065 // Re-insert the text removed by ins_compl_delete().
5066 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5067
5068 for (p = cpt; *p;)
5069 {
5070 while (*p == ',' || *p == ' ') // Skip delimiters
5071 p++;
5072 cb = get_callback_if_cpt_func(p);
5073 if (cb)
5074 {
5075 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5076 == FAIL)
5077 {
5078 if (startcol == -3)
5079 cpt_sources_array[idx].cs_refresh_always = FALSE;
5080 else
5081 startcol = -2;
5082 }
5083 cpt_sources_array[idx].cs_startcol = startcol;
5084 }
5085 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5086 idx++;
5087 }
5088
5089 // Undo insertion
5090 ins_compl_delete();
5091
5092 vim_free(cpt);
5093#endif
5094}
5095
5096/*
Girish Palya7c621052025-05-26 19:41:59 +02005097 * Safely advance the cpt_sources_index by one.
5098 */
5099 static int
5100advance_cpt_sources_index_safe(void)
5101{
5102 if (cpt_sources_index < cpt_sources_count - 1)
5103 {
5104 cpt_sources_index++;
5105 return OK;
5106 }
5107#ifdef FEAT_EVAL
5108 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5109#endif
5110 return FAIL;
5111}
5112
5113/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005114 * Get the next expansion(s), using "compl_pattern".
5115 * The search starts at position "ini" in curbuf and in the direction
5116 * compl_direction.
5117 * When "compl_started" is FALSE start at that position, otherwise continue
5118 * where we stopped searching before.
5119 * This may return before finding all the matches.
5120 * Return the total number of matches or -1 if still unknown -- Acevedo
5121 */
5122 static int
5123ins_compl_get_exp(pos_T *ini)
5124{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005125 static ins_compl_next_state_T st;
5126 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005127 int i;
5128 int found_new_match;
5129 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005130 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005131
5132 if (!compl_started)
5133 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005134 buf_T *buf;
5135
5136 FOR_ALL_BUFFERS(buf)
5137 buf->b_scanned = 0;
5138 if (!st_cleared)
5139 {
5140 CLEAR_FIELD(st);
5141 st_cleared = TRUE;
5142 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005143 st.found_all = FALSE;
5144 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005145 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005146 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005147 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5148 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005149 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005150 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005151 st.last_match_pos = st.first_match_pos = *ini;
5152 }
5153 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5154 st.ins_buf = curbuf; // In case the buffer was wiped out.
5155
5156 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005157 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005158 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005159
Girish Palya98c29db2025-06-01 19:40:00 +02005160 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5161 !(compl_cont_status & CONT_LOCAL))
5162 {
5163 // ^N completion, not ^X^L or complete() or ^X^N
5164 if (!compl_started) // Before showing menu the first time
5165 {
5166 if (setup_cpt_sources() == FAIL)
5167 return FAIL;
5168 }
5169 prepare_cpt_compl_funcs();
5170 cpt_sources_index = 0;
5171 }
5172
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005173 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005174 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005175 {
5176 found_new_match = FAIL;
5177 st.set_match_pos = FALSE;
5178
5179 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5180 // or if found_all says this entry is done. For ^X^L only use the
5181 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005182 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005183 && (!compl_started || st.found_all))
5184 {
Girish Palya7c621052025-05-26 19:41:59 +02005185 int status = process_next_cpt_value(&st, &type, ini,
5186 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005187
5188 if (status == INS_COMPL_CPT_END)
5189 break;
5190 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005191 {
Girish Palya7c621052025-05-26 19:41:59 +02005192 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5193 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005194 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005195 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005196 }
5197
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005198 // If complete() was called then compl_pattern has been reset. The
5199 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005200 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005201 break;
5202
5203 // get the next set of completion matches
5204 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005205
Girish Palya7c621052025-05-26 19:41:59 +02005206 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5207 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005208
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005209 // break the loop for specialized modes (use 'complete' just for the
5210 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5211 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005212 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5213 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005214 {
5215 if (got_int)
5216 break;
5217 // Fill the popup menu as soon as possible.
5218 if (type != -1)
5219 ins_compl_check_keys(0, FALSE);
5220
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005221 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005222 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5223 break;
5224 compl_started = TRUE;
5225 }
5226 else
5227 {
5228 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005229 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005230 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005231
5232 compl_started = FALSE;
5233 }
5234 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005235 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005236 compl_started = TRUE;
5237
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005238 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005239 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005240 found_new_match = FAIL;
5241
5242 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005243 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005244 && !ctrl_x_mode_line_or_eval()))
5245 i = ins_compl_make_cyclic();
5246
glepnirf31cfa22025-03-06 21:59:13 +01005247 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5248 fuzzy_longest_match();
5249
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005250 if (compl_old_match != NULL)
5251 {
5252 // If several matches were added (FORWARD) or the search failed and has
5253 // just been made cyclic then we have to move compl_curr_match to the
5254 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005255 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005256 : compl_old_match->cp_prev;
5257 if (compl_curr_match == NULL)
5258 compl_curr_match = compl_old_match;
5259 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005260 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005261
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005262 if (is_nearest_active())
5263 sort_compl_match_list(cp_compare_nearest);
5264
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005265 return i;
5266}
5267
5268/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005269 * Update "compl_shown_match" to the actually shown match, it may differ when
5270 * "compl_leader" is used to omit some of the matches.
5271 */
5272 static void
5273ins_compl_update_shown_match(void)
5274{
5275 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005276 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005277 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005278 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005279 compl_shown_match = compl_shown_match->cp_next;
5280
5281 // If we didn't find it searching forward, and compl_shows_dir is
5282 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005283 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005284 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005285 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005286 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005287 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005288 {
5289 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005290 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005291 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005292 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005293 compl_shown_match = compl_shown_match->cp_prev;
5294 }
5295}
5296
5297/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005298 * Delete the old text being completed.
5299 */
5300 void
5301ins_compl_delete(void)
5302{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005303 // In insert mode: Delete the typed part.
5304 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005305 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005306 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005307 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005308 int has_preinsert = ins_compl_preinsert_effect();
5309 if (has_preinsert)
5310 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005311 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005312 curwin->w_cursor.col = compl_ins_end_col;
5313 }
5314
glepnir76bdb822025-02-08 19:04:51 +01005315 if (curwin->w_cursor.lnum > compl_lnum)
5316 {
5317 if (curwin->w_cursor.col < ml_get_curline_len())
5318 {
John Marriottf4b36412025-02-23 09:09:59 +01005319 char_u *line = ml_get_cursor();
5320 remaining.length = ml_get_cursor_len();
5321 remaining.string = vim_strnsave(line, remaining.length);
5322 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005323 return;
5324 }
5325 while (curwin->w_cursor.lnum > compl_lnum)
5326 {
5327 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5328 {
John Marriottf4b36412025-02-23 09:09:59 +01005329 if (remaining.string)
5330 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005331 return;
5332 }
zeertzjq060e6552025-02-21 20:06:26 +01005333 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005334 curwin->w_cursor.lnum--;
5335 }
5336 // move cursor to end of line
5337 curwin->w_cursor.col = ml_get_curline_len();
5338 }
5339
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005340 if ((int)curwin->w_cursor.col > col)
5341 {
5342 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005343 {
John Marriottf4b36412025-02-23 09:09:59 +01005344 if (remaining.string)
5345 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005346 return;
glepnire3647c82025-02-10 21:16:32 +01005347 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005348 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005349 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005350 }
5351
John Marriottf4b36412025-02-23 09:09:59 +01005352 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005353 {
5354 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005355 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005356 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005357 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005358 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005359 // TODO: is this sufficient for redrawing? Redrawing everything causes
5360 // flicker, thus we can't do that.
5361 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005362#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005363 // clear v:completed_item
5364 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005365#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005366}
5367
5368/*
glepnir76bdb822025-02-08 19:04:51 +01005369 * Insert a completion string that contains newlines.
5370 * The string is split and inserted line by line.
5371 */
5372 static void
5373ins_compl_expand_multiple(char_u *str)
5374{
5375 char_u *start = str;
5376 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005377 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005378
5379 while (*curr != NUL)
5380 {
5381 if (*curr == '\n')
5382 {
5383 // Insert the text chunk before newline
5384 if (curr > start)
5385 ins_char_bytes(start, (int)(curr - start));
5386
5387 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005388 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005389 start = curr + 1;
5390 }
5391 curr++;
5392 }
5393
5394 // Handle remaining text after last newline (if any)
5395 if (curr > start)
5396 ins_char_bytes(start, (int)(curr - start));
5397
5398 compl_ins_end_col = curwin->w_cursor.col;
5399}
5400
5401/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005402 * Insert the new text being completed.
5403 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005404 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5405 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005406 */
5407 void
glepniredd4ac32025-01-29 18:53:51 +01005408ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005409{
glepnir76bdb822025-02-08 19:04:51 +01005410 int compl_len = get_compl_len();
5411 int preinsert = ins_compl_has_preinsert();
5412 char_u *cp_str = compl_shown_match->cp_str.string;
5413 size_t cp_str_len = compl_shown_match->cp_str.length;
5414 size_t leader_len = ins_compl_leader_len();
5415 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005416
5417 // Make sure we don't go over the end of the string, this can happen with
5418 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005419 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005420 {
glepnir76bdb822025-02-08 19:04:51 +01005421 if (has_multiple)
5422 ins_compl_expand_multiple(cp_str + compl_len);
5423 else
5424 {
5425 ins_compl_insert_bytes(cp_str + compl_len, -1);
5426 if (preinsert && move_cursor)
5427 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5428 }
glepniredd4ac32025-01-29 18:53:51 +01005429 }
5430 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005431 compl_used_match = FALSE;
5432 else
5433 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005434#ifdef FEAT_EVAL
5435 {
5436 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5437
5438 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5439 }
5440#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005441 if (!in_compl_func)
5442 compl_curr_match = compl_shown_match;
5443}
5444
5445/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005446 * show the file name for the completion match (if any). Truncate the file
5447 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005448 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005449 static void
5450ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005451{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005452 char *lead = _("match in file");
5453 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5454 char_u *s;
5455 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005456
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005457 if (space <= 0)
5458 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005459
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005460 // We need the tail that fits. With double-byte encoding going
5461 // back from the end is very slow, thus go from the start and keep
5462 // the text that fits in "space" between "s" and "e".
5463 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005464 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005465 space -= ptr2cells(e);
5466 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005467 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005468 space += ptr2cells(s);
5469 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005470 }
5471 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005472 msg_hist_off = TRUE;
5473 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5474 s > compl_shown_match->cp_fname ? "<" : "", s);
5475 msg((char *)IObuff);
5476 msg_hist_off = FALSE;
5477 redraw_cmdline = FALSE; // don't overwrite!
5478}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005479
glepnirdca57fb2024-06-04 22:01:21 +02005480/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005481 * Find the appropriate completion item when 'complete' ('cpt') includes
5482 * a 'max_matches' postfix. In this case, we search for a match where
5483 * 'cp_in_match_array' is set, indicating that the match is also present
5484 * in 'compl_match_array'.
5485 */
5486 static compl_T *
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005487find_next_match_in_menu(void)
Girish Palya0ac1eb32025-04-16 20:18:33 +02005488{
5489 int is_forward = compl_shows_dir_forward();
5490 compl_T *match = compl_shown_match;
5491
5492 do
5493 match = is_forward ? match->cp_next : match->cp_prev;
5494 while (match->cp_next && !match->cp_in_match_array
5495 && !match_at_original_text(match));
5496 return match;
5497}
5498
5499/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005500 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005501 * times. The number of matches found is returned in 'num_matches'.
5502 *
5503 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5504 * get more completions. If it is FALSE, then do nothing when there are no more
5505 * completions in the given direction.
5506 *
5507 * If "advance" is TRUE, then completion will move to the first match.
5508 * Otherwise, the original text will be shown.
5509 *
5510 * Returns OK on success and -1 if the number of matches are unknown.
5511 */
5512 static int
5513find_next_completion_match(
5514 int allow_get_expansion,
5515 int todo, // repeat completion this many times
5516 int advance,
5517 int *num_matches)
5518{
5519 int found_end = FALSE;
5520 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005521 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005522 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5523 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005524
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005525 while (--todo >= 0)
5526 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005527 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005528 {
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005529 if (compl_match_array != NULL)
5530 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005531 else
5532 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005533 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005534 && (is_first_match(compl_shown_match->cp_next)
5535 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005536 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005537 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005538 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005539 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005540 found_end = is_first_match(compl_shown_match);
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005541 if (compl_match_array != NULL)
5542 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005543 else
5544 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005545 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005546 }
5547 else
5548 {
5549 if (!allow_get_expansion)
5550 {
5551 if (advance)
5552 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005553 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005554 compl_pending -= todo + 1;
5555 else
5556 compl_pending += todo + 1;
5557 }
5558 return -1;
5559 }
5560
5561 if (!compl_no_select && advance)
5562 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005563 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005564 --compl_pending;
5565 else
5566 ++compl_pending;
5567 }
5568
5569 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005570 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005571
5572 // handle any pending completions
5573 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005574 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005575 {
5576 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5577 {
5578 compl_shown_match = compl_shown_match->cp_next;
5579 --compl_pending;
5580 }
5581 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5582 {
5583 compl_shown_match = compl_shown_match->cp_prev;
5584 ++compl_pending;
5585 }
5586 else
5587 break;
5588 }
5589 found_end = FALSE;
5590 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005591 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005592 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005593 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005594 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005595 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005596 ++todo;
5597 else
5598 // Remember a matching item.
5599 found_compl = compl_shown_match;
5600
5601 // Stop at the end of the list when we found a usable match.
5602 if (found_end)
5603 {
5604 if (found_compl != NULL)
5605 {
5606 compl_shown_match = found_compl;
5607 break;
5608 }
5609 todo = 1; // use first usable match after wrapping around
5610 }
5611 }
5612
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005613 return OK;
5614}
5615
5616/*
5617 * Fill in the next completion in the current direction.
5618 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5619 * get more completions. If it is FALSE, then we just do nothing when there
5620 * are no more completions in a given direction. The latter case is used when
5621 * we are still in the middle of finding completions, to allow browsing
5622 * through the ones found so far.
5623 * Return the total number of matches, or -1 if still unknown -- webb.
5624 *
5625 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5626 * compl_shown_match here.
5627 *
5628 * Note that this function may be called recursively once only. First with
5629 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5630 * calls this function with "allow_get_expansion" FALSE.
5631 */
5632 static int
5633ins_compl_next(
5634 int allow_get_expansion,
5635 int count, // repeat completion this many times; should
5636 // be at least 1
5637 int insert_match, // Insert the newly selected match
5638 int in_compl_func) // called from complete_check()
5639{
5640 int num_matches = -1;
5641 int todo = count;
5642 int advance;
5643 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005644 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005645 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005646 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5647 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005648 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005649
5650 // When user complete function return -1 for findstart which is next
5651 // time of 'always', compl_shown_match become NULL.
5652 if (compl_shown_match == NULL)
5653 return -1;
5654
John Marriott5e6ea922024-11-23 14:01:57 +01005655 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005656 && !match_at_original_text(compl_shown_match)
5657 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005658 // Update "compl_shown_match" to the actually shown match
5659 ins_compl_update_shown_match();
5660
5661 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005662 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005663 // Delete old text to be replaced
5664 ins_compl_delete();
5665
5666 // When finding the longest common text we stick at the original text,
5667 // don't let CTRL-N or CTRL-P move to the first match.
5668 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5669
5670 // When restarting the search don't insert the first match either.
5671 if (compl_restarting)
5672 {
5673 advance = FALSE;
5674 compl_restarting = FALSE;
5675 }
5676
5677 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5678 // around.
5679 if (find_next_completion_match(allow_get_expansion, todo, advance,
5680 &num_matches) == -1)
5681 return -1;
5682
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005683 if (curbuf != orig_curbuf)
5684 {
5685 // In case some completion function switched buffer, don't want to
5686 // insert the completion elsewhere.
5687 return -1;
5688 }
5689
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005690 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005691 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005692 {
glepnir6a38aff2024-12-16 21:56:16 +01005693 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005694 compl_used_match = FALSE;
5695 }
5696 else if (insert_match)
5697 {
5698 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005699 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005700 else
glepnir6a38aff2024-12-16 21:56:16 +01005701 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005702 }
5703 else
5704 compl_used_match = FALSE;
5705
5706 if (!allow_get_expansion)
5707 {
5708 // may undisplay the popup menu first
5709 ins_compl_upd_pum();
5710
5711 if (pum_enough_matches())
5712 // Will display the popup menu, don't redraw yet to avoid flicker.
5713 pum_call_update_screen();
5714 else
5715 // Not showing the popup menu yet, redraw to show the user what was
5716 // inserted.
5717 update_screen(0);
5718
5719 // display the updated popup menu
5720 ins_compl_show_pum();
5721#ifdef FEAT_GUI
5722 if (gui.in_use)
5723 {
5724 // Show the cursor after the match, not after the redrawn text.
5725 setcursor();
5726 out_flush_cursor(FALSE, FALSE);
5727 }
5728#endif
5729
5730 // Delete old text to be replaced, since we're still searching and
5731 // don't want to match ourselves!
5732 ins_compl_delete();
5733 }
5734
5735 // Enter will select a match when the match wasn't inserted and the popup
5736 // menu is visible.
5737 if (compl_no_insert && !started)
5738 compl_enter_selects = TRUE;
5739 else
5740 compl_enter_selects = !insert_match && compl_match_array != NULL;
5741
5742 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005743 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005744 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005745
5746 return num_matches;
5747}
5748
5749/*
5750 * Call this while finding completions, to check whether the user has hit a key
5751 * that should change the currently displayed completion, or exit completion
5752 * mode. Also, when compl_pending is not zero, show a completion as soon as
5753 * possible. -- webb
5754 * "frequency" specifies out of how many calls we actually check.
5755 * "in_compl_func" is TRUE when called from complete_check(), don't set
5756 * compl_curr_match.
5757 */
5758 void
5759ins_compl_check_keys(int frequency, int in_compl_func)
5760{
5761 static int count = 0;
5762 int c;
5763
5764 // Don't check when reading keys from a script, :normal or feedkeys().
5765 // That would break the test scripts. But do check for keys when called
5766 // from complete_check().
5767 if (!in_compl_func && (using_script() || ex_normal_busy))
5768 return;
5769
5770 // Only do this at regular intervals
5771 if (++count < frequency)
5772 return;
5773 count = 0;
5774
5775 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5776 // can't do its work correctly.
5777 c = vpeekc_any();
5778 if (c != NUL)
5779 {
5780 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5781 {
5782 c = safe_vgetc(); // Eat the character
5783 compl_shows_dir = ins_compl_key2dir(c);
5784 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5785 c != K_UP && c != K_DOWN, in_compl_func);
5786 }
5787 else
5788 {
5789 // Need to get the character to have KeyTyped set. We'll put it
5790 // back with vungetc() below. But skip K_IGNORE.
5791 c = safe_vgetc();
5792 if (c != K_IGNORE)
5793 {
5794 // Don't interrupt completion when the character wasn't typed,
5795 // e.g., when doing @q to replay keys.
5796 if (c != Ctrl_R && KeyTyped)
5797 compl_interrupted = TRUE;
5798
5799 vungetc(c);
5800 }
5801 }
5802 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005803 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005804 {
5805 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5806
5807 compl_pending = 0;
5808 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5809 }
5810}
5811
5812/*
5813 * Decide the direction of Insert mode complete from the key typed.
5814 * Returns BACKWARD or FORWARD.
5815 */
5816 static int
5817ins_compl_key2dir(int c)
5818{
5819 if (c == Ctrl_P || c == Ctrl_L
5820 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5821 return BACKWARD;
5822 return FORWARD;
5823}
5824
5825/*
5826 * Return TRUE for keys that are used for completion only when the popup menu
5827 * is visible.
5828 */
5829 static int
5830ins_compl_pum_key(int c)
5831{
5832 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5833 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5834 || c == K_UP || c == K_DOWN);
5835}
5836
5837/*
5838 * Decide the number of completions to move forward.
5839 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5840 */
5841 static int
5842ins_compl_key2count(int c)
5843{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005844 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5845 {
glepnir19e1dd62025-05-08 22:50:38 +02005846 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005847 if (h > 3)
5848 h -= 2; // keep some context
5849 return h;
5850 }
5851 return 1;
5852}
5853
5854/*
5855 * Return TRUE if completion with "c" should insert the match, FALSE if only
5856 * to change the currently selected completion.
5857 */
5858 static int
5859ins_compl_use_match(int c)
5860{
5861 switch (c)
5862 {
5863 case K_UP:
5864 case K_DOWN:
5865 case K_PAGEDOWN:
5866 case K_KPAGEDOWN:
5867 case K_S_DOWN:
5868 case K_PAGEUP:
5869 case K_KPAGEUP:
5870 case K_S_UP:
5871 return FALSE;
5872 }
5873 return TRUE;
5874}
5875
5876/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005877 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5878 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005879 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005880 * Uses the global variables: compl_cont_status and ctrl_x_mode
5881 */
5882 static int
5883get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5884{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005885 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005886 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005887 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005888 {
5889 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5890 ;
5891 compl_col += ++startcol;
5892 compl_length = curs_col - startcol;
5893 }
5894 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005895 {
John Marriott5e6ea922024-11-23 14:01:57 +01005896 compl_pattern.string = str_foldcase(line + compl_col,
5897 compl_length, NULL, 0);
5898 if (compl_pattern.string == NULL)
5899 {
5900 compl_pattern.length = 0;
5901 return FAIL;
5902 }
5903 compl_pattern.length = STRLEN(compl_pattern.string);
5904 }
5905 else
5906 {
5907 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5908 if (compl_pattern.string == NULL)
5909 {
5910 compl_pattern.length = 0;
5911 return FAIL;
5912 }
5913 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005914 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005915 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005916 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005917 {
5918 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005919 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005920 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005921
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005922 if (!vim_iswordp(line + compl_col)
5923 || (compl_col > 0
5924 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005925 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005926 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005927 prefixlen = 0;
5928 }
John Marriott5e6ea922024-11-23 14:01:57 +01005929
5930 // we need up to 2 extra chars for the prefix
5931 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5932 compl_pattern.string = alloc(n);
5933 if (compl_pattern.string == NULL)
5934 {
5935 compl_pattern.length = 0;
5936 return FAIL;
5937 }
5938 STRCPY((char *)compl_pattern.string, prefix);
5939 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005940 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005941 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005942 }
5943 else if (--startcol < 0
5944 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5945 {
John Marriott5e6ea922024-11-23 14:01:57 +01005946 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5947
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005948 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005949 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5950 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005951 {
John Marriott5e6ea922024-11-23 14:01:57 +01005952 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005953 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005954 }
John Marriott5e6ea922024-11-23 14:01:57 +01005955 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005956 compl_col += curs_col;
5957 compl_length = 0;
5958 }
5959 else
5960 {
5961 // Search the point of change class of multibyte character
5962 // or not a word single byte character backward.
5963 if (has_mbyte)
5964 {
5965 int base_class;
5966 int head_off;
5967
5968 startcol -= (*mb_head_off)(line, line + startcol);
5969 base_class = mb_get_class(line + startcol);
5970 while (--startcol >= 0)
5971 {
5972 head_off = (*mb_head_off)(line, line + startcol);
5973 if (base_class != mb_get_class(line + startcol
5974 - head_off))
5975 break;
5976 startcol -= head_off;
5977 }
5978 }
5979 else
glepnir19e1dd62025-05-08 22:50:38 +02005980 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005981 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5982 ;
glepnir19e1dd62025-05-08 22:50:38 +02005983 }
5984
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005985 compl_col += ++startcol;
5986 compl_length = (int)curs_col - startcol;
5987 if (compl_length == 1)
5988 {
5989 // Only match word with at least two chars -- webb
5990 // there's no need to call quote_meta,
5991 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005992 compl_pattern.string = alloc(7);
5993 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005994 {
John Marriott5e6ea922024-11-23 14:01:57 +01005995 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005996 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005997 }
John Marriott5e6ea922024-11-23 14:01:57 +01005998 STRCPY((char *)compl_pattern.string, "\\<");
5999 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
6000 STRCAT((char *)compl_pattern.string, "\\k");
6001 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006002 }
6003 else
6004 {
John Marriott5e6ea922024-11-23 14:01:57 +01006005 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6006
6007 compl_pattern.string = alloc(n);
6008 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006009 {
John Marriott5e6ea922024-11-23 14:01:57 +01006010 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006011 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006012 }
John Marriott5e6ea922024-11-23 14:01:57 +01006013 STRCPY((char *)compl_pattern.string, "\\<");
6014 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006015 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006016 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006017 }
6018 }
6019
6020 return OK;
6021}
6022
6023/*
6024 * Get the pattern, column and length for whole line completion or for the
6025 * complete() function.
6026 * Sets the global variables: compl_col, compl_length and compl_pattern.
6027 */
6028 static int
6029get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6030{
6031 compl_col = (colnr_T)getwhitecols(line);
6032 compl_length = (int)curs_col - (int)compl_col;
6033 if (compl_length < 0) // cursor in indent: empty pattern
6034 compl_length = 0;
6035 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006036 {
John Marriott5e6ea922024-11-23 14:01:57 +01006037 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6038 NULL, 0);
6039 if (compl_pattern.string == NULL)
6040 {
6041 compl_pattern.length = 0;
6042 return FAIL;
6043 }
6044 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006045 }
John Marriott5e6ea922024-11-23 14:01:57 +01006046 else
6047 {
6048 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6049 if (compl_pattern.string == NULL)
6050 {
6051 compl_pattern.length = 0;
6052 return FAIL;
6053 }
6054 compl_pattern.length = (size_t)compl_length;
6055 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006056
6057 return OK;
6058}
6059
6060/*
6061 * Get the pattern, column and length for filename completion.
6062 * Sets the global variables: compl_col, compl_length and compl_pattern.
6063 */
6064 static int
6065get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6066{
6067 // Go back to just before the first filename character.
6068 if (startcol > 0)
6069 {
6070 char_u *p = line + startcol;
6071
6072 MB_PTR_BACK(line, p);
6073 while (p > line && vim_isfilec(PTR2CHAR(p)))
6074 MB_PTR_BACK(line, p);
6075 if (p == line && vim_isfilec(PTR2CHAR(p)))
6076 startcol = 0;
6077 else
6078 startcol = (int)(p - line) + 1;
6079 }
6080
6081 compl_col += startcol;
6082 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006083 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6084 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006085 {
John Marriott5e6ea922024-11-23 14:01:57 +01006086 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006087 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006088 }
6089
John Marriott5e6ea922024-11-23 14:01:57 +01006090 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006091
6092 return OK;
6093}
6094
6095/*
6096 * Get the pattern, column and length for command-line completion.
6097 * Sets the global variables: compl_col, compl_length and compl_pattern.
6098 */
6099 static int
6100get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6101{
John Marriott5e6ea922024-11-23 14:01:57 +01006102 compl_pattern.string = vim_strnsave(line, curs_col);
6103 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006104 {
John Marriott5e6ea922024-11-23 14:01:57 +01006105 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006106 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006107 }
John Marriott5e6ea922024-11-23 14:01:57 +01006108 compl_pattern.length = curs_col;
6109 set_cmd_context(&compl_xp, compl_pattern.string,
6110 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006111 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6112 || compl_xp.xp_context == EXPAND_NOTHING)
6113 // No completion possible, use an empty pattern to get a
6114 // "pattern not found" message.
6115 compl_col = curs_col;
6116 else
John Marriott5e6ea922024-11-23 14:01:57 +01006117 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006118 compl_length = curs_col - compl_col;
6119
6120 return OK;
6121}
6122
Girish Palya98c29db2025-06-01 19:40:00 +02006123#ifdef FEAT_COMPL_FUNC
6124/*
6125 * Set global variables related to completion:
6126 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6127 */
6128 static int
6129set_compl_globals(
6130 int startcol UNUSED,
6131 colnr_T curs_col UNUSED,
6132 int is_cpt_compl UNUSED)
6133{
6134 char_u *line = NULL;
6135 string_T *pattern = NULL;
6136 int len;
6137
6138 if (startcol < 0 || startcol > curs_col)
6139 startcol = curs_col;
6140 len = curs_col - startcol;
6141
6142 // Re-obtain line in case it has changed
6143 line = ml_get(curwin->w_cursor.lnum);
6144
6145 pattern = is_cpt_compl ? &cpt_compl_pattern : &compl_pattern;
6146 pattern->string = vim_strnsave(line + startcol, (size_t)len);
6147 if (pattern->string == NULL)
6148 {
6149 pattern->length = 0;
6150 return FAIL;
6151 }
6152 pattern->length = (size_t)len;
6153 if (!is_cpt_compl)
6154 {
6155 compl_col = startcol;
6156 compl_length = len;
6157 }
6158 return OK;
6159}
6160#endif
6161
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006162/*
6163 * Get the pattern, column and length for user defined completion ('omnifunc',
6164 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006165 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006166 * Callback function "cb" is set if triggered by a function in the 'cpt'
6167 * option; otherwise, it is NULL.
6168 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006169 */
6170 static int
glepnir19e1dd62025-05-08 22:50:38 +02006171get_userdefined_compl_info(
6172 colnr_T curs_col UNUSED,
6173 callback_T *cb UNUSED,
6174 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006175{
6176 int ret = FAIL;
6177
6178#ifdef FEAT_COMPL_FUNC
6179 // Call user defined function 'completefunc' with "a:findstart"
6180 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006181 typval_T args[3];
6182 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006183 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006184 pos_T pos;
6185 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006186 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006187
Girish Palyacbe53192025-04-14 22:13:15 +02006188 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006189 {
Girish Palyacbe53192025-04-14 22:13:15 +02006190 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6191 // length as a string
6192 funcname = get_complete_funcname(ctrl_x_mode);
6193 if (*funcname == NUL)
6194 {
6195 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6196 ? "completefunc" : "omnifunc");
6197 return FAIL;
6198 }
6199 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006200 }
6201
6202 args[0].v_type = VAR_NUMBER;
6203 args[0].vval.v_number = 1;
6204 args[1].v_type = VAR_STRING;
6205 args[1].vval.v_string = (char_u *)"";
6206 args[2].v_type = VAR_UNKNOWN;
6207 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006208 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006209 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006210 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006211
6212 State = save_State;
6213 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006214 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006215 validate_cursor();
6216 if (!EQUAL_POS(curwin->w_cursor, pos))
6217 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006218 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006219 return FAIL;
6220 }
6221
Girish Palyacbe53192025-04-14 22:13:15 +02006222 if (startcol != NULL)
6223 *startcol = col;
6224
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006225 // Return value -2 means the user complete function wants to cancel the
6226 // complete without an error, do the same if the function did not execute
6227 // successfully.
6228 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006229 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006230
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006231 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006232 if (col == -3)
6233 {
Girish Palyacbe53192025-04-14 22:13:15 +02006234 if (is_cpt_function)
6235 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006236 ctrl_x_mode = CTRL_X_NORMAL;
6237 edit_submode = NULL;
6238 if (!shortmess(SHM_COMPLETIONMENU))
6239 msg_clr_cmdline();
6240 return FAIL;
6241 }
6242
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006243 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006244 // completion.
6245 compl_opt_refresh_always = FALSE;
6246 compl_opt_suppress_empty = FALSE;
6247
Girish Palya98c29db2025-06-01 19:40:00 +02006248 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006249#endif
6250
6251 return ret;
6252}
6253
6254/*
6255 * Get the pattern, column and length for spell completion.
6256 * Sets the global variables: compl_col, compl_length and compl_pattern.
6257 * Uses the global variable: spell_bad_len
6258 */
6259 static int
6260get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6261{
6262 int ret = FAIL;
6263#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006264 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006265
6266 if (spell_bad_len > 0)
6267 compl_col = curs_col - spell_bad_len;
6268 else
6269 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006270
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006271 if (compl_col >= (colnr_T)startcol)
6272 {
6273 compl_length = 0;
6274 compl_col = curs_col;
6275 }
6276 else
6277 {
6278 spell_expand_check_cap(compl_col);
6279 compl_length = (int)curs_col - compl_col;
6280 }
6281 // Need to obtain "line" again, it may have become invalid.
6282 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006283 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6284 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006285 {
John Marriott5e6ea922024-11-23 14:01:57 +01006286 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006287 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006288 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006289
John Marriott5e6ea922024-11-23 14:01:57 +01006290 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006291 ret = OK;
6292#endif
6293
6294 return ret;
6295}
6296
6297/*
6298 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006299 * "startcol" - start column number of the completion pattern/text
6300 * "cur_col" - current cursor column
6301 * On return, "line_invalid" is set to TRUE, if the current line may have
6302 * become invalid and needs to be fetched again.
6303 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006304 */
6305 static int
6306compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6307{
glepnird5fdfa52025-06-02 19:45:41 +02006308 if (ctrl_x_mode_normal() || ctrl_x_mode_register()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006309 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6310 && !thesaurus_func_complete(ctrl_x_mode)))
6311 {
6312 return get_normal_compl_info(line, startcol, curs_col);
6313 }
6314 else if (ctrl_x_mode_line_or_eval())
6315 {
6316 return get_wholeline_compl_info(line, curs_col);
6317 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006318 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006319 {
6320 return get_filename_compl_info(line, startcol, curs_col);
6321 }
6322 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6323 {
6324 return get_cmdline_compl_info(line, curs_col);
6325 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006326 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006327 || thesaurus_func_complete(ctrl_x_mode))
6328 {
Girish Palyacbe53192025-04-14 22:13:15 +02006329 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006330 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006331 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006332 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006333 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006334 {
6335 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6336 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006337 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006338 }
6339 else
6340 {
6341 internal_error("ins_complete()");
6342 return FAIL;
6343 }
6344
6345 return OK;
6346}
6347
6348/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006349 * Continue an interrupted completion mode search in "line".
6350 *
6351 * If this same ctrl_x_mode has been interrupted use the text from
6352 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6353 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6354 * the same line as the cursor then fix it (the line has been split because it
6355 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6356 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006357 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006358 static void
6359ins_compl_continue_search(char_u *line)
6360{
6361 // it is a continued search
6362 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006363 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6364 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006365 {
6366 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6367 {
6368 // line (probably) wrapped, set compl_startpos to the
6369 // first non_blank in the line, if it is not a wordchar
6370 // include it to get a better pattern, but then we don't
6371 // want the "\\<" prefix, check it below
6372 compl_col = (colnr_T)getwhitecols(line);
6373 compl_startpos.col = compl_col;
6374 compl_startpos.lnum = curwin->w_cursor.lnum;
6375 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6376 }
6377 else
6378 {
6379 // S_IPOS was set when we inserted a word that was at the
6380 // beginning of the line, which means that we'll go to SOL
6381 // mode but first we need to redefine compl_startpos
6382 if (compl_cont_status & CONT_S_IPOS)
6383 {
6384 compl_cont_status |= CONT_SOL;
6385 compl_startpos.col = (colnr_T)(skipwhite(
6386 line + compl_length
6387 + compl_startpos.col) - line);
6388 }
6389 compl_col = compl_startpos.col;
6390 }
6391 compl_length = curwin->w_cursor.col - (int)compl_col;
6392 // IObuff is used to add a "word from the next line" would we
6393 // have enough space? just being paranoid
6394#define MIN_SPACE 75
6395 if (compl_length > (IOSIZE - MIN_SPACE))
6396 {
6397 compl_cont_status &= ~CONT_SOL;
6398 compl_length = (IOSIZE - MIN_SPACE);
6399 compl_col = curwin->w_cursor.col - compl_length;
6400 }
6401 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6402 if (compl_length < 1)
6403 compl_cont_status &= CONT_LOCAL;
6404 }
glepnird5fdfa52025-06-02 19:45:41 +02006405 else if (ctrl_x_mode_line_or_eval() || ctrl_x_mode_register())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006406 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6407 else
6408 compl_cont_status = 0;
6409}
6410
6411/*
6412 * start insert mode completion
6413 */
6414 static int
6415ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006416{
glepnir19e1dd62025-05-08 22:50:38 +02006417 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006418 int startcol = 0; // column where searched text starts
6419 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006420 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006421 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006422 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006423
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006424 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006425 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006426 did_si = FALSE;
6427 can_si = FALSE;
6428 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006429 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006430 return FAIL;
6431
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006432 line = ml_get(curwin->w_cursor.lnum);
6433 curs_col = curwin->w_cursor.col;
6434 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006435 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006436
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006437 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6438 && compl_cont_mode == ctrl_x_mode)
6439 // this same ctrl-x_mode was interrupted previously. Continue the
6440 // completion.
6441 ins_compl_continue_search(line);
6442 else
6443 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006444
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006445 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006446 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006447 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006448 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006449 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6450 compl_cont_status = 0;
6451 compl_cont_status |= CONT_N_ADDS;
6452 compl_startpos = curwin->w_cursor;
6453 startcol = (int)curs_col;
6454 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006455 }
6456
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006457 // Work out completion pattern and original text -- webb
6458 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6459 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006460 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6461 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006462 // restore did_ai, so that adding comment leader works
6463 did_ai = save_did_ai;
6464 return FAIL;
6465 }
6466 // If "line" was changed while getting completion info get it again.
6467 if (line_invalid)
6468 line = ml_get(curwin->w_cursor.lnum);
6469
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006470 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006471 {
6472 edit_submode_pre = (char_u *)_(" Adding");
6473 if (ctrl_x_mode_line_or_eval())
6474 {
6475 // Insert a new line, keep indentation but ignore 'comments'.
6476 char_u *old = curbuf->b_p_com;
6477
6478 curbuf->b_p_com = (char_u *)"";
6479 compl_startpos.lnum = curwin->w_cursor.lnum;
6480 compl_startpos.col = compl_col;
6481 ins_eol('\r');
6482 curbuf->b_p_com = old;
6483 compl_length = 0;
6484 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006485 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006486 }
glepnircfe502c2025-04-17 20:17:53 +02006487 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006488 {
6489 compl_startpos = curwin->w_cursor;
6490 compl_cont_status &= CONT_S_IPOS;
6491 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006492 }
6493 else
6494 {
6495 edit_submode_pre = NULL;
6496 compl_startpos.col = compl_col;
6497 }
6498
6499 if (compl_cont_status & CONT_LOCAL)
6500 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6501 else
6502 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6503
6504 // If any of the original typed text has been changed we need to fix
6505 // the redo buffer.
6506 ins_compl_fixRedoBufForLeader(NULL);
6507
6508 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006509 VIM_CLEAR_STRING(compl_orig_text);
6510 compl_orig_text.length = (size_t)compl_length;
6511 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006512 if (p_ic)
6513 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006514 if (compl_orig_text.string == NULL
6515 || ins_compl_add(compl_orig_text.string,
6516 (int)compl_orig_text.length,
6517 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006518 {
John Marriott5e6ea922024-11-23 14:01:57 +01006519 VIM_CLEAR_STRING(compl_pattern);
6520 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006521 return FAIL;
6522 }
6523
6524 // showmode might reset the internal line pointers, so it must
6525 // be called before line = ml_get(), or when this address is no
6526 // longer needed. -- Acevedo.
6527 edit_submode_extra = (char_u *)_("-- Searching...");
6528 edit_submode_highl = HLF_COUNT;
6529 showmode();
6530 edit_submode_extra = NULL;
6531 out_flush();
6532
6533 return OK;
6534}
6535
6536/*
6537 * display the completion status message
6538 */
6539 static void
6540ins_compl_show_statusmsg(void)
6541{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006542 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006543 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006544 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006545 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006546 ? (char_u *)_("Hit end of paragraph")
6547 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006548 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006549 }
6550
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006551 if (edit_submode_extra == NULL)
6552 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006553 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006554 {
6555 edit_submode_extra = (char_u *)_("Back at original");
6556 edit_submode_highl = HLF_W;
6557 }
6558 else if (compl_cont_status & CONT_S_IPOS)
6559 {
6560 edit_submode_extra = (char_u *)_("Word from other line");
6561 edit_submode_highl = HLF_COUNT;
6562 }
6563 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6564 {
6565 edit_submode_extra = (char_u *)_("The only match");
6566 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006567 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006568 }
6569 else
6570 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006571#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006572 // Update completion sequence number when needed.
6573 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006574 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006575#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006576 // The match should always have a sequence number now, this is
6577 // just a safety check.
6578 if (compl_curr_match->cp_number != -1)
6579 {
6580 // Space for 10 text chars. + 2x10-digit no.s = 31.
6581 // Translations may need more than twice that.
6582 static char_u match_ref[81];
6583
6584 if (compl_matches > 0)
6585 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006586 _("match %d of %d"),
6587 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006588 else
6589 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006590 _("match %d"),
6591 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006592 edit_submode_extra = match_ref;
6593 edit_submode_highl = HLF_R;
6594 if (dollar_vcol >= 0)
6595 curs_columns(FALSE);
6596 }
6597 }
6598 }
6599
6600 // Show a message about what (completion) mode we're in.
6601 if (!compl_opt_suppress_empty)
6602 {
6603 showmode();
6604 if (!shortmess(SHM_COMPLETIONMENU))
6605 {
6606 if (edit_submode_extra != NULL)
6607 {
6608 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006609 {
6610 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006611 msg_attr((char *)edit_submode_extra,
6612 edit_submode_highl < HLF_COUNT
6613 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006614 msg_hist_off = FALSE;
6615 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006616 }
6617 else
6618 msg_clr_cmdline(); // necessary for "noshowmode"
6619 }
6620 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006621}
6622
6623/*
6624 * Do Insert mode completion.
6625 * Called when character "c" was typed, which has a meaning for completion.
6626 * Returns OK if completion was done, FAIL if something failed (out of mem).
6627 */
6628 int
6629ins_complete(int c, int enable_pum)
6630{
6631 int n;
6632 int save_w_wrow;
6633 int save_w_leftcol;
6634 int insert_match;
6635
6636 compl_direction = ins_compl_key2dir(c);
6637 insert_match = ins_compl_use_match(c);
6638
6639 if (!compl_started)
6640 {
6641 if (ins_compl_start() == FAIL)
6642 return FAIL;
6643 }
6644 else if (insert_match && stop_arrow() == FAIL)
6645 return FAIL;
6646
glepnircf7f0122025-04-15 19:02:00 +02006647 compl_curr_win = curwin;
6648 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006649 compl_shown_match = compl_curr_match;
6650 compl_shows_dir = compl_direction;
6651
6652 // Find next match (and following matches).
6653 save_w_wrow = curwin->w_wrow;
6654 save_w_leftcol = curwin->w_leftcol;
6655 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6656
6657 // may undisplay the popup menu
6658 ins_compl_upd_pum();
6659
6660 if (n > 1) // all matches have been found
6661 compl_matches = n;
6662 compl_curr_match = compl_shown_match;
6663 compl_direction = compl_shows_dir;
6664
6665 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6666 // mode.
6667 if (got_int && !global_busy)
6668 {
6669 (void)vgetc();
6670 got_int = FALSE;
6671 }
6672
6673 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006674 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006675 {
6676 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6677 // because we couldn't expand anything at first place, but if we used
6678 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6679 // (such as M in M'exico) if not tried already. -- Acevedo
6680 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006681 || compl_status_adding()
6682 || (ctrl_x_mode_not_default()
6683 && !ctrl_x_mode_path_patterns()
6684 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006685 compl_cont_status &= ~CONT_N_ADDS;
6686 }
6687
6688 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6689 compl_cont_status |= CONT_S_IPOS;
6690 else
6691 compl_cont_status &= ~CONT_S_IPOS;
6692
6693 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006694
6695 // Show the popup menu, unless we got interrupted.
6696 if (enable_pum && !compl_interrupted)
6697 show_pum(save_w_wrow, save_w_leftcol);
6698
6699 compl_was_interrupted = compl_interrupted;
6700 compl_interrupted = FALSE;
6701
6702 return OK;
6703}
6704
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006705/*
6706 * Remove (if needed) and show the popup menu
6707 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006708 static void
6709show_pum(int prev_w_wrow, int prev_w_leftcol)
6710{
6711 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006712 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006713 RedrawingDisabled = 0;
6714
6715 // If the cursor moved or the display scrolled we need to remove the pum
6716 // first.
6717 setcursor();
6718 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6719 ins_compl_del_pum();
6720
6721 ins_compl_show_pum();
6722 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006723
6724 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006725}
6726
6727/*
6728 * Looks in the first "len" chars. of "src" for search-metachars.
6729 * If dest is not NULL the chars. are copied there quoting (with
6730 * a backslash) the metachars, and dest would be NUL terminated.
6731 * Returns the length (needed) of dest
6732 */
6733 static unsigned
6734quote_meta(char_u *dest, char_u *src, int len)
6735{
6736 unsigned m = (unsigned)len + 1; // one extra for the NUL
6737
6738 for ( ; --len >= 0; src++)
6739 {
6740 switch (*src)
6741 {
6742 case '.':
6743 case '*':
6744 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006745 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006746 break;
6747 // FALLTHROUGH
6748 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006749 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006750 break;
6751 // FALLTHROUGH
6752 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006753 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006754 break;
6755 // FALLTHROUGH
6756 case '^': // currently it's not needed.
6757 case '$':
6758 m++;
6759 if (dest != NULL)
6760 *dest++ = '\\';
6761 break;
6762 }
6763 if (dest != NULL)
6764 *dest++ = *src;
6765 // Copy remaining bytes of a multibyte character.
6766 if (has_mbyte)
6767 {
glepnir19e1dd62025-05-08 22:50:38 +02006768 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006769 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006770 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006771 {
6772 --len;
6773 ++src;
6774 if (dest != NULL)
6775 *dest++ = *src;
6776 }
6777 }
6778 }
6779 if (dest != NULL)
6780 *dest = NUL;
6781
6782 return m;
6783}
6784
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006785#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006786 void
6787free_insexpand_stuff(void)
6788{
John Marriott5e6ea922024-11-23 14:01:57 +01006789 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006790# ifdef FEAT_EVAL
6791 free_callback(&cfu_cb);
6792 free_callback(&ofu_cb);
6793 free_callback(&tsrfu_cb);
6794# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006795}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006796#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006797
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006798#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006799/*
6800 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6801 * spelled word, if there is one.
6802 */
6803 static void
6804spell_back_to_badword(void)
6805{
6806 pos_T tpos = curwin->w_cursor;
6807
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006808 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006809 if (curwin->w_cursor.col != tpos.col)
6810 start_arrow(&tpos);
6811}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006812#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006813
6814/*
6815 * Reset the info associated with completion sources.
6816 */
6817 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006818cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006819{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006820 VIM_CLEAR(cpt_sources_array);
6821 cpt_sources_index = -1;
6822 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006823}
6824
6825/*
Girish Palya98c29db2025-06-01 19:40:00 +02006826 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006827 */
6828 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006829setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006830{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006831 char_u buf[LSIZE];
6832 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006833 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006834 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006835
Girish Palya0ac1eb32025-04-16 20:18:33 +02006836 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006837 {
6838 while (*p == ',' || *p == ' ') // Skip delimiters
6839 p++;
6840 if (*p) // If not end of string, count this segment
6841 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006842 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006843 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006844 }
6845 }
Girish Palya98c29db2025-06-01 19:40:00 +02006846 if (count == 0)
6847 return OK;
6848
Girish Palya0ac1eb32025-04-16 20:18:33 +02006849 cpt_sources_clear();
6850 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006851 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6852 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006853 {
Girish Palya98c29db2025-06-01 19:40:00 +02006854 cpt_sources_count = 0;
6855 return FAIL;
6856 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006857
Girish Palya98c29db2025-06-01 19:40:00 +02006858 for (p = curbuf->b_p_cpt; *p;)
6859 {
6860 while (*p == ',' || *p == ' ') // Skip delimiters
6861 p++;
6862 if (*p) // If not end of string, count this segment
6863 {
6864 char_u *t;
6865
6866 vim_memset(buf, 0, LSIZE);
6867 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6868 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6869 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
6870 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006871 }
Girish Palyacbe53192025-04-14 22:13:15 +02006872 }
6873 return OK;
6874}
6875
6876/*
6877 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6878 */
6879 static int
6880is_cpt_func_refresh_always(void)
6881{
6882#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006883 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02006884 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006885 return TRUE;
6886#endif
6887 return FALSE;
6888}
6889
6890/*
6891 * Make the completion list non-cyclic.
6892 */
Girish Palyacbe53192025-04-14 22:13:15 +02006893 static void
6894ins_compl_make_linear(void)
6895{
6896 compl_T *m;
6897
6898 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6899 return;
6900 m = compl_first_match->cp_prev;
6901 m->cp_next = NULL;
6902 compl_first_match->cp_prev = NULL;
6903}
Girish Palyacbe53192025-04-14 22:13:15 +02006904
6905/*
6906 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006907 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006908 */
6909#ifdef FEAT_COMPL_FUNC
6910 static compl_T *
6911remove_old_matches(void)
6912{
6913 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6914 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006915 int compl_shown_removed = FALSE;
6916 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6917
6918 compl_direction = forward ? FORWARD : BACKWARD;
6919 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006920
6921 // Identify the sublist of old matches that needs removal
6922 for (current = compl_first_match; current != NULL; current = current->cp_next)
6923 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006924 if (current->cp_cpt_source_idx < cpt_sources_index &&
6925 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006926 insert_at = current;
6927
Girish Palya0ac1eb32025-04-16 20:18:33 +02006928 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006929 {
6930 if (!sublist_start)
6931 sublist_start = current;
6932 sublist_end = current;
6933 if (!compl_shown_removed && compl_shown_match == current)
6934 compl_shown_removed = TRUE;
6935 }
6936
Girish Palya0ac1eb32025-04-16 20:18:33 +02006937 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6938 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006939 break;
6940 }
6941
6942 // Re-assign compl_shown_match if necessary
6943 if (compl_shown_removed)
6944 {
6945 if (forward)
6946 compl_shown_match = compl_first_match;
6947 else
6948 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006949 for (current = compl_first_match; current->cp_next != NULL;
6950 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006951 ;
6952 compl_shown_match = current;
6953 }
6954 }
6955
6956 if (!sublist_start) // No nodes to remove
6957 return insert_at;
6958
6959 // Update links to remove sublist
6960 if (sublist_start->cp_prev)
6961 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6962 else
6963 compl_first_match = sublist_end->cp_next;
6964
6965 if (sublist_end->cp_next)
6966 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6967
6968 // Free all nodes in the sublist
6969 sublist_end->cp_next = NULL;
6970 for (current = sublist_start; current != NULL; current = next)
6971 {
6972 next = current->cp_next;
6973 ins_compl_item_free(current);
6974 }
6975
6976 return insert_at;
6977}
6978#endif
6979
6980/*
6981 * Retrieve completion matches using the callback function "cb" and store the
6982 * 'refresh:always' flag.
6983 */
6984#ifdef FEAT_COMPL_FUNC
6985 static void
6986get_cpt_func_completion_matches(callback_T *cb UNUSED)
6987{
Girish Palya98c29db2025-06-01 19:40:00 +02006988 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02006989
6990 VIM_CLEAR_STRING(cpt_compl_pattern);
Girish Palya98c29db2025-06-01 19:40:00 +02006991
6992 if (startcol == -2 || startcol == -3)
6993 return;
6994
6995 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02006996 {
6997 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02006998 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02006999 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02007000 compl_opt_refresh_always = FALSE;
7001 }
7002}
7003#endif
7004
7005/*
7006 * Retrieve completion matches from functions in the 'cpt' option where the
7007 * 'refresh:always' flag is set.
7008 */
7009 static void
7010cpt_compl_refresh(void)
7011{
7012#ifdef FEAT_COMPL_FUNC
7013 char_u *cpt;
7014 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007015 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007016 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007017
7018 // Make the completion list linear (non-cyclic)
7019 ins_compl_make_linear();
7020 // Make a copy of 'cpt' in case the buffer gets wiped out
7021 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007022 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007023
Girish Palya0ac1eb32025-04-16 20:18:33 +02007024 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007025 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007026 {
7027 while (*p == ',' || *p == ' ') // Skip delimiters
7028 p++;
7029
Girish Palya98c29db2025-06-01 19:40:00 +02007030 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007031 {
Girish Palya98c29db2025-06-01 19:40:00 +02007032 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007033 if (cb)
7034 {
7035 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007036 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7037 &startcol);
7038 if (ret == FAIL)
7039 {
7040 if (startcol == -3)
7041 cpt_sources_array[cpt_sources_index].cs_refresh_always
7042 = FALSE;
7043 else
7044 startcol = -2;
7045 }
7046 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7047 if (ret == OK)
7048 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007049 }
7050 }
7051
Girish Palya7c621052025-05-26 19:41:59 +02007052 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7053 if (may_advance_cpt_index(p))
7054 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007055 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007056 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007057
7058 vim_free(cpt);
7059 // Make the list cyclic
7060 compl_matches = ins_compl_make_cyclic();
7061#endif
7062}