blob: 66db022c19ff67fbaa0c7dbf5a3978c7f6307e66 [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);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100268
269#ifdef FEAT_SPELL
270static void spell_back_to_badword(void);
271static int spell_bad_len = 0; // length of located bad word
272#endif
273
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100274/*
275 * CTRL-X pressed in Insert mode.
276 */
277 void
278ins_ctrl_x(void)
279{
zeertzjqdca29d92021-08-31 19:12:51 +0200280 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100281 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000282 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100283 if (compl_cont_status & CONT_N_ADDS)
284 compl_cont_status |= CONT_INTRPT;
285 else
286 compl_cont_status = 0;
287 // We're not sure which CTRL-X mode it will be yet
288 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
289 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
290 edit_submode_pre = NULL;
291 showmode();
292 }
zeertzjqdca29d92021-08-31 19:12:51 +0200293 else
294 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
295 // CTRL-V look like CTRL-N
296 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100297
LemonBoy2bf52dd2022-04-09 18:17:34 +0100298 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100299}
300
301/*
302 * Functions to check the current CTRL-X mode.
303 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000304int ctrl_x_mode_none(void)
305 { return ctrl_x_mode == 0; }
306int ctrl_x_mode_normal(void)
307 { return ctrl_x_mode == CTRL_X_NORMAL; }
308int ctrl_x_mode_scroll(void)
309 { return ctrl_x_mode == CTRL_X_SCROLL; }
310int ctrl_x_mode_whole_line(void)
311 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
312int ctrl_x_mode_files(void)
313 { return ctrl_x_mode == CTRL_X_FILES; }
314int ctrl_x_mode_tags(void)
315 { return ctrl_x_mode == CTRL_X_TAGS; }
316int ctrl_x_mode_path_patterns(void)
317 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
318int ctrl_x_mode_path_defines(void)
319 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
320int ctrl_x_mode_dictionary(void)
321 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
322int ctrl_x_mode_thesaurus(void)
323 { return ctrl_x_mode == CTRL_X_THESAURUS; }
324int ctrl_x_mode_cmdline(void)
325 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200326 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000327int ctrl_x_mode_function(void)
328 { return ctrl_x_mode == CTRL_X_FUNCTION; }
329int ctrl_x_mode_omni(void)
330 { return ctrl_x_mode == CTRL_X_OMNI; }
331int ctrl_x_mode_spell(void)
332 { return ctrl_x_mode == CTRL_X_SPELL; }
333static int ctrl_x_mode_eval(void)
334 { return ctrl_x_mode == CTRL_X_EVAL; }
335int ctrl_x_mode_line_or_eval(void)
336 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
glepnir05460682025-05-26 18:23:27 +0200337int ctrl_x_mode_register(void)
338 { return ctrl_x_mode == CTRL_X_REGISTER; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100339
340/*
341 * Whether other than default completion has been selected.
342 */
343 int
344ctrl_x_mode_not_default(void)
345{
346 return ctrl_x_mode != CTRL_X_NORMAL;
347}
348
349/*
zeertzjqdca29d92021-08-31 19:12:51 +0200350 * Whether CTRL-X was typed without a following character,
351 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100352 */
353 int
354ctrl_x_mode_not_defined_yet(void)
355{
356 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
357}
358
359/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000360 * Return TRUE if currently in "normal" or "adding" insert completion matches
361 * state
362 */
363 int
364compl_status_adding(void)
365{
366 return compl_cont_status & CONT_ADDING;
367}
368
369/*
370 * Return TRUE if the completion pattern includes start of line, just for
371 * word-wise expansion.
372 */
373 int
374compl_status_sol(void)
375{
376 return compl_cont_status & CONT_SOL;
377}
378
379/*
380 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
381 */
382 int
383compl_status_local(void)
384{
385 return compl_cont_status & CONT_LOCAL;
386}
387
388/*
389 * Clear the completion status flags
390 */
391 void
392compl_status_clear(void)
393{
394 compl_cont_status = 0;
395}
396
397/*
398 * Return TRUE if completion is using the forward direction matches
399 */
400 static int
401compl_dir_forward(void)
402{
403 return compl_direction == FORWARD;
404}
405
406/*
407 * Return TRUE if currently showing forward completion matches
408 */
409 static int
410compl_shows_dir_forward(void)
411{
412 return compl_shows_dir == FORWARD;
413}
414
415/*
416 * Return TRUE if currently showing backward completion matches
417 */
418 static int
419compl_shows_dir_backward(void)
420{
421 return compl_shows_dir == BACKWARD;
422}
423
424/*
425 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100426 */
427 int
428has_compl_option(int dict_opt)
429{
430 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200431#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100432 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200433#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100435 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
436#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100437 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100438#endif
439 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100440 {
441 ctrl_x_mode = CTRL_X_NORMAL;
442 edit_submode = NULL;
443 msg_attr(dict_opt ? _("'dictionary' option is empty")
444 : _("'thesaurus' option is empty"),
445 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100446 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100447 {
448 vim_beep(BO_COMPL);
449 setcursor();
450 out_flush();
451#ifdef FEAT_EVAL
452 if (!get_vim_var_nr(VV_TESTING))
453#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100454 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100455 }
456 return FALSE;
457 }
458 return TRUE;
459}
460
461/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000462 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100463 * This depends on the current mode.
464 */
465 int
466vim_is_ctrl_x_key(int c)
467{
468 // Always allow ^R - let its results then be checked
glepnir05460682025-05-26 18:23:27 +0200469 if (c == Ctrl_R && ctrl_x_mode != CTRL_X_REGISTER)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100470 return TRUE;
471
472 // Accept <PageUp> and <PageDown> if the popup menu is visible.
473 if (ins_compl_pum_key(c))
474 return TRUE;
475
476 switch (ctrl_x_mode)
477 {
478 case 0: // Not in any CTRL-X mode
479 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
480 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200481 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100482 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
483 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
484 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
485 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
486 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200487 || c == Ctrl_S || c == Ctrl_K || c == 's'
glepnir05460682025-05-26 18:23:27 +0200488 || c == Ctrl_Z || c == Ctrl_R);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100489 case CTRL_X_SCROLL:
490 return (c == Ctrl_Y || c == Ctrl_E);
491 case CTRL_X_WHOLE_LINE:
492 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
493 case CTRL_X_FILES:
494 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
495 case CTRL_X_DICTIONARY:
496 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
497 case CTRL_X_THESAURUS:
498 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
499 case CTRL_X_TAGS:
500 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
501#ifdef FEAT_FIND_ID
502 case CTRL_X_PATH_PATTERNS:
503 return (c == Ctrl_P || c == Ctrl_N);
504 case CTRL_X_PATH_DEFINES:
505 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
506#endif
507 case CTRL_X_CMDLINE:
508 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
509 || c == Ctrl_X);
510#ifdef FEAT_COMPL_FUNC
511 case CTRL_X_FUNCTION:
512 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
513 case CTRL_X_OMNI:
514 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
515#endif
516 case CTRL_X_SPELL:
517 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
518 case CTRL_X_EVAL:
519 return (c == Ctrl_P || c == Ctrl_N);
glepnir05460682025-05-26 18:23:27 +0200520 case CTRL_X_REGISTER:
521 return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100522 }
523 internal_error("vim_is_ctrl_x_key()");
524 return FALSE;
525}
526
527/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000528 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000529 */
530 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000531match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000532{
533 return match->cp_flags & CP_ORIGINAL_TEXT;
534}
535
536/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000537 * Returns TRUE if "match" is the first match in the completion list.
538 */
539 static int
540is_first_match(compl_T *match)
541{
542 return match == compl_first_match;
543}
544
545/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100546 * Return TRUE when character "c" is part of the item currently being
547 * completed. Used to decide whether to abandon complete mode when the menu
548 * is visible.
549 */
550 int
551ins_compl_accept_char(int c)
552{
553 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
554 // When expanding an identifier only accept identifier chars.
555 return vim_isIDc(c);
556
557 switch (ctrl_x_mode)
558 {
559 case CTRL_X_FILES:
560 // When expanding file name only accept file name chars. But not
561 // path separators, so that "proto/<Tab>" expands files in
562 // "proto", not "proto/" as a whole
563 return vim_isfilec(c) && !vim_ispathsep(c);
564
565 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200566 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100567 case CTRL_X_OMNI:
568 // Command line and Omni completion can work with just about any
569 // printable character, but do stop at white space.
570 return vim_isprintc(c) && !VIM_ISWHITE(c);
571
572 case CTRL_X_WHOLE_LINE:
573 // For while line completion a space can be part of the line.
574 return vim_isprintc(c);
575 }
576 return vim_iswordc(c);
577}
578
579/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000580 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100581 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 */
583 static char_u *
584ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200585 char_u *str,
586 int char_len,
587 int compl_char_len,
588 int min_len,
589 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000590{
591 int *wca; // Wide character array.
592 char_u *p;
593 int i, c;
594 int has_lower = FALSE;
595 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100596 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000597
598 IObuff[0] = NUL;
599
600 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100601 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000602 if (wca == NULL)
603 return IObuff;
604
605 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100606 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100607 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000608 if (has_mbyte)
609 wca[i] = mb_ptr2char_adv(&p);
610 else
611 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100612 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000613
614 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100615 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000616 for (i = 0; i < min_len; ++i)
617 {
glepnir6e199932024-12-14 21:13:27 +0100618 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000619 if (MB_ISLOWER(c))
620 {
621 has_lower = TRUE;
622 if (MB_ISUPPER(wca[i]))
623 {
624 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100625 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000626 wca[i] = MB_TOLOWER(wca[i]);
627 break;
628 }
629 }
630 }
631
632 // Rule 2: No lower case, 2nd consecutive letter converted to
633 // upper case.
634 if (!has_lower)
635 {
John Marriott5e6ea922024-11-23 14:01:57 +0100636 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000637 for (i = 0; i < min_len; ++i)
638 {
glepnir6e199932024-12-14 21:13:27 +0100639 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000640 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
641 {
642 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100643 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000644 wca[i] = MB_TOUPPER(wca[i]);
645 break;
646 }
647 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
648 }
649 }
650
651 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100652 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000653 for (i = 0; i < min_len; ++i)
654 {
glepnir6e199932024-12-14 21:13:27 +0100655 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000656 if (MB_ISLOWER(c))
657 wca[i] = MB_TOLOWER(wca[i]);
658 else if (MB_ISUPPER(c))
659 wca[i] = MB_TOUPPER(wca[i]);
660 }
661
662 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000663 p = IObuff;
664 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100665 ga_init2(&gap, 1, 500);
666 while (i < char_len)
667 {
668 if (gap.ga_data != NULL)
669 {
670 if (ga_grow(&gap, 10) == FAIL)
671 {
672 ga_clear(&gap);
673 return (char_u *)"[failed]";
674 }
675 p = (char_u *)gap.ga_data + gap.ga_len;
676 if (has_mbyte)
677 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
678 else
679 {
680 *p = wca[i++];
681 ++gap.ga_len;
682 }
683 }
684 else if ((p - IObuff) + 6 >= IOSIZE)
685 {
686 // Multi-byte characters can occupy up to five bytes more than
687 // ASCII characters, and we also need one byte for NUL, so when
688 // getting to six bytes from the edge of IObuff switch to using a
689 // growarray. Add the character in the next round.
690 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100691 {
692 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100693 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100694 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100695 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100696 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100697 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 }
699 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000700 p += (*mb_char2bytes)(wca[i++], p);
701 else
702 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100703 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000704 vim_free(wca);
705
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100706 if (gap.ga_data != NULL)
707 {
708 *tofree = gap.ga_data;
709 return gap.ga_data;
710 }
711
712 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000713 return IObuff;
714}
715
716/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100717 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
718 * case of the originally typed text is used, and the case of the completed
719 * text is inferred, ie this tries to work out what case you probably wanted
720 * the rest of the word to be in -- webb
721 */
722 int
723ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200724 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 int len,
726 int icase,
727 char_u *fname,
728 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100729 int cont_s_ipos, // next ^X<> will set initial_pos
730 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100731{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200732 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100734 int char_len; // count multi-byte characters
735 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100736 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200737 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 int res;
739 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100740
741 if (p_ic && curbuf->b_p_inf && len > 0)
742 {
743 // Infer case of completed part.
744
745 // Find actual length of completion.
746 if (has_mbyte)
747 {
748 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100749 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100750 while (*p != NUL)
751 {
752 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100753 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100754 }
755 }
756 else
glepnir6e199932024-12-14 21:13:27 +0100757 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100758 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100759 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100760
761 // Find actual length of original text.
762 if (has_mbyte)
763 {
John Marriott5e6ea922024-11-23 14:01:57 +0100764 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100765 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 while (*p != NUL)
767 {
768 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100769 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100770 }
771 }
772 else
glepnir6e199932024-12-14 21:13:27 +0100773 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100774 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100775 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100776
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100777 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100778 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100779 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100781 str = ins_compl_infercase_gettext(str, char_len,
782 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100783 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200784 if (cont_s_ipos)
785 flags |= CP_CONT_S_IPOS;
786 if (icase)
787 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200788
glepnirf31cfa22025-03-06 21:59:13 +0100789 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100790 vim_free(tofree);
791 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100792}
793
794/*
glepnirf31cfa22025-03-06 21:59:13 +0100795 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
796 */
797 static int
798cfc_has_mode(void)
799{
glepnir58760162025-03-13 21:39:51 +0100800 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
801 return (cfc_flags & CFC_KEYWORD) != 0;
802 else if (ctrl_x_mode_files())
803 return (cfc_flags & CFC_FILES) != 0;
804 else if (ctrl_x_mode_whole_line())
805 return (cfc_flags & CFC_WHOLELINE) != 0;
806 else
807 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100808}
809
810/*
Girish Palyab1565882025-04-15 20:16:00 +0200811 * Returns TRUE if matches should be sorted based on proximity to the cursor.
812 */
813 static int
814is_nearest_active(void)
815{
glepnirc3fbaa02025-05-08 23:05:10 +0200816 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200817}
818
819/*
820 * Repositions a match in the completion list based on its proximity score.
821 * If the match is at the head and has a higher score than the next node,
822 * or if it's in the middle/tail and has a lower score than the previous node,
823 * it is moved to the correct position while maintaining ascending order.
824 */
825 static void
826reposition_match(compl_T *match)
827{
828 compl_T *insert_before = NULL;
829 compl_T *insert_after = NULL;
830
831 // Node is at head and score is too big
832 if (!match->cp_prev)
833 {
834 if (match->cp_next && match->cp_next->cp_score > 0 &&
835 match->cp_next->cp_score < match->cp_score)
836 {
837 // <c-p>: compl_first_match is at head and newly inserted node
838 compl_first_match = compl_curr_match = match->cp_next;
839 // Find the correct position in ascending order
840 insert_before = match->cp_next;
841 do
842 {
843 insert_after = insert_before;
844 insert_before = insert_before->cp_next;
845 } while (insert_before && insert_before->cp_score > 0 &&
846 insert_before->cp_score < match->cp_score);
847 }
848 else
849 return;
850 }
851 // Node is at tail or in the middle but score is too small
852 else
853 {
854 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
855 {
856 // <c-n>: compl_curr_match (and newly inserted match) is at tail
857 if (!match->cp_next)
858 compl_curr_match = compl_curr_match->cp_prev;
859 // Find the correct position in ascending order
860 insert_after = match->cp_prev;
861 do
862 {
863 insert_before = insert_after;
864 insert_after = insert_after->cp_prev;
865 } while (insert_after && insert_after->cp_score > 0 &&
866 insert_after->cp_score > match->cp_score);
867 }
868 else
869 return;
870 }
871
872 if (insert_after)
873 {
874 // Remove the match from its current position
875 if (match->cp_prev)
876 match->cp_prev->cp_next = match->cp_next;
877 else
878 compl_first_match = match->cp_next;
879 if (match->cp_next)
880 match->cp_next->cp_prev = match->cp_prev;
881
882 // Insert the match at the correct position
883 match->cp_next = insert_before;
884 match->cp_prev = insert_after;
885 insert_after->cp_next = match;
886 insert_before->cp_prev = match;
887 }
888}
889
890/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000891 * Add a match to the list of matches. The arguments are:
892 * str - text of the match to add
893 * len - length of "str". If -1, then the length of "str" is
894 * computed.
895 * fname - file name to associate with this match.
896 * cptext - list of strings to use with this match (for abbr, menu, info
897 * and kind)
898 * user_data - user supplied data (any vim type) for this match
899 * cdir - match direction. If 0, use "compl_direction".
900 * flags_arg - match flags (cp_flags)
901 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100902 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000903 * If "cdir" is FORWARD, then the match is added after the current match.
904 * Otherwise, it is added before the current match.
905 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100906 * If the given string is already in the list of completions, then return
907 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
908 * maybe because alloc() returns NULL, then FAIL is returned.
909 */
910 static int
911ins_compl_add(
912 char_u *str,
913 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100914 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100915 char_u **cptext, // extra text for popup menu or NULL
916 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100917 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200918 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200919 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100920 int *user_hl, // user abbr/kind hlattr
921 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100922{
glepnirf31cfa22025-03-06 21:59:13 +0100923 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100924 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200925 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100926 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100927
Bram Moolenaarceb06192021-04-04 15:05:22 +0200928 if (flags & CP_FAST)
929 fast_breakcheck();
930 else
931 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100932 if (got_int)
933 return FAIL;
934 if (len < 0)
935 len = (int)STRLEN(str);
936
937 // If the same match is already present, don't add it.
938 if (compl_first_match != NULL && !adup)
939 {
940 match = compl_first_match;
941 do
942 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000943 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100944 && STRNCMP(match->cp_str.string, str, len) == 0
945 && ((int)match->cp_str.length <= len
946 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200947 {
948 if (is_nearest_active() && score > 0 && score < match->cp_score)
949 {
950 match->cp_score = score;
951 reposition_match(match);
952 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100953 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200954 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100955 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000956 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100957 }
958
959 // Remove any popup menu before changing the list of matches.
960 ins_compl_del_pum();
961
962 // Allocate a new match structure.
963 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200964 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100965 if (match == NULL)
966 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100967 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100968 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100969 {
970 vim_free(match);
971 return FAIL;
972 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100973
John Marriott5e6ea922024-11-23 14:01:57 +0100974 match->cp_str.length = len;
975
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100976 // match-fname is:
977 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200978 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100979 // - NULL otherwise. --Acevedo
980 if (fname != NULL
981 && compl_curr_match != NULL
982 && compl_curr_match->cp_fname != NULL
983 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
984 match->cp_fname = compl_curr_match->cp_fname;
985 else if (fname != NULL)
986 {
987 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200988 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100989 }
990 else
991 match->cp_fname = NULL;
992 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100993 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
994 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100995 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200996 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100997
998 if (cptext != NULL)
999 {
glepnir19e1dd62025-05-08 22:50:38 +02001000 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +01001001 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002 if (cptext[i] != NULL && *cptext[i] != NUL)
1003 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +01001004 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001005 }
Bram Moolenaarab782c52020-01-04 19:00:11 +01001006#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001007 if (user_data != NULL)
1008 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +01001009#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001010
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001011 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1012 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001013 if (compl_first_match == NULL)
1014 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001015 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1016 {
1017 current = compl_first_match->cp_next;
1018 prev = compl_first_match;
1019 inserted = FALSE;
1020 // The direction is ignored when using longest and
1021 // completefuzzycollect, because matches are inserted
1022 // and sorted by score.
1023 while (current != NULL && current != compl_first_match)
1024 {
1025 if (current->cp_score < score)
1026 {
Hirohito Higashi355db992025-04-28 18:07:02 +02001027 match->cp_next = current;
1028 match->cp_prev = current->cp_prev;
1029 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +01001030 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +02001031 current->cp_prev = match;
1032 inserted = TRUE;
1033 break;
glepnirf31cfa22025-03-06 21:59:13 +01001034 }
1035 prev = current;
1036 current = current->cp_next;
1037 }
1038 if (!inserted)
1039 {
1040 prev->cp_next = match;
1041 match->cp_prev = prev;
1042 match->cp_next = compl_first_match;
1043 compl_first_match->cp_prev = match;
1044 }
1045 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001046 else if (dir == FORWARD)
1047 {
1048 match->cp_next = compl_curr_match->cp_next;
1049 match->cp_prev = compl_curr_match;
1050 }
1051 else // BACKWARD
1052 {
1053 match->cp_next = compl_curr_match;
1054 match->cp_prev = compl_curr_match->cp_prev;
1055 }
1056 if (match->cp_next)
1057 match->cp_next->cp_prev = match;
1058 if (match->cp_prev)
1059 match->cp_prev->cp_next = match;
1060 else // if there's nothing before, it is the first match
1061 compl_first_match = match;
1062 compl_curr_match = match;
1063
Girish Palyab1565882025-04-15 20:16:00 +02001064 if (is_nearest_active() && score > 0)
1065 reposition_match(match);
1066
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001067 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001068 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001069 ins_compl_longest_match(match);
1070
1071 return OK;
1072}
1073
1074/*
1075 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001076 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001077 */
1078 static int
1079ins_compl_equal(compl_T *match, char_u *str, int len)
1080{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001081 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001082 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001083 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001084 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1085 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001086}
1087
1088/*
glepnir6a38aff2024-12-16 21:56:16 +01001089 * when len is -1 mean use whole length of p otherwise part of p
1090 */
1091 static void
1092ins_compl_insert_bytes(char_u *p, int len)
1093{
1094 if (len == -1)
1095 len = (int)STRLEN(p);
1096 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001097 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001098}
1099
1100/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001101 * Checks if the column is within the currently inserted completion text
1102 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001103 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001104 */
1105 int
glepnir76bdb822025-02-08 19:04:51 +01001106ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001107{
glepnir76bdb822025-02-08 19:04:51 +01001108 int start_col;
1109 int attr;
1110
1111 if ((get_cot_flags() & COT_FUZZY)
1112 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001113 return -1;
1114
glepnir76bdb822025-02-08 19:04:51 +01001115 start_col = compl_col + (int)ins_compl_leader_len();
1116 if (!ins_compl_has_multiple())
1117 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1118
1119 // Multiple lines
1120 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1121 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1122 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1123 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001124
1125 return -1;
1126}
1127
1128/*
glepnir76bdb822025-02-08 19:04:51 +01001129 * Returns TRUE if the current completion string contains newline characters,
1130 * indicating it's a multi-line completion.
1131 */
1132 static int
1133ins_compl_has_multiple(void)
1134{
1135 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1136}
1137
1138/*
1139 * Returns TRUE if the given line number falls within the range of a multi-line
1140 * completion, i.e. between the starting line (compl_lnum) and current cursor
1141 * line. Always returns FALSE for single-line completions.
1142 */
1143 int
1144ins_compl_lnum_in_range(linenr_T lnum)
1145{
1146 if (!ins_compl_has_multiple())
1147 return FALSE;
1148 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1149}
1150
1151/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001152 * Reduce the longest common string for match "match".
1153 */
1154 static void
1155ins_compl_longest_match(compl_T *match)
1156{
1157 char_u *p, *s;
1158 int c1, c2;
1159 int had_match;
1160
John Marriott5e6ea922024-11-23 14:01:57 +01001161 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001162 {
1163 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001164 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1165 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001166 return;
1167
John Marriott5e6ea922024-11-23 14:01:57 +01001168 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001169 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001170 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001171
1172 // When the match isn't there (to avoid matching itself) remove it
1173 // again after redrawing.
1174 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001176 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001177
1178 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001179 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001180
1181 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001182 p = compl_leader.string;
1183 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001184 while (*p != NUL)
1185 {
1186 if (has_mbyte)
1187 {
1188 c1 = mb_ptr2char(p);
1189 c2 = mb_ptr2char(s);
1190 }
1191 else
1192 {
1193 c1 = *p;
1194 c2 = *s;
1195 }
1196 if ((match->cp_flags & CP_ICASE)
1197 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1198 break;
1199 if (has_mbyte)
1200 {
1201 MB_PTR_ADV(p);
1202 MB_PTR_ADV(s);
1203 }
1204 else
1205 {
1206 ++p;
1207 ++s;
1208 }
1209 }
1210
1211 if (*p != NUL)
1212 {
1213 // Leader was shortened, need to change the inserted text.
1214 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001215 compl_leader.length = (size_t)(p - compl_leader.string);
1216
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001217 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001218 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001219
1220 // When the match isn't there (to avoid matching itself) remove it
1221 // again after redrawing.
1222 if (!had_match)
1223 ins_compl_delete();
1224 }
1225
1226 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227}
1228
1229/*
1230 * Add an array of matches to the list of matches.
1231 * Frees matches[].
1232 */
1233 static void
1234ins_compl_add_matches(
1235 int num_matches,
1236 char_u **matches,
1237 int icase)
1238{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001239 int add_r = OK;
1240 int dir = compl_direction;
1241
glepnir19e1dd62025-05-08 22:50:38 +02001242 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001243 {
1244 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001245 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001246 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001247 // if dir was BACKWARD then honor it just once
1248 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001249 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001250 FreeWild(num_matches, matches);
1251}
1252
1253/*
1254 * Make the completion list cyclic.
1255 * Return the number of matches (excluding the original).
1256 */
1257 static int
1258ins_compl_make_cyclic(void)
1259{
1260 compl_T *match;
1261 int count = 0;
1262
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001263 if (compl_first_match == NULL)
1264 return 0;
1265
1266 // Find the end of the list.
1267 match = compl_first_match;
1268 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001269 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001270 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001271 match = match->cp_next;
1272 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001273 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001274 match->cp_next = compl_first_match;
1275 compl_first_match->cp_prev = match;
1276
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001277 return count;
1278}
1279
1280/*
1281 * Return whether there currently is a shown match.
1282 */
1283 int
1284ins_compl_has_shown_match(void)
1285{
1286 return compl_shown_match == NULL
1287 || compl_shown_match != compl_shown_match->cp_next;
1288}
1289
1290/*
1291 * Return whether the shown match is long enough.
1292 */
1293 int
1294ins_compl_long_shown_match(void)
1295{
John Marriott5e6ea922024-11-23 14:01:57 +01001296 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001297 > curwin->w_cursor.col - compl_col;
1298}
1299
1300/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001301 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001302 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 unsigned int
1304get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001305{
zeertzjq529b9ad2024-06-05 20:27:06 +02001306 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001307}
1308
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001309/*
1310 * Update the screen and when there is any scrolling remove the popup menu.
1311 */
1312 static void
1313ins_compl_upd_pum(void)
1314{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001315 if (compl_match_array == NULL)
1316 return;
1317
glepnir19e1dd62025-05-08 22:50:38 +02001318 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001319 // Update the screen later, before drawing the popup menu over it.
1320 pum_call_update_screen();
1321 if (h != curwin->w_cline_height)
1322 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001323}
1324
1325/*
1326 * Remove any popup menu.
1327 */
1328 static void
1329ins_compl_del_pum(void)
1330{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001331 if (compl_match_array == NULL)
1332 return;
1333
1334 pum_undisplay();
1335 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001336}
1337
1338/*
1339 * Return TRUE if the popup menu should be displayed.
1340 */
1341 int
1342pum_wanted(void)
1343{
1344 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001345 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001346 return FALSE;
1347
1348 // The display looks bad on a B&W display.
1349 if (t_colors < 8
1350#ifdef FEAT_GUI
1351 && !gui.in_use
1352#endif
1353 )
1354 return FALSE;
1355 return TRUE;
1356}
1357
1358/*
1359 * Return TRUE if there are two or more matches to be shown in the popup menu.
1360 * One if 'completopt' contains "menuone".
1361 */
1362 static int
1363pum_enough_matches(void)
1364{
1365 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001366 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001367
1368 // Don't display the popup menu if there are no matches or there is only
1369 // one (ignoring the original text).
1370 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001371 do
1372 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001373 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001374 break;
1375 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001376 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001377
zeertzjq529b9ad2024-06-05 20:27:06 +02001378 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001379 return (i >= 1);
1380 return (i >= 2);
1381}
1382
Bram Moolenaar3075a452021-11-17 15:51:52 +00001383#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001384/*
1385 * Allocate Dict for the completed item.
1386 * { word, abbr, menu, kind, info }
1387 */
1388 static dict_T *
1389ins_compl_dict_alloc(compl_T *match)
1390{
1391 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1392
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001393 if (dict == NULL)
1394 return NULL;
1395
John Marriott5e6ea922024-11-23 14:01:57 +01001396 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001397 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1398 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1399 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1400 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1401 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1402 dict_add_string(dict, "user_data", (char_u *)"");
1403 else
1404 dict_add_tv(dict, "user_data", &match->cp_user_data);
1405
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001406 return dict;
1407}
1408
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001409/*
1410 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1411 * completion menu is changed.
1412 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001413 static void
1414trigger_complete_changed_event(int cur)
1415{
1416 dict_T *v_event;
1417 dict_T *item;
1418 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001419 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001420
1421 if (recursive)
1422 return;
1423
glepnir40891ba2025-02-10 22:18:00 +01001424 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001425 if (item == NULL)
1426 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001427 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001428 dict_add_dict(v_event, "completed_item", item);
1429 pum_set_event_info(v_event);
1430 dict_set_items_ro(v_event);
1431
1432 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001433 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001434 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001435 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001436 recursive = FALSE;
1437
Bram Moolenaar3075a452021-11-17 15:51:52 +00001438 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001439}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001440#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001441
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001442/*
Girish Palya19ef6b02025-05-28 20:28:21 +02001443 * Trim compl_match_array to enforce max_matches per completion source.
1444 *
1445 * Note: This special-case trimming is a workaround because compl_match_array
1446 * becomes inconsistent with compl_first_match (list) after former is sorted by
1447 * fuzzy score. The two structures end up in different orders.
1448 * Ideally, compl_first_match list should have been sorted instead.
1449 */
1450 static void
1451trim_compl_match_array(void)
1452{
1453 int i, src_idx, limit, new_size = 0, *match_counts = NULL;
1454 pumitem_T *trimmed = NULL;
1455 int trimmed_idx = 0;
1456
1457 // Count current matches per source.
1458 match_counts = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1459 if (match_counts == NULL)
1460 return;
1461 for (i = 0; i < compl_match_arraysize; i++)
1462 {
1463 src_idx = compl_match_array[i].pum_cpt_source_idx;
1464 if (src_idx != -1)
1465 match_counts[src_idx]++;
1466 }
1467
1468 // Calculate size of trimmed array, respecting max_matches per source.
1469 for (i = 0; i < cpt_sources_count; i++)
1470 {
Girish Palya98c29db2025-06-01 19:40:00 +02001471 limit = cpt_sources_array[i].cs_max_matches;
Girish Palya19ef6b02025-05-28 20:28:21 +02001472 new_size += (limit > 0 && match_counts[i] > limit)
1473 ? limit : match_counts[i];
1474 }
1475
1476 if (new_size == compl_match_arraysize)
1477 goto theend;
1478
1479 // Create trimmed array while enforcing per-source limits
1480 trimmed = ALLOC_CLEAR_MULT(pumitem_T, new_size);
1481 if (trimmed == NULL)
1482 goto theend;
1483 vim_memset(match_counts, 0, sizeof(int) * cpt_sources_count);
1484 for (i = 0; i < compl_match_arraysize; i++)
1485 {
1486 src_idx = compl_match_array[i].pum_cpt_source_idx;
1487 if (src_idx != -1)
1488 {
Girish Palya98c29db2025-06-01 19:40:00 +02001489 limit = cpt_sources_array[src_idx].cs_max_matches;
Girish Palya19ef6b02025-05-28 20:28:21 +02001490 if (limit <= 0 || match_counts[src_idx] < limit)
1491 {
1492 trimmed[trimmed_idx++] = compl_match_array[i];
1493 match_counts[src_idx]++;
1494 }
1495 }
1496 else
1497 trimmed[trimmed_idx++] = compl_match_array[i];
1498 }
1499 vim_free(compl_match_array);
1500 compl_match_array = trimmed;
1501 compl_match_arraysize = new_size;
1502
1503theend:
1504 vim_free(match_counts);
1505}
1506
1507/*
glepnira218cc62024-06-03 19:32:39 +02001508 * pumitem qsort compare func
1509 */
1510 static int
zeertzjq8e567472024-06-14 20:04:42 +02001511ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001512{
1513 const int sa = (*(pumitem_T *)a).pum_score;
1514 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001515 const int ia = (*(pumitem_T *)a).pum_idx;
1516 const int ib = (*(pumitem_T *)b).pum_idx;
1517 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001518}
1519
1520/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001521 * Build a popup menu to show the completion matches.
1522 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1523 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001524 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001525 static int
1526ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001527{
1528 compl_T *compl;
1529 compl_T *shown_compl = NULL;
1530 int did_find_shown_match = FALSE;
1531 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001532 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001533 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001534 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001535 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001536 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001537 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1538 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001539 compl_T *match_head = NULL;
1540 compl_T *match_tail = NULL;
1541 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001542 int update_shown_match = fuzzy_filter;
Christian Brabandtb53d4fb2025-04-16 21:12:30 +02001543 int match_count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001544 int cur_source = -1;
1545 int max_matches_found = FALSE;
Girish Palya19ef6b02025-05-28 20:28:21 +02001546 int is_forward = compl_shows_dir_forward();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001547
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001548 // Need to build the popup menu list.
1549 compl_match_arraysize = 0;
1550 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001551
glepnira49c0772024-11-30 10:56:30 +01001552 // If the current match is the original text don't find the first
1553 // match after it, don't highlight anything.
1554 if (match_at_original_text(compl_shown_match))
1555 shown_match_ok = TRUE;
1556
glepnire4e4d1c2025-04-02 20:18:25 +02001557 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1558 && compl_shown_match->cp_score > 0)
1559 update_shown_match = FALSE;
1560
glepnira49c0772024-11-30 10:56:30 +01001561 if (compl_leader.string != NULL
1562 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1563 && shown_match_ok == FALSE)
1564 compl_shown_match = compl_no_select ? compl_first_match
1565 : compl_first_match->cp_next;
1566
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001567 do
1568 {
glepnird4088ed2024-12-31 10:55:22 +01001569 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001570 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1571 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001572 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001573 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001574
Girish Palya19ef6b02025-05-28 20:28:21 +02001575 if (is_forward && !fuzzy_sort && compl->cp_cpt_source_idx != -1)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001576 {
1577 if (cur_source != compl->cp_cpt_source_idx)
1578 {
1579 cur_source = compl->cp_cpt_source_idx;
1580 match_count = 1;
1581 max_matches_found = FALSE;
1582 }
Girish Palyadc314052025-05-08 23:28:52 +02001583 else if (cpt_sources_array != NULL && !max_matches_found)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001584 {
Girish Palya98c29db2025-06-01 19:40:00 +02001585 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001586 if (max_matches > 0 && match_count > max_matches)
1587 max_matches_found = TRUE;
1588 }
1589 }
1590
Girish Palyadc314052025-05-08 23:28:52 +02001591 // Apply 'smartcase' behavior during normal mode
1592 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1593 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1594 compl->cp_flags &= ~CP_ICASE;
1595
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001596 if (!match_at_original_text(compl)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001597 && !max_matches_found
John Marriott5e6ea922024-11-23 14:01:57 +01001598 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001599 || ins_compl_equal(compl, compl_leader.string,
1600 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001601 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001602 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001603 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001604 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001605 if (match_head == NULL)
1606 match_head = compl;
1607 else
glepnira49c0772024-11-30 10:56:30 +01001608 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001609 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001610
glepnirf400a0c2025-01-23 19:55:14 +01001611 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001612 {
1613 if (compl == compl_shown_match || did_find_shown_match)
1614 {
1615 // This item is the shown match or this is the
1616 // first displayed item after the shown match.
1617 compl_shown_match = compl;
1618 did_find_shown_match = TRUE;
1619 shown_match_ok = TRUE;
1620 }
1621 else
1622 // Remember this displayed match for when the
1623 // shown match is just below it.
1624 shown_compl = compl;
1625 cur = i;
1626 }
glepnirf400a0c2025-01-23 19:55:14 +01001627 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001628 {
1629 if (i == 0)
1630 shown_compl = compl;
1631 // Update the maximum fuzzy score and the shown match
1632 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001633 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1634 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001635 {
1636 did_find_shown_match = TRUE;
1637 max_fuzzy_score = compl->cp_score;
1638 if (!compl_no_select)
1639 compl_shown_match = compl;
1640 }
1641
glepnir3af0a8d2025-02-20 22:06:16 +01001642 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001643 {
1644 cur = i;
1645 shown_match_ok = TRUE;
1646 }
1647 }
Girish Palya19ef6b02025-05-28 20:28:21 +02001648 if (is_forward && !fuzzy_sort && compl->cp_cpt_source_idx != -1)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001649 match_count++;
glepnira49c0772024-11-30 10:56:30 +01001650 i++;
glepnir80b66202024-11-27 21:53:53 +01001651 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001652
glepnirf400a0c2025-01-23 19:55:14 +01001653 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001654 {
1655 did_find_shown_match = TRUE;
1656
1657 // When the original text is the shown match don't set
1658 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001659 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001660 shown_match_ok = TRUE;
1661
1662 if (!shown_match_ok && shown_compl != NULL)
1663 {
1664 // The shown match isn't displayed, set it to the
1665 // previously displayed match.
1666 compl_shown_match = shown_compl;
1667 shown_match_ok = TRUE;
1668 }
1669 }
glepnira49c0772024-11-30 10:56:30 +01001670 compl = compl->cp_next;
1671 } while (compl != NULL && !is_first_match(compl));
1672
1673 if (compl_match_arraysize == 0)
1674 return -1;
1675
glepnirc0b7ca42025-02-13 20:27:44 +01001676 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1677 {
1678 compl_shown_match = shown_compl;
1679 shown_match_ok = TRUE;
1680 cur = 0;
1681 }
1682
glepnira49c0772024-11-30 10:56:30 +01001683 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1684 if (compl_match_array == NULL)
1685 return -1;
1686
1687 compl = match_head;
1688 i = 0;
1689 while (compl != NULL)
1690 {
glepnir6e199932024-12-14 21:13:27 +01001691 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1692 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001693 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1694 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1695 compl_match_array[i].pum_score = compl->cp_score;
Girish Palya19ef6b02025-05-28 20:28:21 +02001696 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001697 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1698 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001699 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1700 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001701 match_next = compl->cp_match_next;
1702 compl->cp_match_next = NULL;
1703 compl = match_next;
1704 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001705
zeertzjqd65aa1b2025-01-25 15:29:03 +01001706 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001707 {
1708 for (i = 0; i < compl_match_arraysize; i++)
1709 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001710 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001711 qsort(compl_match_array, (size_t)compl_match_arraysize,
1712 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001713 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001714 }
glepnira218cc62024-06-03 19:32:39 +02001715
Girish Palya19ef6b02025-05-28 20:28:21 +02001716 if (is_forward && fuzzy_sort && cpt_sources_array != NULL)
1717 trim_compl_match_array(); // Truncate by max_matches in 'cpt'
1718
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001719 if (!shown_match_ok) // no displayed match at all
1720 cur = -1;
1721
1722 return cur;
1723}
1724
1725/*
1726 * Show the popup menu for the list of matches.
1727 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1728 */
1729 void
1730ins_compl_show_pum(void)
1731{
1732 int i;
1733 int cur = -1;
1734 colnr_T col;
1735
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001736 if (!pum_wanted() || !pum_enough_matches())
1737 return;
1738
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001739 // Update the screen later, before drawing the popup menu over it.
1740 pum_call_update_screen();
1741
1742 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001743 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001744 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001745 else
1746 {
1747 // popup menu already exists, only need to find the current item.
1748 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001749 {
John Marriott5e6ea922024-11-23 14:01:57 +01001750 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001751 || compl_match_array[i].pum_text
1752 == compl_shown_match->cp_text[CPT_ABBR])
1753 {
1754 cur = i;
1755 break;
1756 }
glepnir19e1dd62025-05-08 22:50:38 +02001757 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001758 }
1759
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001760 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001761 {
1762#ifdef FEAT_EVAL
1763 if (compl_started && has_completechanged())
1764 trigger_complete_changed_event(cur);
1765#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001766 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001767 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001768
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001769 // In Replace mode when a $ is displayed at the end of the line only
1770 // part of the screen would be updated. We do need to redraw here.
1771 dollar_vcol = -1;
1772
1773 // Compute the screen column of the start of the completed text.
1774 // Use the cursor to get all wrapping and other settings right.
1775 col = curwin->w_cursor.col;
1776 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001777 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001778 pum_display(compl_match_array, compl_match_arraysize, cur);
1779 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001780
glepnircbb46b42024-02-03 18:11:13 +01001781 // After adding leader, set the current match to shown match.
1782 if (compl_started && compl_curr_match != compl_shown_match)
1783 compl_curr_match = compl_shown_match;
1784
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001785#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001786 if (has_completechanged())
1787 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001788#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001789}
1790
1791#define DICT_FIRST (1) // use just first element in "dict"
1792#define DICT_EXACT (2) // "dict" is the exact name of a file
1793
1794/*
glepnir40c1c332024-06-11 19:37:04 +02001795 * Get current completion leader
1796 */
1797 char_u *
1798ins_compl_leader(void)
1799{
John Marriott5e6ea922024-11-23 14:01:57 +01001800 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1801}
1802
1803/*
1804 * Get current completion leader length
1805 */
1806 size_t
1807ins_compl_leader_len(void)
1808{
1809 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001810}
1811
1812/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001813 * Add any identifiers that match the given pattern "pat" in the list of
1814 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001815 */
1816 static void
1817ins_compl_dictionaries(
1818 char_u *dict_start,
1819 char_u *pat,
1820 int flags, // DICT_FIRST and/or DICT_EXACT
1821 int thesaurus) // Thesaurus completion
1822{
1823 char_u *dict = dict_start;
1824 char_u *ptr;
1825 char_u *buf;
1826 regmatch_T regmatch;
1827 char_u **files;
1828 int count;
1829 int save_p_scs;
1830 int dir = compl_direction;
1831
1832 if (*dict == NUL)
1833 {
1834#ifdef FEAT_SPELL
1835 // When 'dictionary' is empty and spell checking is enabled use
1836 // "spell".
1837 if (!thesaurus && curwin->w_p_spell)
1838 dict = (char_u *)"spell";
1839 else
1840#endif
1841 return;
1842 }
1843
1844 buf = alloc(LSIZE);
1845 if (buf == NULL)
1846 return;
1847 regmatch.regprog = NULL; // so that we can goto theend
1848
1849 // If 'infercase' is set, don't use 'smartcase' here
1850 save_p_scs = p_scs;
1851 if (curbuf->b_p_inf)
1852 p_scs = FALSE;
1853
1854 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1855 // to only match at the start of a line. Otherwise just match the
1856 // pattern. Also need to double backslashes.
1857 if (ctrl_x_mode_line_or_eval())
1858 {
1859 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001860
1861 if (pat_esc == NULL)
1862 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001863 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001864 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001865 if (ptr == NULL)
1866 {
1867 vim_free(pat_esc);
1868 goto theend;
1869 }
1870 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1871 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1872 vim_free(pat_esc);
1873 vim_free(ptr);
1874 }
1875 else
1876 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001877 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001878 if (regmatch.regprog == NULL)
1879 goto theend;
1880 }
1881
1882 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1883 regmatch.rm_ic = ignorecase(pat);
1884 while (*dict != NUL && !got_int && !compl_interrupted)
1885 {
1886 // copy one dictionary file name into buf
1887 if (flags == DICT_EXACT)
1888 {
1889 count = 1;
1890 files = &dict;
1891 }
1892 else
1893 {
1894 // Expand wildcards in the dictionary name, but do not allow
1895 // backticks (for security, the 'dict' option may have been set in
1896 // a modeline).
1897 copy_option_part(&dict, buf, LSIZE, ",");
1898# ifdef FEAT_SPELL
1899 if (!thesaurus && STRCMP(buf, "spell") == 0)
1900 count = -1;
1901 else
1902# endif
1903 if (vim_strchr(buf, '`') != NULL
1904 || expand_wildcards(1, &buf, &count, &files,
1905 EW_FILE|EW_SILENT) != OK)
1906 count = 0;
1907 }
1908
1909# ifdef FEAT_SPELL
1910 if (count == -1)
1911 {
1912 // Complete from active spelling. Skip "\<" in the pattern, we
1913 // don't use it as a RE.
1914 if (pat[0] == '\\' && pat[1] == '<')
1915 ptr = pat + 2;
1916 else
1917 ptr = pat;
1918 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1919 }
1920 else
1921# endif
1922 if (count > 0) // avoid warning for using "files" uninit
1923 {
1924 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001925 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001926 if (flags != DICT_EXACT)
1927 FreeWild(count, files);
1928 }
1929 if (flags != 0)
1930 break;
1931 }
1932
1933theend:
1934 p_scs = save_p_scs;
1935 vim_regfree(regmatch.regprog);
1936 vim_free(buf);
1937}
1938
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001939/*
1940 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1941 * skipping the word at 'skip_word'. Returns OK on success.
1942 */
1943 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001944thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001945 char_u *fname,
1946 char_u **buf_arg,
1947 int dir,
1948 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001949{
1950 int status = OK;
1951 char_u *ptr;
1952 char_u *wstart;
1953
1954 // Add the other matches on the line
1955 ptr = *buf_arg;
1956 while (!got_int)
1957 {
1958 // Find start of the next word. Skip white
1959 // space and punctuation.
1960 ptr = find_word_start(ptr);
1961 if (*ptr == NUL || *ptr == NL)
1962 break;
1963 wstart = ptr;
1964
1965 // Find end of the word.
1966 if (has_mbyte)
1967 // Japanese words may have characters in
1968 // different classes, only separate words
1969 // with single-byte non-word characters.
1970 while (*ptr != NUL)
1971 {
1972 int l = (*mb_ptr2len)(ptr);
1973
1974 if (l < 2 && !vim_iswordc(*ptr))
1975 break;
1976 ptr += l;
1977 }
1978 else
1979 ptr = find_word_end(ptr);
1980
1981 // Add the word. Skip the regexp match.
1982 if (wstart != skip_word)
1983 {
1984 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001985 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001986 if (status == FAIL)
1987 break;
1988 }
1989 }
1990
1991 *buf_arg = ptr;
1992 return status;
1993}
1994
1995/*
1996 * Process "count" dictionary/thesaurus "files" and add the text matching
1997 * "regmatch".
1998 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001999 static void
2000ins_compl_files(
2001 int count,
2002 char_u **files,
2003 int thesaurus,
2004 int flags,
2005 regmatch_T *regmatch,
2006 char_u *buf,
2007 int *dir)
2008{
2009 char_u *ptr;
2010 int i;
2011 FILE *fp;
2012 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01002013 char_u *leader = NULL;
2014 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01002015 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01002016 int score = 0;
2017 int len = 0;
2018 char_u *line_end = NULL;
2019
2020 if (in_fuzzy_collect)
2021 {
2022 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02002023 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01002024 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002025
2026 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
2027 {
2028 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01002029 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002030 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01002031 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002032 vim_snprintf((char *)IObuff, IOSIZE,
2033 _("Scanning dictionary: %s"), (char *)files[i]);
2034 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2035 }
2036
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002037 if (fp == NULL)
2038 continue;
2039
2040 // Read dictionary file line by line.
2041 // Check each line for a match.
2042 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002043 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002044 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01002045 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002046 {
glepnirf31cfa22025-03-06 21:59:13 +01002047 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002048 {
glepnirf31cfa22025-03-06 21:59:13 +01002049 ptr = regmatch->startp[0];
2050 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
2051 : find_word_end(ptr);
2052 add_r = ins_compl_add_infercase(regmatch->startp[0],
2053 (int)(ptr - regmatch->startp[0]),
2054 p_ic, files[i], *dir, FALSE, 0);
2055 if (thesaurus)
2056 {
2057 // For a thesaurus, add all the words in the line
2058 ptr = buf;
2059 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
2060 regmatch->startp[0]);
2061 }
2062 if (add_r == OK)
2063 // if dir was BACKWARD then honor it just once
2064 *dir = FORWARD;
2065 else if (add_r == FAIL)
2066 break;
2067 // avoid expensive call to vim_regexec() when at end
2068 // of line
2069 if (*ptr == '\n' || got_int)
2070 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002071 }
glepnirf31cfa22025-03-06 21:59:13 +01002072 }
2073 else if (in_fuzzy_collect && leader_len > 0)
2074 {
2075 line_end = find_line_end(ptr);
2076 while (ptr < line_end)
2077 {
2078 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
2079 {
2080 char_u *end_ptr = ctrl_x_mode_line_or_eval()
2081 ? find_line_end(ptr) : find_word_end(ptr);
2082 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2083 p_ic, files[i], *dir, FALSE, score);
2084 if (add_r == FAIL)
2085 break;
2086 ptr = end_ptr; // start from next word
2087 if (compl_get_longest && ctrl_x_mode_normal()
2088 && compl_first_match->cp_next
2089 && score == compl_first_match->cp_next->cp_score)
2090 compl_num_bests++;
2091 }
glepnirf31cfa22025-03-06 21:59:13 +01002092 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002093 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002094 line_breakcheck();
2095 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002096 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002097 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098 }
2099}
2100
2101/*
2102 * Find the start of the next word.
2103 * Returns a pointer to the first char of the word. Also stops at a NUL.
2104 */
2105 char_u *
2106find_word_start(char_u *ptr)
2107{
2108 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002109 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002110 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2111 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002112 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002113 else
glepnir19e1dd62025-05-08 22:50:38 +02002114 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002115 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2116 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002117 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002118 return ptr;
2119}
2120
2121/*
2122 * Find the end of the word. Assumes it starts inside a word.
2123 * Returns a pointer to just after the word.
2124 */
2125 char_u *
2126find_word_end(char_u *ptr)
2127{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002128 if (has_mbyte)
2129 {
glepnir19e1dd62025-05-08 22:50:38 +02002130 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002131 if (start_class > 1)
2132 while (*ptr != NUL)
2133 {
2134 ptr += (*mb_ptr2len)(ptr);
2135 if (mb_get_class(ptr) != start_class)
2136 break;
2137 }
2138 }
2139 else
2140 while (vim_iswordc(*ptr))
2141 ++ptr;
2142 return ptr;
2143}
2144
2145/*
2146 * Find the end of the line, omitting CR and NL at the end.
2147 * Returns a pointer to just after the line.
2148 */
glepnirdd42b052025-03-08 16:52:55 +01002149 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002150find_line_end(char_u *ptr)
2151{
glepnir19e1dd62025-05-08 22:50:38 +02002152 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002153 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2154 --s;
2155 return s;
2156}
2157
2158/*
Girish Palyacbe53192025-04-14 22:13:15 +02002159 * Free a completion item in the list
2160 */
2161 static void
2162ins_compl_item_free(compl_T *match)
2163{
Girish Palyacbe53192025-04-14 22:13:15 +02002164 VIM_CLEAR_STRING(match->cp_str);
2165 // several entries may use the same fname, free it just once.
2166 if (match->cp_flags & CP_FREE_FNAME)
2167 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002168 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002169 vim_free(match->cp_text[i]);
2170#ifdef FEAT_EVAL
2171 clear_tv(&match->cp_user_data);
2172#endif
2173 vim_free(match);
2174}
2175
2176/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002177 * Free the list of completions
2178 */
2179 static void
2180ins_compl_free(void)
2181{
2182 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002183
John Marriott5e6ea922024-11-23 14:01:57 +01002184 VIM_CLEAR_STRING(compl_pattern);
2185 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002186
2187 if (compl_first_match == NULL)
2188 return;
2189
2190 ins_compl_del_pum();
2191 pum_clear();
2192
2193 compl_curr_match = compl_first_match;
2194 do
2195 {
2196 match = compl_curr_match;
2197 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002198 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002199 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002200 compl_first_match = compl_curr_match = NULL;
2201 compl_shown_match = NULL;
2202 compl_old_match = NULL;
2203}
2204
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002205/*
2206 * Reset/clear the completion state.
2207 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002208 void
2209ins_compl_clear(void)
2210{
2211 compl_cont_status = 0;
2212 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002213 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002214 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002215 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002216 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002217 compl_curr_win = NULL;
2218 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002219 VIM_CLEAR_STRING(compl_pattern);
2220 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002221 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002222 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002223 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002224 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002225#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002226 // clear v:completed_item
2227 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002228#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002229}
2230
2231/*
2232 * Return TRUE when Insert completion is active.
2233 */
2234 int
2235ins_compl_active(void)
2236{
2237 return compl_started;
2238}
2239
2240/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002241 * Return True when wp is the actual completion window
2242 */
2243 int
glepnircf7f0122025-04-15 19:02:00 +02002244ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002245{
glepnircf7f0122025-04-15 19:02:00 +02002246 return ins_compl_active() && wp == compl_curr_win
2247 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002248}
2249
2250/*
Girish Palyacbe53192025-04-14 22:13:15 +02002251 * Selected one of the matches. When FALSE, the match was either edited or
2252 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002253 */
2254 int
2255ins_compl_used_match(void)
2256{
2257 return compl_used_match;
2258}
2259
2260/*
2261 * Initialize get longest common string.
2262 */
2263 void
2264ins_compl_init_get_longest(void)
2265{
2266 compl_get_longest = FALSE;
2267}
2268
2269/*
2270 * Returns TRUE when insert completion is interrupted.
2271 */
2272 int
2273ins_compl_interrupted(void)
2274{
2275 return compl_interrupted;
2276}
2277
2278/*
2279 * Returns TRUE if the <Enter> key selects a match in the completion popup
2280 * menu.
2281 */
2282 int
2283ins_compl_enter_selects(void)
2284{
2285 return compl_enter_selects;
2286}
2287
2288/*
2289 * Return the column where the text starts that is being completed
2290 */
2291 colnr_T
2292ins_compl_col(void)
2293{
2294 return compl_col;
2295}
2296
2297/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002298 * Return the length in bytes of the text being completed
2299 */
2300 int
2301ins_compl_len(void)
2302{
2303 return compl_length;
2304}
2305
2306/*
glepnir94a045e2025-03-01 16:12:23 +01002307 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2308 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002309 */
2310 static int
2311ins_compl_has_preinsert(void)
2312{
glepnira2c55592025-02-28 17:43:42 +01002313 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002314 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2315 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002316}
2317
2318/*
2319 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2320 * the `compl_ins_end_col` range.
2321 */
2322 int
2323ins_compl_preinsert_effect(void)
2324{
2325 if (!ins_compl_has_preinsert())
2326 return FALSE;
2327
2328 return curwin->w_cursor.col < compl_ins_end_col;
2329}
2330
2331/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002332 * Delete one character before the cursor and show the subset of the matches
2333 * that match the word that is now before the cursor.
2334 * Returns the character to be used, NUL if the work is done and another char
2335 * to be got from the user.
2336 */
2337 int
2338ins_compl_bs(void)
2339{
2340 char_u *line;
2341 char_u *p;
2342
glepniredd4ac32025-01-29 18:53:51 +01002343 if (ins_compl_preinsert_effect())
2344 ins_compl_delete();
2345
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002346 line = ml_get_curline();
2347 p = line + curwin->w_cursor.col;
2348 MB_PTR_BACK(line, p);
2349
2350 // Stop completion when the whole word was deleted. For Omni completion
2351 // allow the word to be deleted, we won't match everything.
2352 // Respect the 'backspace' option.
2353 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002354 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2355 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002356 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2357 - compl_length < 0))
2358 return K_BS;
2359
2360 // Deleted more than what was used to find matches or didn't finish
2361 // finding all matches: need to look for matches all over again.
2362 if (curwin->w_cursor.col <= compl_col + compl_length
2363 || ins_compl_need_restart())
2364 ins_compl_restart();
2365
John Marriott5e6ea922024-11-23 14:01:57 +01002366 VIM_CLEAR_STRING(compl_leader);
2367 compl_leader.length = (size_t)((p - line) - compl_col);
2368 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2369 if (compl_leader.string == NULL)
2370 {
2371 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002372 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002373 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002374
2375 ins_compl_new_leader();
2376 if (compl_shown_match != NULL)
2377 // Make sure current match is not a hidden item.
2378 compl_curr_match = compl_shown_match;
2379 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002380}
2381
2382/*
2383 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2384 * be called.
2385 */
2386 static int
2387ins_compl_need_restart(void)
2388{
2389 // Return TRUE if we didn't complete finding matches or when the
2390 // 'completefunc' returned "always" in the "refresh" dictionary item.
2391 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002392 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002393 && compl_opt_refresh_always);
2394}
2395
2396/*
2397 * Called after changing "compl_leader".
2398 * Show the popup menu with a different set of matches.
2399 * May also search for matches again if the previous search was interrupted.
2400 */
2401 static void
2402ins_compl_new_leader(void)
2403{
2404 ins_compl_del_pum();
2405 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002406 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002407 compl_used_match = FALSE;
2408
2409 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002410 {
John Marriott5e6ea922024-11-23 14:01:57 +01002411 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002412 if (is_cpt_func_refresh_always())
2413 cpt_compl_refresh();
2414 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002415 else
2416 {
2417#ifdef FEAT_SPELL
2418 spell_bad_len = 0; // need to redetect bad word
2419#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002420 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002421 // the popup menu display the changed text before the cursor. Set
2422 // "compl_restarting" to avoid that the first match is inserted.
2423 pum_call_update_screen();
2424#ifdef FEAT_GUI
2425 if (gui.in_use)
2426 {
2427 // Show the cursor after the match, not after the redrawn text.
2428 setcursor();
2429 out_flush_cursor(FALSE, FALSE);
2430 }
2431#endif
2432 compl_restarting = TRUE;
2433 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2434 compl_cont_status = 0;
2435 compl_restarting = FALSE;
2436 }
2437
glepnir44180412025-02-20 22:09:48 +01002438 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002439
2440 // Show the popup menu with a different set of matches.
2441 ins_compl_show_pum();
2442
2443 // Don't let Enter select the original text when there is no popup menu.
2444 if (compl_match_array == NULL)
2445 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002446 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2447 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002448}
2449
2450/*
2451 * Return the length of the completion, from the completion start column to
2452 * the cursor column. Making sure it never goes below zero.
2453 */
2454 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002455get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002456{
2457 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002458 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002459}
2460
2461/*
2462 * Append one character to the match leader. May reduce the number of
2463 * matches.
2464 */
2465 void
2466ins_compl_addleader(int c)
2467{
glepnir19e1dd62025-05-08 22:50:38 +02002468 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002469
glepniredd4ac32025-01-29 18:53:51 +01002470 if (ins_compl_preinsert_effect())
2471 ins_compl_delete();
2472
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002473 if (stop_arrow() == FAIL)
2474 return;
2475 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2476 {
2477 char_u buf[MB_MAXBYTES + 1];
2478
2479 (*mb_char2bytes)(c, buf);
2480 buf[cc] = NUL;
2481 ins_char_bytes(buf, cc);
2482 if (compl_opt_refresh_always)
2483 AppendToRedobuff(buf);
2484 }
2485 else
2486 {
2487 ins_char(c);
2488 if (compl_opt_refresh_always)
2489 AppendCharToRedobuff(c);
2490 }
2491
2492 // If we didn't complete finding matches we must search again.
2493 if (ins_compl_need_restart())
2494 ins_compl_restart();
2495
2496 // When 'always' is set, don't reset compl_leader. While completing,
2497 // cursor doesn't point original position, changing compl_leader would
2498 // break redo.
2499 if (!compl_opt_refresh_always)
2500 {
John Marriott5e6ea922024-11-23 14:01:57 +01002501 VIM_CLEAR_STRING(compl_leader);
2502 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2503 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2504 compl_leader.length);
2505 if (compl_leader.string == NULL)
2506 {
2507 compl_leader.length = 0;
2508 return;
2509 }
2510
2511 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002512 }
2513}
2514
2515/*
2516 * Setup for finding completions again without leaving CTRL-X mode. Used when
2517 * BS or a key was typed while still searching for matches.
2518 */
2519 static void
2520ins_compl_restart(void)
2521{
2522 ins_compl_free();
2523 compl_started = FALSE;
2524 compl_matches = 0;
2525 compl_cont_status = 0;
2526 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002527 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002528}
2529
2530/*
2531 * Set the first match, the original text.
2532 */
2533 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002534ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002535{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002536 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002537 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2538 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002539 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002540 {
John Marriott5e6ea922024-11-23 14:01:57 +01002541 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002542 if (p != NULL)
2543 {
John Marriott5e6ea922024-11-23 14:01:57 +01002544 VIM_CLEAR_STRING(compl_first_match->cp_str);
2545 compl_first_match->cp_str.string = p;
2546 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002547 }
2548 }
2549 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002550 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002551 {
John Marriott5e6ea922024-11-23 14:01:57 +01002552 char_u *p = vim_strnsave(str, len);
2553 if (p != NULL)
2554 {
2555 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2556 compl_first_match->cp_prev->cp_str.string = p;
2557 compl_first_match->cp_prev->cp_str.length = len;
2558 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002559 }
2560}
2561
2562/*
2563 * Append one character to the match leader. May reduce the number of
2564 * matches.
2565 */
2566 void
2567ins_compl_addfrommatch(void)
2568{
2569 char_u *p;
2570 int len = (int)curwin->w_cursor.col - (int)compl_col;
2571 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002572
John Marriott5e6ea922024-11-23 14:01:57 +01002573 p = compl_shown_match->cp_str.string;
2574 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002575 {
John Marriott5e6ea922024-11-23 14:01:57 +01002576 size_t plen;
2577 compl_T *cp;
2578
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002579 // When still at the original match use the first entry that matches
2580 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002581 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002582 return;
2583
2584 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002585 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002586 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002587 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002588 {
John Marriott5e6ea922024-11-23 14:01:57 +01002589 if (compl_leader.string == NULL
2590 || ins_compl_equal(cp, compl_leader.string,
2591 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002592 {
John Marriott5e6ea922024-11-23 14:01:57 +01002593 p = cp->cp_str.string;
2594 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002595 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002596 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002597 }
John Marriott5e6ea922024-11-23 14:01:57 +01002598 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002599 return;
2600 }
2601 p += len;
2602 c = PTR2CHAR(p);
2603 ins_compl_addleader(c);
2604}
2605
2606/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002607 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002608 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2609 * compl_cont_mode and compl_cont_status.
2610 * Returns TRUE when the character is not to be inserted.
2611 */
2612 static int
2613set_ctrl_x_mode(int c)
2614{
glepnir05460682025-05-26 18:23:27 +02002615 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002616
2617 switch (c)
2618 {
2619 case Ctrl_E:
2620 case Ctrl_Y:
2621 // scroll the window one line up or down
2622 ctrl_x_mode = CTRL_X_SCROLL;
2623 if (!(State & REPLACE_FLAG))
2624 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2625 else
2626 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2627 edit_submode_pre = NULL;
2628 showmode();
2629 break;
2630 case Ctrl_L:
2631 // complete whole line
2632 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2633 break;
2634 case Ctrl_F:
2635 // complete filenames
2636 ctrl_x_mode = CTRL_X_FILES;
2637 break;
2638 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002639 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002640 ctrl_x_mode = CTRL_X_DICTIONARY;
2641 break;
2642 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002643 // When CTRL-R is followed by '=', don't trigger register completion
2644 // This allows expressions like <C-R>=func()<CR> to work normally
2645 if (vpeekc() == '=')
2646 break;
2647 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002648 break;
2649 case Ctrl_T:
2650 // complete words from a thesaurus
2651 ctrl_x_mode = CTRL_X_THESAURUS;
2652 break;
2653#ifdef FEAT_COMPL_FUNC
2654 case Ctrl_U:
2655 // user defined completion
2656 ctrl_x_mode = CTRL_X_FUNCTION;
2657 break;
2658 case Ctrl_O:
2659 // omni completion
2660 ctrl_x_mode = CTRL_X_OMNI;
2661 break;
2662#endif
2663 case 's':
2664 case Ctrl_S:
2665 // complete spelling suggestions
2666 ctrl_x_mode = CTRL_X_SPELL;
2667#ifdef FEAT_SPELL
2668 ++emsg_off; // Avoid getting the E756 error twice.
2669 spell_back_to_badword();
2670 --emsg_off;
2671#endif
2672 break;
2673 case Ctrl_RSB:
2674 // complete tag names
2675 ctrl_x_mode = CTRL_X_TAGS;
2676 break;
2677#ifdef FEAT_FIND_ID
2678 case Ctrl_I:
2679 case K_S_TAB:
2680 // complete keywords from included files
2681 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2682 break;
2683 case Ctrl_D:
2684 // complete definitions from included files
2685 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2686 break;
2687#endif
2688 case Ctrl_V:
2689 case Ctrl_Q:
2690 // complete vim commands
2691 ctrl_x_mode = CTRL_X_CMDLINE;
2692 break;
2693 case Ctrl_Z:
2694 // stop completion
2695 ctrl_x_mode = CTRL_X_NORMAL;
2696 edit_submode = NULL;
2697 showmode();
2698 retval = TRUE;
2699 break;
2700 case Ctrl_P:
2701 case Ctrl_N:
2702 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2703 // just started ^X mode, or there were enough ^X's to cancel
2704 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2705 // do normal expansion when interrupting a different mode (say
2706 // ^X^F^X^P or ^P^X^X^P, see below)
2707 // nothing changes if interrupting mode 0, (eg, the flag
2708 // doesn't change when going to ADDING mode -- Acevedo
2709 if (!(compl_cont_status & CONT_INTRPT))
2710 compl_cont_status |= CONT_LOCAL;
2711 else if (compl_cont_mode != 0)
2712 compl_cont_status &= ~CONT_LOCAL;
2713 // FALLTHROUGH
2714 default:
2715 // If we have typed at least 2 ^X's... for modes != 0, we set
2716 // compl_cont_status = 0 (eg, as if we had just started ^X
2717 // mode).
2718 // For mode 0, we set "compl_cont_mode" to an impossible
2719 // value, in both cases ^X^X can be used to restart the same
2720 // mode (avoiding ADDING mode).
2721 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2722 // 'complete' and local ^P expansions respectively.
2723 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2724 // mode -- Acevedo
2725 if (c == Ctrl_X)
2726 {
2727 if (compl_cont_mode != 0)
2728 compl_cont_status = 0;
2729 else
2730 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2731 }
2732 ctrl_x_mode = CTRL_X_NORMAL;
2733 edit_submode = NULL;
2734 showmode();
2735 break;
2736 }
2737
2738 return retval;
2739}
2740
2741/*
glepnir1c5a1202024-12-04 20:27:34 +01002742 * Trigger CompleteDone event and adds relevant information to v:event
2743 */
2744 static void
2745trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2746{
2747#if defined(FEAT_EVAL)
2748 save_v_event_T save_v_event;
2749 dict_T *v_event = get_v_event(&save_v_event);
2750 char_u *mode_str = NULL;
2751
2752 mode = mode & ~CTRL_X_WANT_IDENT;
2753 if (ctrl_x_mode_names[mode])
2754 mode_str = (char_u *)ctrl_x_mode_names[mode];
2755
2756 (void)dict_add_string(v_event, "complete_word",
2757 word == NULL ? (char_u *)"" : word);
2758 (void)dict_add_string(v_event, "complete_type",
2759 mode_str != NULL ? mode_str : (char_u *)"");
2760
2761 dict_set_items_ro(v_event);
2762#endif
2763 ins_apply_autocmds(EVENT_COMPLETEDONE);
2764
2765#if defined(FEAT_EVAL)
2766 restore_v_event(v_event, &save_v_event);
2767#endif
2768}
2769
2770/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002771 * Stop insert completion mode
2772 */
2773 static int
2774ins_compl_stop(int c, int prev_mode, int retval)
2775{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002776 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002777 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002778
glepnir84a75032025-03-15 09:59:22 +01002779 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002780 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002781 ins_compl_delete();
2782
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002783 // Get here when we have finished typing a sequence of ^N and
2784 // ^P or other completion characters in CTRL-X mode. Free up
2785 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002786 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002787 {
glepnir40891ba2025-02-10 22:18:00 +01002788 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002789
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002790 // If any of the original typed text has been changed, eg when
2791 // ignorecase is set, we must add back-spaces to the redo
2792 // buffer. We add as few as necessary to delete just the part
2793 // of the original text that has changed.
2794 // When using the longest match, edited the match or used
2795 // CTRL-E then don't use the current match.
2796 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002797 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002798 ins_compl_fixRedoBufForLeader(ptr);
2799 }
2800
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002801 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002802
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002803 // When completing whole lines: fix indent for 'cindent'.
2804 // Otherwise, break line if it's too long.
2805 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2806 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002807 // re-indent the current line
2808 if (want_cindent)
2809 {
2810 do_c_expr_indent();
2811 want_cindent = FALSE; // don't do it again
2812 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002813 }
2814 else
2815 {
2816 int prev_col = curwin->w_cursor.col;
2817
2818 // put the cursor on the last char, for 'tw' formatting
2819 if (prev_col > 0)
2820 dec_cursor();
2821 // only format when something was inserted
2822 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2823 insertchar(NUL, 0, -1);
2824 if (prev_col > 0
2825 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2826 inc_cursor();
2827 }
2828
2829 // If the popup menu is displayed pressing CTRL-Y means accepting
2830 // the selection without inserting anything. When
2831 // compl_enter_selects is set the Enter key does the same.
2832 if ((c == Ctrl_Y || (compl_enter_selects
2833 && (c == CAR || c == K_KENTER || c == NL)))
2834 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002835 {
2836 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002837 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002838 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002839
2840 // CTRL-E means completion is Ended, go back to the typed text.
2841 // but only do this, if the Popup is still visible
2842 if (c == Ctrl_E)
2843 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002844 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002845 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002846
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002847 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002848 if (compl_leader.string != NULL)
2849 {
2850 p = compl_leader.string;
2851 plen = compl_leader.length;
2852 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002853 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002854 {
2855 p = compl_orig_text.string;
2856 plen = compl_orig_text.length;
2857 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002858 if (p != NULL)
2859 {
2860 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002861
John Marriott5e6ea922024-11-23 14:01:57 +01002862 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002863 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002864 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002865 retval = TRUE;
2866 }
2867
2868 auto_format(FALSE, TRUE);
2869
2870 // Trigger the CompleteDonePre event to give scripts a chance to
2871 // act upon the completion before clearing the info, and restore
2872 // ctrl_x_mode, so that complete_info() can be used.
2873 ctrl_x_mode = prev_mode;
2874 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2875
2876 ins_compl_free();
2877 compl_started = FALSE;
2878 compl_matches = 0;
2879 if (!shortmess(SHM_COMPLETIONMENU))
2880 msg_clr_cmdline(); // necessary for "noshowmode"
2881 ctrl_x_mode = CTRL_X_NORMAL;
2882 compl_enter_selects = FALSE;
2883 if (edit_submode != NULL)
2884 {
2885 edit_submode = NULL;
2886 showmode();
2887 }
2888
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002889 if (c == Ctrl_C && cmdwin_type != 0)
2890 // Avoid the popup menu remains displayed when leaving the
2891 // command line window.
2892 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002893 // Indent now if a key was typed that is in 'cinkeys'.
2894 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2895 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002896 // Trigger the CompleteDone event to give scripts a chance to act
2897 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002898 trigger_complete_done_event(prev_mode, word);
2899 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002900
2901 return retval;
2902}
2903
2904/*
glepnircf7f0122025-04-15 19:02:00 +02002905 * Cancel completion.
2906 */
2907 int
2908ins_compl_cancel(void)
2909{
2910 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2911}
2912
2913/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002914 * Prepare for Insert mode completion, or stop it.
2915 * Called just after typing a character in Insert mode.
2916 * Returns TRUE when the character is not to be inserted;
2917 */
2918 int
2919ins_compl_prep(int c)
2920{
glepnir19e1dd62025-05-08 22:50:38 +02002921 int retval = FALSE;
2922 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002923
2924 // Forget any previous 'special' messages if this is actually
2925 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2926 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2927 edit_submode_extra = NULL;
2928
zeertzjq440d4cb2023-03-02 17:51:32 +00002929 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002930 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002931 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002932 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002933 return retval;
2934
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002935#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002936 // Ignore mouse events in a popup window
2937 if (is_mouse_key(c))
2938 {
2939 // Ignore drag and release events, the position does not need to be in
2940 // the popup and it may have just closed.
2941 if (c == K_LEFTRELEASE
2942 || c == K_LEFTRELEASE_NM
2943 || c == K_MIDDLERELEASE
2944 || c == K_RIGHTRELEASE
2945 || c == K_X1RELEASE
2946 || c == K_X2RELEASE
2947 || c == K_LEFTDRAG
2948 || c == K_MIDDLEDRAG
2949 || c == K_RIGHTDRAG
2950 || c == K_X1DRAG
2951 || c == K_X2DRAG)
2952 return retval;
2953 if (popup_visible)
2954 {
2955 int row = mouse_row;
2956 int col = mouse_col;
2957 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2958
2959 if (wp != NULL && WIN_IS_POPUP(wp))
2960 return retval;
2961 }
2962 }
2963#endif
2964
zeertzjqdca29d92021-08-31 19:12:51 +02002965 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2966 {
2967 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2968 || !vim_is_ctrl_x_key(c))
2969 {
2970 // Not starting another completion mode.
2971 ctrl_x_mode = CTRL_X_CMDLINE;
2972
2973 // CTRL-X CTRL-Z should stop completion without inserting anything
2974 if (c == Ctrl_Z)
2975 retval = TRUE;
2976 }
2977 else
2978 {
2979 ctrl_x_mode = CTRL_X_CMDLINE;
2980
2981 // Other CTRL-X keys first stop completion, then start another
2982 // completion mode.
2983 ins_compl_prep(' ');
2984 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2985 }
2986 }
2987
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002988 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002989 if (ctrl_x_mode_not_defined_yet()
2990 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002991 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002992 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002993 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002994 }
2995
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002996 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002997 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2998 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002999 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003000 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003001 {
3002 // We're already in CTRL-X mode, do we stay in it?
3003 if (!vim_is_ctrl_x_key(c))
3004 {
glepnir40891ba2025-02-10 22:18:00 +01003005 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003006 edit_submode = NULL;
3007 }
3008 showmode();
3009 }
3010
3011 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3012 {
3013 // Show error message from attempted keyword completion (probably
3014 // 'Pattern not found') until another key is hit, then go back to
3015 // showing what mode we are in.
3016 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003017 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003018 && c != Ctrl_R && !ins_compl_pum_key(c))
3019 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003020 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003021 }
3022 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
3023 // Trigger the CompleteDone event to give scripts a chance to act
3024 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01003025 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003026
LemonBoy2bf52dd2022-04-09 18:17:34 +01003027 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003028
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003029 // reset continue_* if we left expansion-mode, if we stay they'll be
3030 // (re)set properly in ins_complete()
3031 if (!vim_is_ctrl_x_key(c))
3032 {
3033 compl_cont_status = 0;
3034 compl_cont_mode = 0;
3035 }
3036
3037 return retval;
3038}
3039
3040/*
3041 * Fix the redo buffer for the completion leader replacing some of the typed
3042 * text. This inserts backspaces and appends the changed text.
3043 * "ptr" is the known leader text or NUL.
3044 */
3045 static void
3046ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
3047{
John Marriott5e6ea922024-11-23 14:01:57 +01003048 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003049 char_u *p;
3050 char_u *ptr = ptr_arg;
3051
3052 if (ptr == NULL)
3053 {
John Marriott5e6ea922024-11-23 14:01:57 +01003054 if (compl_leader.string != NULL)
3055 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003056 else
3057 return; // nothing to do
3058 }
John Marriott5e6ea922024-11-23 14:01:57 +01003059 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003060 {
John Marriott5e6ea922024-11-23 14:01:57 +01003061 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01003062 // Find length of common prefix between original text and new completion
3063 while (p[len] != NUL && p[len] == ptr[len])
3064 len++;
3065 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003066 if (len > 0)
3067 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01003068 // Add backspace characters for each remaining character in
3069 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003070 for (p += len; *p != NUL; MB_PTR_ADV(p))
3071 AppendCharToRedobuff(K_BS);
3072 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003073 if (ptr != NULL)
3074 AppendToRedobuffLit(ptr + len, -1);
3075}
3076
3077/*
3078 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3079 * (depending on flag) starting from buf and looking for a non-scanned
3080 * buffer (other than curbuf). curbuf is special, if it is called with
3081 * buf=curbuf then it has to be the first call for a given flag/expansion.
3082 *
3083 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3084 */
3085 static buf_T *
3086ins_compl_next_buf(buf_T *buf, int flag)
3087{
glepnir19e1dd62025-05-08 22:50:38 +02003088 static win_T *wp = NULL;
3089 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003090
3091 if (flag == 'w') // just windows
3092 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003093 if (buf == curbuf || !win_valid(wp))
3094 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003095 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003096
3097 while (TRUE)
3098 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003099 // Move to next window (wrap to first window if at the end)
3100 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3101 // Break if we're back at start or found an unscanned buffer
3102 if (wp == curwin || !wp->w_buffer->b_scanned)
3103 break;
glepnir40891ba2025-02-10 22:18:00 +01003104 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003105 buf = wp->w_buffer;
3106 }
3107 else
glepnir40891ba2025-02-10 22:18:00 +01003108 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003109 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3110 // (unlisted buffers)
3111 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003112 while (TRUE)
3113 {
3114 // Move to next buffer (wrap to first buffer if at the end)
3115 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3116 // Break if we're back at start buffer
3117 if (buf == curbuf)
3118 break;
3119
3120 // Check buffer conditions based on flag
3121 if (flag == 'U')
3122 skip_buffer = buf->b_p_bl;
3123 else
3124 skip_buffer = !buf->b_p_bl ||
3125 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3126
3127 // Break if we found a buffer that matches our criteria
3128 if (!skip_buffer && !buf->b_scanned)
3129 break;
3130 }
3131 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003132 return buf;
3133}
3134
3135#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003136
3137# ifdef FEAT_EVAL
3138static callback_T cfu_cb; // 'completefunc' callback function
3139static callback_T ofu_cb; // 'omnifunc' callback function
3140static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3141# endif
3142
3143/*
3144 * Copy a global callback function to a buffer local callback.
3145 */
3146 static void
3147copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3148{
3149 free_callback(bufcb);
3150 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3151 copy_callback(bufcb, globcb);
3152}
3153
3154/*
3155 * Parse the 'completefunc' option value and set the callback function.
3156 * Invoked when the 'completefunc' option is set. The option value can be a
3157 * name of a function (string), or function(<name>) or funcref(<name>) or a
3158 * lambda expression.
3159 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003160 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003161did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003162{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003163 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3164 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003165
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003166 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003167
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003168 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003169}
3170
3171/*
3172 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003173 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003174 */
3175 void
3176set_buflocal_cfu_callback(buf_T *buf UNUSED)
3177{
3178# ifdef FEAT_EVAL
3179 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3180# endif
3181}
3182
3183/*
3184 * Parse the 'omnifunc' option value and set the callback function.
3185 * Invoked when the 'omnifunc' option is set. The option value can be a
3186 * name of a function (string), or function(<name>) or funcref(<name>) or a
3187 * lambda expression.
3188 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003189 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003190did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003191{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003192 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3193 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003194
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003195 set_buflocal_ofu_callback(curbuf);
3196 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003197}
3198
3199/*
3200 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003201 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003202 */
3203 void
3204set_buflocal_ofu_callback(buf_T *buf UNUSED)
3205{
3206# ifdef FEAT_EVAL
3207 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3208# endif
3209}
3210
3211/*
3212 * Parse the 'thesaurusfunc' option value and set the callback function.
3213 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3214 * name of a function (string), or function(<name>) or funcref(<name>) or a
3215 * lambda expression.
3216 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003217 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003218did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003219{
3220 int retval;
3221
zeertzjq6eda2692024-11-03 09:23:33 +01003222 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003223 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003224 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3225 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003226 else
3227 {
3228 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003229 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003230 // when using :set, free the local callback
3231 if (!(args->os_flags & OPT_GLOBAL))
3232 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003233 }
3234
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003235 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003236}
3237
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003238/*
3239 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003240 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003241 */
3242 int
3243set_ref_in_insexpand_funcs(int copyID)
3244{
glepnir19e1dd62025-05-08 22:50:38 +02003245 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003246 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3247 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3248
3249 return abort;
3250}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003251
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003252/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003253 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003254 */
3255 static char_u *
3256get_complete_funcname(int type)
3257{
3258 switch (type)
3259 {
3260 case CTRL_X_FUNCTION:
3261 return curbuf->b_p_cfu;
3262 case CTRL_X_OMNI:
3263 return curbuf->b_p_ofu;
3264 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003265 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003266 default:
3267 return (char_u *)"";
3268 }
3269}
3270
3271/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003272 * Get the callback to use for insert mode completion.
3273 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003274 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003275get_insert_callback(int type)
3276{
3277 if (type == CTRL_X_FUNCTION)
3278 return &curbuf->b_cfu_cb;
3279 if (type == CTRL_X_OMNI)
3280 return &curbuf->b_ofu_cb;
3281 // CTRL_X_THESAURUS
3282 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3283}
3284
3285/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003286 * Execute user defined complete function 'completefunc', 'omnifunc' or
3287 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003288 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3289 * Callback function "cb" is set if triggered by a function in the 'cpt'
3290 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003291 */
3292 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003293expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003294{
3295 list_T *matchlist = NULL;
3296 dict_T *matchdict = NULL;
3297 typval_T args[3];
3298 char_u *funcname;
3299 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003300 typval_T rettv;
3301 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003302 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003303 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003304
Girish Palyacbe53192025-04-14 22:13:15 +02003305 if (!is_cpt_function)
3306 {
3307 funcname = get_complete_funcname(type);
3308 if (*funcname == NUL)
3309 return;
3310 cb = get_insert_callback(type);
3311 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003312
3313 // Call 'completefunc' to obtain the list of matches.
3314 args[0].v_type = VAR_NUMBER;
3315 args[0].vval.v_number = 0;
3316 args[1].v_type = VAR_STRING;
3317 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3318 args[2].v_type = VAR_UNKNOWN;
3319
3320 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003321 // Lock the text to avoid weird things from happening. Also disallow
3322 // switching to another window, it should not be needed and may end up in
3323 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003324 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003325
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003326 retval = call_callback(cb, 0, &rettv, 2, args);
3327
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003328 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003329 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003330 {
3331 switch (rettv.v_type)
3332 {
3333 case VAR_LIST:
3334 matchlist = rettv.vval.v_list;
3335 break;
3336 case VAR_DICT:
3337 matchdict = rettv.vval.v_dict;
3338 break;
3339 case VAR_SPECIAL:
3340 if (rettv.vval.v_number == VVAL_NONE)
3341 compl_opt_suppress_empty = TRUE;
3342 // FALLTHROUGH
3343 default:
3344 // TODO: Give error message?
3345 clear_tv(&rettv);
3346 break;
3347 }
3348 }
zeertzjqcfe45652022-05-27 17:26:55 +01003349 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003350
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003351 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003352 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003353 validate_cursor();
3354 if (!EQUAL_POS(curwin->w_cursor, pos))
3355 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003356 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003357 goto theend;
3358 }
3359
3360 if (matchlist != NULL)
3361 ins_compl_add_list(matchlist);
3362 else if (matchdict != NULL)
3363 ins_compl_add_dict(matchdict);
3364
3365theend:
3366 // Restore State, it might have been changed.
3367 State = save_State;
3368
3369 if (matchdict != NULL)
3370 dict_unref(matchdict);
3371 if (matchlist != NULL)
3372 list_unref(matchlist);
3373}
3374#endif // FEAT_COMPL_FUNC
3375
3376#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003377
3378 static inline int
3379get_user_highlight_attr(char_u *hlname)
3380{
3381 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003382 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003383 return -1;
3384}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003385/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003386 * Add a match to the list of matches from a typeval_T.
3387 * If the given string is already in the list of completions, then return
3388 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3389 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003390 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003391 */
3392 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003393ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003394{
3395 char_u *word;
3396 int dup = FALSE;
3397 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003398 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003399 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003400 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003401 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003402 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003403 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003404 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003405
Bram Moolenaar08928322020-01-04 14:32:48 +01003406 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003407 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3408 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003409 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3410 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3411 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3412 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3413 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003414
glepnir0fe17f82024-10-08 22:26:44 +02003415 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003416 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003417
3418 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003419 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003420
Bram Moolenaard61efa52022-07-23 09:52:04 +01003421 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3422 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3423 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003424 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003425 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3426 dup = dict_get_number(tv->vval.v_dict, "dup");
3427 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3428 empty = dict_get_number(tv->vval.v_dict, "empty");
3429 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3430 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003431 flags |= CP_EQUAL;
3432 }
3433 else
3434 {
3435 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003436 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003437 }
3438 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003439 {
3440 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003441 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003442 }
glepnir508e7852024-07-25 21:39:08 +02003443 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003444 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003445 if (status != OK)
3446 clear_tv(&user_data);
3447 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003448}
3449
3450/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003451 * Add completions from a list.
3452 */
3453 static void
3454ins_compl_add_list(list_T *list)
3455{
3456 listitem_T *li;
3457 int dir = compl_direction;
3458
3459 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003460 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003461 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003462 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003463 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003464 // if dir was BACKWARD then honor it just once
3465 dir = FORWARD;
3466 else if (did_emsg)
3467 break;
3468 }
3469}
3470
3471/*
3472 * Add completions from a dict.
3473 */
3474 static void
3475ins_compl_add_dict(dict_T *dict)
3476{
3477 dictitem_T *di_refresh;
3478 dictitem_T *di_words;
3479
3480 // Check for optional "refresh" item.
3481 compl_opt_refresh_always = FALSE;
3482 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3483 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3484 {
3485 char_u *v = di_refresh->di_tv.vval.v_string;
3486
3487 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3488 compl_opt_refresh_always = TRUE;
3489 }
3490
3491 // Add completions from a "words" list.
3492 di_words = dict_find(dict, (char_u *)"words", 5);
3493 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3494 ins_compl_add_list(di_words->di_tv.vval.v_list);
3495}
3496
3497/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003498 * Start completion for the complete() function.
3499 * "startcol" is where the matched text starts (1 is first column).
3500 * "list" is the list of matches.
3501 */
3502 static void
3503set_completion(colnr_T startcol, list_T *list)
3504{
3505 int save_w_wrow = curwin->w_wrow;
3506 int save_w_leftcol = curwin->w_leftcol;
3507 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003508 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003509 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3510 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3511 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003512
3513 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003514 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003515 ins_compl_prep(' ');
3516 ins_compl_clear();
3517 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003518 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003519
3520 compl_direction = FORWARD;
3521 if (startcol > curwin->w_cursor.col)
3522 startcol = curwin->w_cursor.col;
3523 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003524 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003525 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3526 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003527 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3528 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003529 if (p_ic)
3530 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003531 if (compl_orig_text.string == NULL)
3532 {
3533 compl_orig_text.length = 0;
3534 return;
3535 }
3536 compl_orig_text.length = (size_t)compl_length;
3537 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003538 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3539 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003540 return;
3541
3542 ctrl_x_mode = CTRL_X_EVAL;
3543
3544 ins_compl_add_list(list);
3545 compl_matches = ins_compl_make_cyclic();
3546 compl_started = TRUE;
3547 compl_used_match = TRUE;
3548 compl_cont_status = 0;
3549
3550 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003551 int no_select = compl_no_select || compl_longest;
3552 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003553 {
3554 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003555 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003556 // Down/Up has no real effect.
3557 ins_complete(K_UP, FALSE);
3558 }
3559 else
3560 ins_complete(Ctrl_N, FALSE);
3561 compl_enter_selects = compl_no_insert;
3562
3563 // Lazily show the popup menu, unless we got interrupted.
3564 if (!compl_interrupted)
3565 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003566 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003567 out_flush();
3568}
3569
3570/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003571 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003572 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003573 void
3574f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003575{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003576 if (in_vim9script()
3577 && (check_for_number_arg(argvars, 0) == FAIL
3578 || check_for_list_arg(argvars, 1) == FAIL))
3579 return;
3580
Bram Moolenaar24959102022-05-07 20:01:16 +01003581 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003582 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003583 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003584 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003585 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003586
3587 // Check for undo allowed here, because if something was already inserted
3588 // the line was already saved for undo and this check isn't done.
3589 if (!undo_allowed())
3590 return;
3591
Bram Moolenaard83392a2022-09-01 12:22:46 +01003592 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003593 {
glepnir19e1dd62025-05-08 22:50:38 +02003594 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003595 if (startcol > 0)
3596 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003597 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003598}
3599
3600/*
3601 * "complete_add()" function
3602 */
3603 void
3604f_complete_add(typval_T *argvars, typval_T *rettv)
3605{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003606 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003607 return;
3608
Bram Moolenaar440cf092021-04-03 20:13:30 +02003609 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003610}
3611
3612/*
3613 * "complete_check()" function
3614 */
3615 void
3616f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3617{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003618 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003619 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003620
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003621 ins_compl_check_keys(0, TRUE);
3622 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003623
3624 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003625}
3626
3627/*
glepnirbcd59952025-04-24 21:48:35 +02003628 * Add match item to the return list.
3629 * Returns FAIL if out of memory, OK otherwise.
3630 */
3631 static int
3632add_match_to_list(
3633 typval_T *rettv,
3634 char_u *str,
3635 int len,
3636 int pos)
3637{
3638 list_T *match;
3639 int ret;
3640
3641 match = list_alloc();
3642 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003643 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003644
3645 if ((ret = list_append_number(match, pos + 1)) == FAIL
3646 || (ret = list_append_string(match, str, len)) == FAIL
3647 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3648 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003649 vim_free(match);
3650 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003651 }
3652
3653 return OK;
3654}
3655
3656/*
3657 * "complete_match()" function
3658 */
3659 void
3660f_complete_match(typval_T *argvars, typval_T *rettv)
3661{
3662 linenr_T lnum;
3663 colnr_T col;
3664 char_u *line = NULL;
3665 char_u *ise = NULL;
3666 regmatch_T regmatch;
3667 char_u *before_cursor = NULL;
3668 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003669 int bytepos = 0;
3670 char_u part[MAXPATHL];
3671 int ret;
3672
3673 if (rettv_list_alloc(rettv) == FAIL)
3674 return;
3675
3676 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3677
3678 if (argvars[0].v_type == VAR_UNKNOWN)
3679 {
3680 lnum = curwin->w_cursor.lnum;
3681 col = curwin->w_cursor.col;
3682 }
3683 else if (argvars[1].v_type == VAR_UNKNOWN)
3684 {
3685 emsg(_(e_invalid_argument));
3686 return;
3687 }
3688 else
3689 {
3690 lnum = (linenr_T)tv_get_number(&argvars[0]);
3691 col = (colnr_T)tv_get_number(&argvars[1]);
3692 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3693 {
3694 semsg(_(e_invalid_line_number_nr), lnum);
3695 return;
3696 }
3697 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3698 {
3699 semsg(_(e_invalid_column_number_nr), col + 1);
3700 return;
3701 }
3702 }
3703
3704 line = ml_get_buf(curbuf, lnum, FALSE);
3705 if (line == NULL)
3706 return;
3707
3708 before_cursor = vim_strnsave(line, col);
3709 if (before_cursor == NULL)
3710 return;
3711
3712 if (ise == NULL || *ise == NUL)
3713 {
3714 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3715 if (regmatch.regprog != NULL)
3716 {
3717 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3718 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003719 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003720 regmatch.endp[0] - regmatch.startp[0]);
3721 if (trig == NULL)
3722 {
3723 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003724 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003725 return;
3726 }
3727
Christian Brabandt3accf042025-04-25 19:01:06 +02003728 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003729 ret = add_match_to_list(rettv, trig, -1, bytepos);
3730 vim_free(trig);
3731 if (ret == FAIL)
3732 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003733 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003734 vim_regfree(regmatch.regprog);
3735 return;
3736 }
3737 }
3738 vim_regfree(regmatch.regprog);
3739 }
3740 }
3741 else
3742 {
glepnir08db2f42025-05-14 20:26:19 +02003743 char_u *p = ise;
3744 char_u *p_space = NULL;
3745
glepnirbcd59952025-04-24 21:48:35 +02003746 cur_end = before_cursor + (int)STRLEN(before_cursor);
3747
3748 while (*p != NUL)
3749 {
glepnir8d0e42b2025-05-12 20:28:28 +02003750 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003751 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003752 {
glepnir08db2f42025-05-14 20:26:19 +02003753 len = p - p_space - 1;
3754 memcpy(part, p_space + 1, len);
3755 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003756 }
3757 else
glepnir08db2f42025-05-14 20:26:19 +02003758 {
3759 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3760 if (next_comma && *(next_comma + 1) == ' ')
3761 p_space = next_comma;
3762
glepnir8d0e42b2025-05-12 20:28:28 +02003763 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003764 }
glepnirbcd59952025-04-24 21:48:35 +02003765
3766 if (len > 0 && len <= col)
3767 {
3768 if (STRNCMP(cur_end - len, part, len) == 0)
3769 {
3770 bytepos = col - len;
3771 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3772 {
3773 vim_free(before_cursor);
3774 return;
3775 }
3776 }
3777 }
3778 }
3779 }
3780
3781 vim_free(before_cursor);
3782}
3783
3784/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003785 * Return Insert completion mode name string
3786 */
3787 static char_u *
3788ins_compl_mode(void)
3789{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003790 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003791 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3792
3793 return (char_u *)"";
3794}
3795
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003796/*
3797 * Assign the sequence number to all the completion matches which don't have
3798 * one assigned yet.
3799 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003800 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003801ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003802{
3803 int number = 0;
3804 compl_T *match;
3805
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003806 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003807 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003808 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003809 // This should normally succeed already at the first loop
3810 // cycle, so it's fast!
3811 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003812 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003813 if (match->cp_number != -1)
3814 {
3815 number = match->cp_number;
3816 break;
3817 }
3818 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003819 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003820 for (match = match->cp_next;
3821 match != NULL && match->cp_number == -1;
3822 match = match->cp_next)
3823 match->cp_number = ++number;
3824 }
3825 else // BACKWARD
3826 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003827 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003828 // number. This should normally succeed already at the
3829 // first loop cycle, so it's fast!
3830 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003831 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003832 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003833 if (match->cp_number != -1)
3834 {
3835 number = match->cp_number;
3836 break;
3837 }
glepnir40891ba2025-02-10 22:18:00 +01003838 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003839 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003840 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003841 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003842 for (match = match->cp_prev; match
3843 && match->cp_number == -1;
3844 match = match->cp_prev)
3845 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003846 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003847 }
3848}
3849
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003850/*
glepnir037b0282025-01-16 14:37:44 +01003851 * Fill the dict of complete_info
3852 */
3853 static void
3854fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3855{
3856 dict_add_string(di, "word", match->cp_str.string);
3857 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3858 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3859 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3860 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3861 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003862 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003863 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003864 // Add an empty string for backwards compatibility
3865 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003866 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003867 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003868}
3869
3870/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003871 * Get complete information
3872 */
3873 static void
3874get_complete_info(list_T *what_list, dict_T *retdict)
3875{
3876 int ret = OK;
3877 listitem_T *item;
3878#define CI_WHAT_MODE 0x01
3879#define CI_WHAT_PUM_VISIBLE 0x02
3880#define CI_WHAT_ITEMS 0x04
3881#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003882#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003883#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003884#define CI_WHAT_ALL 0xff
3885 int what_flag;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003886 int compl_fuzzy_match = (get_cot_flags() & COT_FUZZY) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003887
3888 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003889 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003890 else
3891 {
3892 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003893 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003894 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003895 {
3896 char_u *what = tv_get_string(&item->li_tv);
3897
3898 if (STRCMP(what, "mode") == 0)
3899 what_flag |= CI_WHAT_MODE;
3900 else if (STRCMP(what, "pum_visible") == 0)
3901 what_flag |= CI_WHAT_PUM_VISIBLE;
3902 else if (STRCMP(what, "items") == 0)
3903 what_flag |= CI_WHAT_ITEMS;
3904 else if (STRCMP(what, "selected") == 0)
3905 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003906 else if (STRCMP(what, "completed") == 0)
3907 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003908 else if (STRCMP(what, "matches") == 0)
3909 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003910 }
3911 }
3912
3913 if (ret == OK && (what_flag & CI_WHAT_MODE))
3914 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3915
3916 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3917 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3918
glepnir037b0282025-01-16 14:37:44 +01003919 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3920 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003921 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003922 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003923 dict_T *di;
3924 compl_T *match;
3925 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003926 int has_items = what_flag & CI_WHAT_ITEMS;
3927 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003928 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003929
glepnird4088ed2024-12-31 10:55:22 +01003930 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003931 {
3932 li = list_alloc();
3933 if (li == NULL)
3934 return;
glepnird4088ed2024-12-31 10:55:22 +01003935 ret = dict_add_list(retdict, (has_matches && !has_items)
3936 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003937 }
3938 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3939 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3940 ins_compl_update_sequence_numbers();
3941 if (ret == OK && compl_first_match != NULL)
3942 {
3943 int list_idx = 0;
3944 match = compl_first_match;
3945 do
3946 {
3947 if (!match_at_original_text(match))
3948 {
glepnird4088ed2024-12-31 10:55:22 +01003949 if (has_items
3950 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003951 {
3952 di = dict_alloc();
3953 if (di == NULL)
3954 return;
3955 ret = list_append_dict(li, di);
3956 if (ret != OK)
3957 return;
glepnir037b0282025-01-16 14:37:44 +01003958 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003959 }
glepnird4088ed2024-12-31 10:55:22 +01003960 if (compl_curr_match != NULL
3961 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003962 selected_idx = list_idx;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003963 if (compl_fuzzy_match || match->cp_in_match_array)
3964 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003965 }
3966 match = match->cp_next;
3967 }
3968 while (match != NULL && !is_first_match(match));
3969 }
3970 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3971 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003972
glepnir037b0282025-01-16 14:37:44 +01003973 if (ret == OK && selected_idx != -1 && has_completed)
3974 {
3975 di = dict_alloc();
3976 if (di == NULL)
3977 return;
3978 fill_complete_info_dict(di, compl_curr_match, FALSE);
3979 ret = dict_add_dict(retdict, "completed", di);
3980 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003981 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003982}
3983
3984/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003985 * "complete_info()" function
3986 */
3987 void
3988f_complete_info(typval_T *argvars, typval_T *rettv)
3989{
3990 list_T *what_list = NULL;
3991
Bram Moolenaar93a10962022-06-16 11:42:09 +01003992 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003993 return;
3994
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003995 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3996 return;
3997
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003998 if (argvars[0].v_type != VAR_UNKNOWN)
3999 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01004000 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004001 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004002 what_list = argvars[0].vval.v_list;
4003 }
4004 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004005}
4006#endif
4007
4008/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01004009 * Returns TRUE when using a user-defined function for thesaurus completion.
4010 */
4011 static int
4012thesaurus_func_complete(int type UNUSED)
4013{
4014#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01004015 return type == CTRL_X_THESAURUS
4016 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01004017#else
4018 return FALSE;
4019#endif
4020}
4021
4022/*
Girish Palya7c621052025-05-26 19:41:59 +02004023 * Check if 'cpt' list index can be advanced to the next completion source.
4024 */
4025 static int
4026may_advance_cpt_index(char_u *cpt)
4027{
4028 char_u *p = cpt;
4029
Girish Palya98c29db2025-06-01 19:40:00 +02004030 if (cpt_sources_index == -1)
4031 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004032 while (*p == ',' || *p == ' ') // Skip delimiters
4033 p++;
4034 return (*p != NUL);
4035}
4036
4037/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004038 * Return value of process_next_cpt_value()
4039 */
4040enum
4041{
4042 INS_COMPL_CPT_OK = 1,
4043 INS_COMPL_CPT_CONT,
4044 INS_COMPL_CPT_END
4045};
4046
4047/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004048 * state information used for getting the next set of insert completion
4049 * matches.
4050 */
4051typedef struct
4052{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004053 char_u *e_cpt_copy; // copy of 'complete'
4054 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004055 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004056 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004057 pos_T prev_match_pos; // previous match position
4058 int set_match_pos; // save first_match_pos/last_match_pos
4059 pos_T first_match_pos; // first match position
4060 pos_T last_match_pos; // last match position
4061 int found_all; // found all matches of a certain type.
4062 char_u *dict; // dictionary file to search
4063 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02004064 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004065} ins_compl_next_state_T;
4066
4067/*
4068 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004069 *
4070 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004072 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004073 * st->found_all - all matches of this type are found
4074 * st->ins_buf - search for completions in this buffer
4075 * st->first_match_pos - position of the first completion match
4076 * st->last_match_pos - position of the last completion match
4077 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004078 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004079 * st->dict - name of the dictionary or thesaurus file to search
4080 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004081 *
4082 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004083 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4084 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004085 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004086 */
4087 static int
4088process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004089 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004090 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004091 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004092 int fuzzy_collect,
4093 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004094{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004095 int compl_type = -1;
4096 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004097
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004098 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004099 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004100
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004101 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4102 st->e_cpt++;
4103
4104 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004105 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004106 st->ins_buf = curbuf;
4107 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004108 // Move the cursor back one character so that ^N can match the
4109 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004110 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004111 {
4112 // Move the cursor to after the last character in the
4113 // buffer, so that word at start of buffer is found
4114 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004115 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004116 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004117 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004118 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004119 compl_type = 0;
4120
4121 // Remember the first match so that the loop stops when we
4122 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004123 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004125 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004126 && (st->ins_buf = ins_compl_next_buf(
4127 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004128 {
4129 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004130 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004131 {
4132 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004133 st->first_match_pos.col = st->last_match_pos.col = 0;
4134 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4135 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004136 compl_type = 0;
4137 }
4138 else // unloaded buffer, scan like dictionary
4139 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004140 st->found_all = TRUE;
4141 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004142 {
4143 status = INS_COMPL_CPT_CONT;
4144 goto done;
4145 }
4146 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004147 st->dict = st->ins_buf->b_fname;
4148 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004149 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004150 if (!shortmess(SHM_COMPLETIONSCAN))
4151 {
4152 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4153 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4154 st->ins_buf->b_fname == NULL
4155 ? buf_spname(st->ins_buf)
4156 : st->ins_buf->b_sfname == NULL
4157 ? st->ins_buf->b_fname
4158 : st->ins_buf->b_sfname);
4159 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4160 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004161 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004162 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004163 status = INS_COMPL_CPT_END;
4164 else
4165 {
4166 if (ctrl_x_mode_line_or_eval())
4167 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004168 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004169 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004170 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004171 compl_type = CTRL_X_DICTIONARY;
4172 else
4173 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004174 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004175 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004176 st->dict = st->e_cpt;
4177 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004178 }
4179 }
Girish Palyacbe53192025-04-14 22:13:15 +02004180#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004181 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004182 {
4183 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004184 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004185 if (!st->func_cb)
4186 compl_type = -1;
4187 }
4188#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004189#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004190 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004191 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004192 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004193 compl_type = CTRL_X_PATH_DEFINES;
4194#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004195 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004196 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004197 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004198 if (!shortmess(SHM_COMPLETIONSCAN))
4199 {
4200 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4201 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4202 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4203 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004204 }
4205 else
4206 compl_type = -1;
4207
4208 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004209 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004210 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004211
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004212 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004213 if (compl_type == -1)
4214 status = INS_COMPL_CPT_CONT;
4215 }
4216
4217done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004218 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004219 return status;
4220}
4221
4222#ifdef FEAT_FIND_ID
4223/*
4224 * Get the next set of identifiers or defines matching "compl_pattern" in
4225 * included files.
4226 */
4227 static void
4228get_next_include_file_completion(int compl_type)
4229{
John Marriott5e6ea922024-11-23 14:01:57 +01004230 find_pattern_in_path(compl_pattern.string, compl_direction,
4231 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004232 (compl_type == CTRL_X_PATH_DEFINES
4233 && !(compl_cont_status & CONT_SOL))
4234 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004235 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004236}
4237#endif
4238
4239/*
4240 * Get the next set of words matching "compl_pattern" in dictionary or
4241 * thesaurus files.
4242 */
4243 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004244get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004245{
4246#ifdef FEAT_COMPL_FUNC
4247 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004248 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004249 else
4250#endif
4251 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004252 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004253 : (compl_type == CTRL_X_THESAURUS
4254 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4255 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004256 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004257 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004258 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004259}
4260
4261/*
4262 * Get the next set of tag names matching "compl_pattern".
4263 */
4264 static void
4265get_next_tag_completion(void)
4266{
4267 int save_p_ic;
4268 char_u **matches;
4269 int num_matches;
4270
4271 // set p_ic according to p_ic, p_scs and pat for find_tags().
4272 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004273 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004274
4275 // Find up to TAG_MANY matches. Avoids that an enormous number
4276 // of matches is found when compl_pattern is empty
4277 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004278 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004279 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004280 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004281 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4282 ins_compl_add_matches(num_matches, matches, p_ic);
4283 g_tag_at_cursor = FALSE;
4284 p_ic = save_p_ic;
4285}
4286
4287/*
glepnir8159fb12024-07-17 20:32:54 +02004288 * Compare function for qsort
4289 */
glepnirf31cfa22025-03-06 21:59:13 +01004290 static int
4291compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004292{
4293 int idx_a = *(const int *)a;
4294 int idx_b = *(const int *)b;
4295 int score_a = compl_fuzzy_scores[idx_a];
4296 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004297 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4298 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004299}
4300
4301/*
glepnirf31cfa22025-03-06 21:59:13 +01004302 * insert prefix with redraw
4303 */
4304 static void
4305ins_compl_longest_insert(char_u *prefix)
4306{
4307 ins_compl_delete();
4308 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4309 ins_redraw(FALSE);
4310}
4311
4312/*
4313 * Calculate the longest common prefix among the best fuzzy matches
4314 * stored in compl_best_matches, and insert it as the longest.
4315 */
4316 static void
4317fuzzy_longest_match(void)
4318{
4319 char_u *prefix = NULL;
4320 int prefix_len = 0;
4321 int i = 0;
4322 int j = 0;
4323 char_u *match_str = NULL;
4324 char_u *prefix_ptr = NULL;
4325 char_u *match_ptr = NULL;
4326 char_u *leader = NULL;
4327 size_t leader_len = 0;
4328 compl_T *compl = NULL;
4329 int more_candidates = FALSE;
4330 compl_T *nn_compl = NULL;
4331
4332 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004333 return;
glepnirf31cfa22025-03-06 21:59:13 +01004334
4335 nn_compl = compl_first_match->cp_next->cp_next;
4336 if (nn_compl && nn_compl != compl_first_match)
4337 more_candidates = TRUE;
4338
4339 compl = ctrl_x_mode_whole_line() ? compl_first_match
4340 : compl_first_match->cp_next;
4341 if (compl_num_bests == 1)
4342 {
4343 // no more candidates insert the match str
4344 if (!more_candidates)
4345 {
4346 ins_compl_longest_insert(compl->cp_str.string);
4347 compl_num_bests = 0;
4348 }
4349 compl_num_bests = 0;
4350 return;
4351 }
4352
4353 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4354 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004355 return;
glepnirf31cfa22025-03-06 21:59:13 +01004356 while (compl != NULL && i < compl_num_bests)
4357 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004358 compl_best_matches[i] = compl;
4359 compl = compl->cp_next;
4360 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004361 }
4362
4363 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004364 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004365
4366 for (i = 1; i < compl_num_bests; i++)
4367 {
4368 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004369 prefix_ptr = prefix;
4370 match_ptr = match_str;
4371 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004372
4373 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4374 {
4375 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4376 break;
4377
4378 MB_PTR_ADV(prefix_ptr);
4379 MB_PTR_ADV(match_ptr);
4380 j++;
4381 }
4382
4383 if (j > 0)
4384 prefix_len = j;
4385 }
4386
4387 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004388 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004389
4390 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004391 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004392 goto end;
4393
zeertzjq4422de62025-03-07 19:06:02 +01004394 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004395 if (prefix != NULL)
4396 {
4397 ins_compl_longest_insert(prefix);
4398 compl_cfc_longest_ins = TRUE;
4399 vim_free(prefix);
4400 }
4401
4402end:
4403 vim_free(compl_best_matches);
4404 compl_best_matches = NULL;
4405 compl_num_bests = 0;
4406}
4407
4408/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004409 * Get the next set of filename matching "compl_pattern".
4410 */
4411 static void
4412get_next_filename_completion(void)
4413{
4414 char_u **matches;
4415 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004416 char_u *ptr;
4417 garray_T fuzzy_indices;
4418 int i;
4419 int score;
4420 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004421 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004422 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004423 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004424 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004425 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4426 int max_score = 0;
4427 int current_score = 0;
4428 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004429
glepnirb9de1a02024-08-02 19:14:38 +02004430#ifdef BACKSLASH_IN_FILENAME
4431 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4432 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4433#else
4434 char pathsep = PATHSEP;
4435#endif
4436
glepnirf31cfa22025-03-06 21:59:13 +01004437 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004438 {
glepnirb9de1a02024-08-02 19:14:38 +02004439#ifdef BACKSLASH_IN_FILENAME
4440 if (curbuf->b_p_csl[0] == 's')
4441 {
John Marriott5e6ea922024-11-23 14:01:57 +01004442 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004443 {
4444 if (leader[i] == '\\')
4445 leader[i] = '/';
4446 }
4447 }
4448 else if (curbuf->b_p_csl[0] == 'b')
4449 {
John Marriott5e6ea922024-11-23 14:01:57 +01004450 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004451 {
4452 if (leader[i] == '/')
4453 leader[i] = '\\';
4454 }
4455 }
4456#endif
4457 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004458 if (last_sep == NULL)
4459 {
4460 // No path separator or separator is the last character,
4461 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004462 VIM_CLEAR_STRING(compl_pattern);
4463 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4464 if (compl_pattern.string == NULL)
4465 return;
4466 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004467 }
4468 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004469 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004470 else
4471 {
4472 // Split leader into path and file parts
4473 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004474 char_u *path_with_wildcard;
4475
4476 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004477 if (path_with_wildcard != NULL)
4478 {
John Marriott5e6ea922024-11-23 14:01:57 +01004479 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4480 VIM_CLEAR_STRING(compl_pattern);
4481 compl_pattern.string = path_with_wildcard;
4482 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004483
4484 // Move leader to the file part
4485 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004486 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004487 }
4488 }
glepnir8159fb12024-07-17 20:32:54 +02004489 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004490
John Marriott5e6ea922024-11-23 14:01:57 +01004491 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004492 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4493 return;
4494
4495 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004496 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004497#ifdef BACKSLASH_IN_FILENAME
4498 if (curbuf->b_p_csl[0] != NUL)
4499 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004500 for (i = 0; i < num_matches; ++i)
4501 {
glepnir8159fb12024-07-17 20:32:54 +02004502 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004503 while (*ptr != NUL)
4504 {
4505 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4506 *ptr = '/';
4507 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4508 *ptr = '\\';
4509 ptr += (*mb_ptr2len)(ptr);
4510 }
4511 }
4512 }
4513#endif
glepnir8159fb12024-07-17 20:32:54 +02004514
glepnirf31cfa22025-03-06 21:59:13 +01004515 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004516 {
4517 ga_init2(&fuzzy_indices, sizeof(int), 10);
4518 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4519
4520 for (i = 0; i < num_matches; i++)
4521 {
4522 ptr = matches[i];
4523 score = fuzzy_match_str(ptr, leader);
4524 if (score > 0)
4525 {
4526 if (ga_grow(&fuzzy_indices, 1) == OK)
4527 {
4528 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4529 compl_fuzzy_scores[i] = score;
4530 fuzzy_indices.ga_len++;
4531 }
4532 }
4533 }
4534
Christian Brabandt220474d2024-07-20 13:26:44 +02004535 // prevent qsort from deref NULL pointer
4536 if (fuzzy_indices.ga_len > 0)
4537 {
glepnirf31cfa22025-03-06 21:59:13 +01004538 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004539 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4540 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004541
Christian Brabandt220474d2024-07-20 13:26:44 +02004542 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004543 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004544 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004545 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4546 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004547 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4548 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004549 dir = FORWARD;
4550
4551 if (need_collect_bests)
4552 {
4553 if (i == 0 || current_score == max_score)
4554 {
4555 compl_num_bests++;
4556 max_score = current_score;
4557 }
4558 }
4559 }
glepnir8159fb12024-07-17 20:32:54 +02004560
Christian Brabandt220474d2024-07-20 13:26:44 +02004561 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004562 }
glepnir6b6280c2024-07-27 16:25:45 +02004563 else if (leader_len > 0)
4564 {
4565 FreeWild(num_matches, matches);
4566 num_matches = 0;
4567 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004568
glepnir8159fb12024-07-17 20:32:54 +02004569 vim_free(compl_fuzzy_scores);
4570 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004571
4572 if (compl_num_bests > 0 && compl_get_longest)
4573 fuzzy_longest_match();
4574 return;
glepnir8159fb12024-07-17 20:32:54 +02004575 }
4576
glepnir6b6280c2024-07-27 16:25:45 +02004577 if (num_matches > 0)
4578 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004579}
4580
4581/*
4582 * Get the next set of command-line completions matching "compl_pattern".
4583 */
4584 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004585get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004586{
4587 char_u **matches;
4588 int num_matches;
4589
John Marriott5e6ea922024-11-23 14:01:57 +01004590 if (expand_cmdline(&compl_xp, compl_pattern.string,
4591 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004592 ins_compl_add_matches(num_matches, matches, FALSE);
4593}
4594
4595/*
4596 * Get the next set of spell suggestions matching "compl_pattern".
4597 */
4598 static void
4599get_next_spell_completion(linenr_T lnum UNUSED)
4600{
4601#ifdef FEAT_SPELL
4602 char_u **matches;
4603 int num_matches;
4604
John Marriott5e6ea922024-11-23 14:01:57 +01004605 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004606 if (num_matches > 0)
4607 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004608 else
4609 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004610#endif
4611}
4612
4613/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004614 * Return the next word or line from buffer "ins_buf" at position
4615 * "cur_match_pos" for completion. The length of the match is set in "len".
4616 */
4617 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004618ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004619 buf_T *ins_buf, // buffer being scanned
4620 pos_T *cur_match_pos, // current match position
4621 int *match_len,
4622 int *cont_s_ipos) // next ^X<> will set initial_pos
4623{
4624 char_u *ptr;
4625 int len;
4626
4627 *match_len = 0;
4628 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4629 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004630 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004631 if (ctrl_x_mode_line_or_eval())
4632 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004633 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004634 {
4635 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4636 return NULL;
4637 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004638 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004639 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004640 {
4641 char_u *tmp_ptr = ptr;
4642
4643 ptr = skipwhite(tmp_ptr);
4644 len -= (int)(ptr - tmp_ptr);
4645 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004646 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004647 }
4648 else
4649 {
4650 char_u *tmp_ptr = ptr;
4651
John Marriott5e6ea922024-11-23 14:01:57 +01004652 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004653 {
4654 tmp_ptr += compl_length;
4655 // Skip if already inside a word.
4656 if (vim_iswordp(tmp_ptr))
4657 return NULL;
4658 // Find start of next word.
4659 tmp_ptr = find_word_start(tmp_ptr);
4660 }
4661 // Find end of this word.
4662 tmp_ptr = find_word_end(tmp_ptr);
4663 len = (int)(tmp_ptr - ptr);
4664
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004665 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004666 {
4667 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4668 {
4669 // Try next line, if any. the new word will be
4670 // "join" as if the normal command "J" was used.
4671 // IOSIZE is always greater than
4672 // compl_length, so the next STRNCPY always
4673 // works -- Acevedo
4674 STRNCPY(IObuff, ptr, len);
4675 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4676 tmp_ptr = ptr = skipwhite(ptr);
4677 // Find start of next word.
4678 tmp_ptr = find_word_start(tmp_ptr);
4679 // Find end of next word.
4680 tmp_ptr = find_word_end(tmp_ptr);
4681 if (tmp_ptr > ptr)
4682 {
4683 if (*ptr != ')' && IObuff[len - 1] != TAB)
4684 {
4685 if (IObuff[len - 1] != ' ')
4686 IObuff[len++] = ' ';
4687 // IObuf =~ "\k.* ", thus len >= 2
4688 if (p_js
4689 && (IObuff[len - 2] == '.'
4690 || (vim_strchr(p_cpo, CPO_JOINSP)
4691 == NULL
4692 && (IObuff[len - 2] == '?'
4693 || IObuff[len - 2] == '!'))))
4694 IObuff[len++] = ' ';
4695 }
4696 // copy as much as possible of the new word
4697 if (tmp_ptr - ptr >= IOSIZE - len)
4698 tmp_ptr = ptr + IOSIZE - len - 1;
4699 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4700 len += (int)(tmp_ptr - ptr);
4701 *cont_s_ipos = TRUE;
4702 }
4703 IObuff[len] = NUL;
4704 ptr = IObuff;
4705 }
4706 if (len == compl_length)
4707 return NULL;
4708 }
4709 }
4710
4711 *match_len = len;
4712 return ptr;
4713}
4714
4715/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004716 * Get the next set of words matching "compl_pattern" for default completion(s)
4717 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004718 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4719 * position "st->start_pos" in the "compl_direction" direction. If
4720 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4721 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004722 * Returns OK if a new next match is found, otherwise returns FAIL.
4723 */
4724 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004725get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004726{
4727 int found_new_match = FAIL;
4728 int save_p_scs;
4729 int save_p_ws;
4730 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004731 char_u *ptr = NULL;
4732 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004733 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004734 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004735 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004736 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004737
4738 // If 'infercase' is set, don't use 'smartcase' here
4739 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004740 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004741 p_scs = FALSE;
4742
4743 // Buffers other than curbuf are scanned from the beginning or the
4744 // end but never from the middle, thus setting nowrapscan in this
4745 // buffer is a good idea, on the other hand, we always set
4746 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4747 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004748 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004749 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004750 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004751 p_ws = TRUE;
4752 looped_around = FALSE;
4753 for (;;)
4754 {
4755 int cont_s_ipos = FALSE;
4756
4757 ++msg_silent; // Don't want messages for wrapscan.
4758
glepnirf31cfa22025-03-06 21:59:13 +01004759 if (in_collect)
4760 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004761 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004762 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004763 start_pos, &len, &ptr, &score);
4764 }
4765 // ctrl_x_mode_line_or_eval() || word-wise search that
4766 // has added a word that was at the beginning of the line
4767 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4768 found_new_match = search_for_exact_line(st->ins_buf,
4769 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004770 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004771 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004772 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004773 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004774 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004775 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004776 {
4777 // set "compl_started" even on fail
4778 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004779 st->first_match_pos = *st->cur_match_pos;
4780 st->last_match_pos = *st->cur_match_pos;
4781 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004782 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004783 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4784 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004785 {
4786 found_new_match = FAIL;
4787 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004788 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004789 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4790 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4791 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004792 {
4793 if (looped_around)
4794 found_new_match = FAIL;
4795 else
4796 looped_around = TRUE;
4797 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004798 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004799 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4800 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4801 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004802 {
4803 if (looped_around)
4804 found_new_match = FAIL;
4805 else
4806 looped_around = TRUE;
4807 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004808 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004809 if (found_new_match == FAIL)
4810 break;
4811
4812 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004813 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004814 && start_pos->lnum == st->cur_match_pos->lnum
4815 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004816 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004817
glepnirf31cfa22025-03-06 21:59:13 +01004818 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004819 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4820 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004821 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004822 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004823
Girish Palyab1565882025-04-15 20:16:00 +02004824 if (is_nearest_active() && in_curbuf)
4825 {
4826 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4827 if (score < 0)
4828 score = -score;
4829 score++;
4830 }
4831
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004832 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004833 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004834 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004835 {
glepnirf31cfa22025-03-06 21:59:13 +01004836 if (in_collect && score == compl_first_match->cp_next->cp_score)
4837 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004838 found_new_match = OK;
4839 break;
4840 }
4841 }
4842 p_scs = save_p_scs;
4843 p_ws = save_p_ws;
4844
4845 return found_new_match;
4846}
4847
Girish Palyacbe53192025-04-14 22:13:15 +02004848#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004849/*
4850 * Return the callback function associated with "p" if it points to a
4851 * userfunc.
4852 */
Girish Palyacbe53192025-04-14 22:13:15 +02004853 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004854get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004855{
4856 static callback_T cb;
4857 char_u buf[LSIZE];
4858 int slen;
4859
Girish Palya98c29db2025-06-01 19:40:00 +02004860 if (*p == 'o')
4861 return &curbuf->b_ofu_cb;
4862 if (*p == 'F')
4863 {
4864 if (*++p != ',' && *p != NUL)
4865 {
4866 free_callback(&cb);
4867 slen = copy_option_part(&p, buf, LSIZE, ",");
4868 if (slen > 0 && option_set_callback_func(buf, &cb))
4869 return &cb;
4870 return NULL;
4871 }
4872 else
4873 return &curbuf->b_cfu_cb;
4874 }
Girish Palyacbe53192025-04-14 22:13:15 +02004875 return NULL;
4876}
4877
4878/*
4879 * Retrieve new completion matches by invoking callback "cb".
4880 */
4881 static void
4882expand_cpt_function(callback_T *cb)
4883{
4884 // Re-insert the text removed by ins_compl_delete().
4885 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4886 // Get matches
4887 get_cpt_func_completion_matches(cb);
4888 // Undo insertion
4889 ins_compl_delete();
4890}
4891#endif
4892
4893/*
glepnir05460682025-05-26 18:23:27 +02004894 * Get completion matches from register contents.
4895 * Extracts words from all available registers and adds them to the completion list.
4896 */
4897 static void
4898get_register_completion(void)
4899{
4900 int dir = compl_direction;
4901 yankreg_T *reg = NULL;
4902 void *reg_ptr = NULL;
4903
4904 for (int i = 0; i < NUM_REGISTERS; i++)
4905 {
4906 int regname = 0;
4907
4908 if (i == 0)
4909 regname = '"'; // unnamed register
4910 else if (i < 10)
4911 regname = '0' + i;
4912 else if (i == DELETION_REGISTER)
4913 regname = '-';
4914#ifdef FEAT_CLIPBOARD
4915 else if (i == STAR_REGISTER)
4916 regname = '*';
4917 else if (i == PLUS_REGISTER)
4918 regname = '+';
4919#endif
4920 else
4921 regname = 'a' + i - 10;
4922
4923 // Skip invalid or black hole register
4924 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4925 continue;
4926
4927 reg_ptr = get_register(regname, FALSE);
4928 if (reg_ptr == NULL)
4929 continue;
4930
4931 reg = (yankreg_T *)reg_ptr;
4932
4933 for (int j = 0; j < reg->y_size; j++)
4934 {
4935 char_u *str = reg->y_array[j].string;
4936 if (str == NULL)
4937 continue;
4938
4939 char_u *p = str;
4940 while (*p != NUL)
4941 {
4942 p = find_word_start(p);
4943 if (*p == NUL)
4944 break;
4945
4946 char_u *word_end = find_word_end(p);
4947
4948 // Add the word to the completion list
4949 int len = (int)(word_end - p);
4950 if (len > 0 && (!compl_orig_text.string
4951 || (p_ic ? STRNICMP(p, compl_orig_text.string,
4952 compl_orig_text.length) == 0
4953 : STRNCMP(p, compl_orig_text.string,
4954 compl_orig_text.length) == 0)))
4955 {
4956 if (ins_compl_add_infercase(p, len, p_ic, NULL,
4957 dir, FALSE, 0) == OK)
4958 dir = FORWARD;
4959 }
4960
4961 p = word_end;
4962 }
4963 }
4964
4965 // Free the register copy
4966 put_register(regname, reg_ptr);
4967 }
4968}
4969
4970/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004971 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004972 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004973 */
4974 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004975get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004976{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004977 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004978
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004979 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004980 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004981 case -1:
4982 break;
4983#ifdef FEAT_FIND_ID
4984 case CTRL_X_PATH_PATTERNS:
4985 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004986 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987 break;
4988#endif
4989
4990 case CTRL_X_DICTIONARY:
4991 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004992 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4993 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004994 break;
4995
4996 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004997 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004998 break;
4999
5000 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005001 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005002 break;
5003
5004 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02005005 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005006 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005007 break;
5008
5009#ifdef FEAT_COMPL_FUNC
5010 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02005011 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
5012 expand_cpt_function(st->func_cb);
5013 else
5014 expand_by_function(type, compl_pattern.string, NULL);
5015 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005016 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02005017 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005018 break;
5019#endif
5020
5021 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005022 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005023 break;
5024
glepnir05460682025-05-26 18:23:27 +02005025 case CTRL_X_REGISTER:
5026 get_register_completion();
5027 break;
5028
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005029 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005030 found_new_match = get_next_default_completion(st, ini);
5031 if (found_new_match == FAIL && st->ins_buf == curbuf)
5032 st->found_all = TRUE;
5033 }
5034
5035 // check if compl_curr_match has changed, (e.g. other type of
5036 // expansion added something)
5037 if (type != 0 && compl_curr_match != compl_old_match)
5038 found_new_match = OK;
5039
5040 return found_new_match;
5041}
5042
5043/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005044 * Strips carets followed by numbers. This suffix typically represents the
5045 * max_matches setting.
5046 */
5047 static void
5048strip_caret_numbers_in_place(char_u *str)
5049{
5050 char_u *read = str, *write = str, *p;
5051
5052 if (str == NULL)
5053 return;
5054
5055 while (*read)
5056 {
5057 if (*read == '^')
5058 {
5059 p = read + 1;
5060 while (vim_isdigit(*p))
5061 p++;
5062 if ((*p == ',' || *p == '\0') && p != read + 1)
5063 {
5064 read = p;
5065 continue;
5066 }
5067 else
5068 *write++ = *read++;
5069 }
5070 else
5071 *write++ = *read++;
5072 }
5073 *write = '\0';
5074}
5075
5076/*
Girish Palya98c29db2025-06-01 19:40:00 +02005077 * Call functions specified in the 'cpt' option with findstart=1,
5078 * and retrieve the startcol.
5079 */
5080 static void
5081prepare_cpt_compl_funcs(void)
5082{
5083#ifdef FEAT_COMPL_FUNC
5084 char_u *cpt;
5085 char_u *p;
5086 callback_T *cb = NULL;
5087 int idx = 0;
5088 int startcol;
5089
5090 // Make a copy of 'cpt' in case the buffer gets wiped out
5091 cpt = vim_strsave(curbuf->b_p_cpt);
5092 strip_caret_numbers_in_place(cpt);
5093
5094 // Re-insert the text removed by ins_compl_delete().
5095 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5096
5097 for (p = cpt; *p;)
5098 {
5099 while (*p == ',' || *p == ' ') // Skip delimiters
5100 p++;
5101 cb = get_callback_if_cpt_func(p);
5102 if (cb)
5103 {
5104 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5105 == FAIL)
5106 {
5107 if (startcol == -3)
5108 cpt_sources_array[idx].cs_refresh_always = FALSE;
5109 else
5110 startcol = -2;
5111 }
5112 cpt_sources_array[idx].cs_startcol = startcol;
5113 }
5114 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5115 idx++;
5116 }
5117
5118 // Undo insertion
5119 ins_compl_delete();
5120
5121 vim_free(cpt);
5122#endif
5123}
5124
5125/*
Girish Palya7c621052025-05-26 19:41:59 +02005126 * Safely advance the cpt_sources_index by one.
5127 */
5128 static int
5129advance_cpt_sources_index_safe(void)
5130{
5131 if (cpt_sources_index < cpt_sources_count - 1)
5132 {
5133 cpt_sources_index++;
5134 return OK;
5135 }
5136#ifdef FEAT_EVAL
5137 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5138#endif
5139 return FAIL;
5140}
5141
5142/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005143 * Get the next expansion(s), using "compl_pattern".
5144 * The search starts at position "ini" in curbuf and in the direction
5145 * compl_direction.
5146 * When "compl_started" is FALSE start at that position, otherwise continue
5147 * where we stopped searching before.
5148 * This may return before finding all the matches.
5149 * Return the total number of matches or -1 if still unknown -- Acevedo
5150 */
5151 static int
5152ins_compl_get_exp(pos_T *ini)
5153{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005154 static ins_compl_next_state_T st;
5155 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005156 int i;
5157 int found_new_match;
5158 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005159 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005160
5161 if (!compl_started)
5162 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005163 buf_T *buf;
5164
5165 FOR_ALL_BUFFERS(buf)
5166 buf->b_scanned = 0;
5167 if (!st_cleared)
5168 {
5169 CLEAR_FIELD(st);
5170 st_cleared = TRUE;
5171 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005172 st.found_all = FALSE;
5173 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005174 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005175 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005176 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5177 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005178 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005179 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005180 st.last_match_pos = st.first_match_pos = *ini;
5181 }
5182 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5183 st.ins_buf = curbuf; // In case the buffer was wiped out.
5184
5185 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005186 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005187 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005188
Girish Palya98c29db2025-06-01 19:40:00 +02005189 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5190 !(compl_cont_status & CONT_LOCAL))
5191 {
5192 // ^N completion, not ^X^L or complete() or ^X^N
5193 if (!compl_started) // Before showing menu the first time
5194 {
5195 if (setup_cpt_sources() == FAIL)
5196 return FAIL;
5197 }
5198 prepare_cpt_compl_funcs();
5199 cpt_sources_index = 0;
5200 }
5201
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005202 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005203 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005204 {
5205 found_new_match = FAIL;
5206 st.set_match_pos = FALSE;
5207
5208 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5209 // or if found_all says this entry is done. For ^X^L only use the
5210 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005211 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005212 && (!compl_started || st.found_all))
5213 {
Girish Palya7c621052025-05-26 19:41:59 +02005214 int status = process_next_cpt_value(&st, &type, ini,
5215 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005216
5217 if (status == INS_COMPL_CPT_END)
5218 break;
5219 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005220 {
Girish Palya7c621052025-05-26 19:41:59 +02005221 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5222 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005223 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005224 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005225 }
5226
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005227 // If complete() was called then compl_pattern has been reset. The
5228 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005229 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005230 break;
5231
5232 // get the next set of completion matches
5233 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005234
Girish Palya7c621052025-05-26 19:41:59 +02005235 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5236 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005237
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005238 // break the loop for specialized modes (use 'complete' just for the
5239 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5240 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005241 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5242 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005243 {
5244 if (got_int)
5245 break;
5246 // Fill the popup menu as soon as possible.
5247 if (type != -1)
5248 ins_compl_check_keys(0, FALSE);
5249
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005250 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005251 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5252 break;
5253 compl_started = TRUE;
5254 }
5255 else
5256 {
5257 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005258 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005259 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005260
5261 compl_started = FALSE;
5262 }
5263 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005264 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005265 compl_started = TRUE;
5266
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005267 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005268 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005269 found_new_match = FAIL;
5270
5271 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005272 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005273 && !ctrl_x_mode_line_or_eval()))
5274 i = ins_compl_make_cyclic();
5275
glepnirf31cfa22025-03-06 21:59:13 +01005276 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5277 fuzzy_longest_match();
5278
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005279 if (compl_old_match != NULL)
5280 {
5281 // If several matches were added (FORWARD) or the search failed and has
5282 // just been made cyclic then we have to move compl_curr_match to the
5283 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005284 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005285 : compl_old_match->cp_prev;
5286 if (compl_curr_match == NULL)
5287 compl_curr_match = compl_old_match;
5288 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005289 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005290
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005291 return i;
5292}
5293
5294/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005295 * Update "compl_shown_match" to the actually shown match, it may differ when
5296 * "compl_leader" is used to omit some of the matches.
5297 */
5298 static void
5299ins_compl_update_shown_match(void)
5300{
5301 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005302 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005303 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005304 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005305 compl_shown_match = compl_shown_match->cp_next;
5306
5307 // If we didn't find it searching forward, and compl_shows_dir is
5308 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005309 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005310 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005311 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005312 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005313 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005314 {
5315 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005316 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005317 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005318 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005319 compl_shown_match = compl_shown_match->cp_prev;
5320 }
5321}
5322
5323/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005324 * Delete the old text being completed.
5325 */
5326 void
5327ins_compl_delete(void)
5328{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005329 // In insert mode: Delete the typed part.
5330 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005331 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005332 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005333 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005334 int has_preinsert = ins_compl_preinsert_effect();
5335 if (has_preinsert)
5336 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005337 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005338 curwin->w_cursor.col = compl_ins_end_col;
5339 }
5340
glepnir76bdb822025-02-08 19:04:51 +01005341 if (curwin->w_cursor.lnum > compl_lnum)
5342 {
5343 if (curwin->w_cursor.col < ml_get_curline_len())
5344 {
John Marriottf4b36412025-02-23 09:09:59 +01005345 char_u *line = ml_get_cursor();
5346 remaining.length = ml_get_cursor_len();
5347 remaining.string = vim_strnsave(line, remaining.length);
5348 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005349 return;
5350 }
5351 while (curwin->w_cursor.lnum > compl_lnum)
5352 {
5353 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5354 {
John Marriottf4b36412025-02-23 09:09:59 +01005355 if (remaining.string)
5356 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005357 return;
5358 }
zeertzjq060e6552025-02-21 20:06:26 +01005359 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005360 curwin->w_cursor.lnum--;
5361 }
5362 // move cursor to end of line
5363 curwin->w_cursor.col = ml_get_curline_len();
5364 }
5365
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005366 if ((int)curwin->w_cursor.col > col)
5367 {
5368 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005369 {
John Marriottf4b36412025-02-23 09:09:59 +01005370 if (remaining.string)
5371 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005372 return;
glepnire3647c82025-02-10 21:16:32 +01005373 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005374 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005375 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005376 }
5377
John Marriottf4b36412025-02-23 09:09:59 +01005378 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005379 {
5380 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005381 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005382 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005383 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005384 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005385 // TODO: is this sufficient for redrawing? Redrawing everything causes
5386 // flicker, thus we can't do that.
5387 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005388#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005389 // clear v:completed_item
5390 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005391#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005392}
5393
5394/*
glepnir76bdb822025-02-08 19:04:51 +01005395 * Insert a completion string that contains newlines.
5396 * The string is split and inserted line by line.
5397 */
5398 static void
5399ins_compl_expand_multiple(char_u *str)
5400{
5401 char_u *start = str;
5402 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005403 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005404
5405 while (*curr != NUL)
5406 {
5407 if (*curr == '\n')
5408 {
5409 // Insert the text chunk before newline
5410 if (curr > start)
5411 ins_char_bytes(start, (int)(curr - start));
5412
5413 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005414 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005415 start = curr + 1;
5416 }
5417 curr++;
5418 }
5419
5420 // Handle remaining text after last newline (if any)
5421 if (curr > start)
5422 ins_char_bytes(start, (int)(curr - start));
5423
5424 compl_ins_end_col = curwin->w_cursor.col;
5425}
5426
5427/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005428 * Insert the new text being completed.
5429 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005430 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5431 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005432 */
5433 void
glepniredd4ac32025-01-29 18:53:51 +01005434ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005435{
glepnir76bdb822025-02-08 19:04:51 +01005436 int compl_len = get_compl_len();
5437 int preinsert = ins_compl_has_preinsert();
5438 char_u *cp_str = compl_shown_match->cp_str.string;
5439 size_t cp_str_len = compl_shown_match->cp_str.length;
5440 size_t leader_len = ins_compl_leader_len();
5441 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005442
5443 // Make sure we don't go over the end of the string, this can happen with
5444 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005445 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005446 {
glepnir76bdb822025-02-08 19:04:51 +01005447 if (has_multiple)
5448 ins_compl_expand_multiple(cp_str + compl_len);
5449 else
5450 {
5451 ins_compl_insert_bytes(cp_str + compl_len, -1);
5452 if (preinsert && move_cursor)
5453 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5454 }
glepniredd4ac32025-01-29 18:53:51 +01005455 }
5456 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005457 compl_used_match = FALSE;
5458 else
5459 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005460#ifdef FEAT_EVAL
5461 {
5462 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5463
5464 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5465 }
5466#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005467 if (!in_compl_func)
5468 compl_curr_match = compl_shown_match;
5469}
5470
5471/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005472 * show the file name for the completion match (if any). Truncate the file
5473 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005474 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005475 static void
5476ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005477{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005478 char *lead = _("match in file");
5479 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5480 char_u *s;
5481 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005482
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005483 if (space <= 0)
5484 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005485
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005486 // We need the tail that fits. With double-byte encoding going
5487 // back from the end is very slow, thus go from the start and keep
5488 // the text that fits in "space" between "s" and "e".
5489 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005491 space -= ptr2cells(e);
5492 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005493 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005494 space += ptr2cells(s);
5495 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005496 }
5497 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005498 msg_hist_off = TRUE;
5499 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5500 s > compl_shown_match->cp_fname ? "<" : "", s);
5501 msg((char *)IObuff);
5502 msg_hist_off = FALSE;
5503 redraw_cmdline = FALSE; // don't overwrite!
5504}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005505
glepnirdca57fb2024-06-04 22:01:21 +02005506/*
zeertzjq551d8c32024-06-05 19:53:32 +02005507 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005508 */
glepnira218cc62024-06-03 19:32:39 +02005509 static compl_T *
5510find_comp_when_fuzzy(void)
5511{
5512 int score;
5513 char_u* str;
5514 int target_idx = -1;
5515 int is_forward = compl_shows_dir_forward();
5516 int is_backward = compl_shows_dir_backward();
5517 compl_T *comp = NULL;
5518
glepnir43eef882024-06-19 20:20:48 +02005519 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005520 || (is_backward && compl_selected_item == 0))
glepnir5a18ccf2025-05-11 13:48:33 +02005521 return match_at_original_text(compl_first_match)
5522 ? compl_first_match : compl_first_match->cp_prev;
glepnira218cc62024-06-03 19:32:39 +02005523
5524 if (is_forward)
5525 target_idx = compl_selected_item + 1;
5526 else if (is_backward)
Hirohito Higashi355db992025-04-28 18:07:02 +02005527 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005528 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005529
5530 score = compl_match_array[target_idx].pum_score;
5531 str = compl_match_array[target_idx].pum_text;
5532
5533 comp = compl_first_match;
Hirohito Higashia4a00a72025-05-08 22:58:31 +02005534 do
5535 {
Hirohito Higashi355db992025-04-28 18:07:02 +02005536 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
5537 return comp;
5538 comp = comp->cp_next;
glepnira218cc62024-06-03 19:32:39 +02005539 } while (comp != NULL && !is_first_match(comp));
5540
5541 return NULL;
5542}
5543
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005544/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005545 * Find the appropriate completion item when 'complete' ('cpt') includes
5546 * a 'max_matches' postfix. In this case, we search for a match where
5547 * 'cp_in_match_array' is set, indicating that the match is also present
5548 * in 'compl_match_array'.
5549 */
5550 static compl_T *
5551find_comp_when_cpt_sources(void)
5552{
5553 int is_forward = compl_shows_dir_forward();
5554 compl_T *match = compl_shown_match;
5555
5556 do
5557 match = is_forward ? match->cp_next : match->cp_prev;
5558 while (match->cp_next && !match->cp_in_match_array
5559 && !match_at_original_text(match));
5560 return match;
5561}
5562
5563/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005564 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005565 * times. The number of matches found is returned in 'num_matches'.
5566 *
5567 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5568 * get more completions. If it is FALSE, then do nothing when there are no more
5569 * completions in the given direction.
5570 *
5571 * If "advance" is TRUE, then completion will move to the first match.
5572 * Otherwise, the original text will be shown.
5573 *
5574 * Returns OK on success and -1 if the number of matches are unknown.
5575 */
5576 static int
5577find_next_completion_match(
5578 int allow_get_expansion,
5579 int todo, // repeat completion this many times
5580 int advance,
5581 int *num_matches)
5582{
5583 int found_end = FALSE;
5584 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005585 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005586 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5587 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005588 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005589
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005590 while (--todo >= 0)
5591 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005592 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005593 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02005594 if (compl_match_array != NULL && compl_fuzzy_match)
5595 compl_shown_match = find_comp_when_fuzzy();
5596 else if (cpt_sources_active)
5597 compl_shown_match = find_comp_when_cpt_sources();
5598 else
5599 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005600 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005601 && (is_first_match(compl_shown_match->cp_next)
5602 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005603 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005604 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005605 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005606 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005607 found_end = is_first_match(compl_shown_match);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005608 if (compl_match_array != NULL && compl_fuzzy_match)
5609 compl_shown_match = find_comp_when_fuzzy();
5610 else if (cpt_sources_active)
5611 compl_shown_match = find_comp_when_cpt_sources();
5612 else
5613 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005614 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005615 }
5616 else
5617 {
5618 if (!allow_get_expansion)
5619 {
5620 if (advance)
5621 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005622 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005623 compl_pending -= todo + 1;
5624 else
5625 compl_pending += todo + 1;
5626 }
5627 return -1;
5628 }
5629
5630 if (!compl_no_select && advance)
5631 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005632 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005633 --compl_pending;
5634 else
5635 ++compl_pending;
5636 }
5637
5638 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005639 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005640
5641 // handle any pending completions
5642 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005643 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005644 {
5645 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5646 {
5647 compl_shown_match = compl_shown_match->cp_next;
5648 --compl_pending;
5649 }
5650 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5651 {
5652 compl_shown_match = compl_shown_match->cp_prev;
5653 ++compl_pending;
5654 }
5655 else
5656 break;
5657 }
5658 found_end = FALSE;
5659 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005660 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005661 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005662 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005663 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005664 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005665 ++todo;
5666 else
5667 // Remember a matching item.
5668 found_compl = compl_shown_match;
5669
5670 // Stop at the end of the list when we found a usable match.
5671 if (found_end)
5672 {
5673 if (found_compl != NULL)
5674 {
5675 compl_shown_match = found_compl;
5676 break;
5677 }
5678 todo = 1; // use first usable match after wrapping around
5679 }
5680 }
5681
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005682 return OK;
5683}
5684
5685/*
5686 * Fill in the next completion in the current direction.
5687 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5688 * get more completions. If it is FALSE, then we just do nothing when there
5689 * are no more completions in a given direction. The latter case is used when
5690 * we are still in the middle of finding completions, to allow browsing
5691 * through the ones found so far.
5692 * Return the total number of matches, or -1 if still unknown -- webb.
5693 *
5694 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5695 * compl_shown_match here.
5696 *
5697 * Note that this function may be called recursively once only. First with
5698 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5699 * calls this function with "allow_get_expansion" FALSE.
5700 */
5701 static int
5702ins_compl_next(
5703 int allow_get_expansion,
5704 int count, // repeat completion this many times; should
5705 // be at least 1
5706 int insert_match, // Insert the newly selected match
5707 int in_compl_func) // called from complete_check()
5708{
5709 int num_matches = -1;
5710 int todo = count;
5711 int advance;
5712 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005713 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005714 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005715 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5716 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005717 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005718
5719 // When user complete function return -1 for findstart which is next
5720 // time of 'always', compl_shown_match become NULL.
5721 if (compl_shown_match == NULL)
5722 return -1;
5723
John Marriott5e6ea922024-11-23 14:01:57 +01005724 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005725 && !match_at_original_text(compl_shown_match)
5726 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005727 // Update "compl_shown_match" to the actually shown match
5728 ins_compl_update_shown_match();
5729
5730 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005731 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005732 // Delete old text to be replaced
5733 ins_compl_delete();
5734
5735 // When finding the longest common text we stick at the original text,
5736 // don't let CTRL-N or CTRL-P move to the first match.
5737 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5738
5739 // When restarting the search don't insert the first match either.
5740 if (compl_restarting)
5741 {
5742 advance = FALSE;
5743 compl_restarting = FALSE;
5744 }
5745
5746 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5747 // around.
5748 if (find_next_completion_match(allow_get_expansion, todo, advance,
5749 &num_matches) == -1)
5750 return -1;
5751
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005752 if (curbuf != orig_curbuf)
5753 {
5754 // In case some completion function switched buffer, don't want to
5755 // insert the completion elsewhere.
5756 return -1;
5757 }
5758
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005759 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005760 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005761 {
glepnir6a38aff2024-12-16 21:56:16 +01005762 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005763 compl_used_match = FALSE;
5764 }
5765 else if (insert_match)
5766 {
5767 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005768 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005769 else
glepnir6a38aff2024-12-16 21:56:16 +01005770 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005771 }
5772 else
5773 compl_used_match = FALSE;
5774
5775 if (!allow_get_expansion)
5776 {
5777 // may undisplay the popup menu first
5778 ins_compl_upd_pum();
5779
5780 if (pum_enough_matches())
5781 // Will display the popup menu, don't redraw yet to avoid flicker.
5782 pum_call_update_screen();
5783 else
5784 // Not showing the popup menu yet, redraw to show the user what was
5785 // inserted.
5786 update_screen(0);
5787
5788 // display the updated popup menu
5789 ins_compl_show_pum();
5790#ifdef FEAT_GUI
5791 if (gui.in_use)
5792 {
5793 // Show the cursor after the match, not after the redrawn text.
5794 setcursor();
5795 out_flush_cursor(FALSE, FALSE);
5796 }
5797#endif
5798
5799 // Delete old text to be replaced, since we're still searching and
5800 // don't want to match ourselves!
5801 ins_compl_delete();
5802 }
5803
5804 // Enter will select a match when the match wasn't inserted and the popup
5805 // menu is visible.
5806 if (compl_no_insert && !started)
5807 compl_enter_selects = TRUE;
5808 else
5809 compl_enter_selects = !insert_match && compl_match_array != NULL;
5810
5811 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005812 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005813 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005814
5815 return num_matches;
5816}
5817
5818/*
5819 * Call this while finding completions, to check whether the user has hit a key
5820 * that should change the currently displayed completion, or exit completion
5821 * mode. Also, when compl_pending is not zero, show a completion as soon as
5822 * possible. -- webb
5823 * "frequency" specifies out of how many calls we actually check.
5824 * "in_compl_func" is TRUE when called from complete_check(), don't set
5825 * compl_curr_match.
5826 */
5827 void
5828ins_compl_check_keys(int frequency, int in_compl_func)
5829{
5830 static int count = 0;
5831 int c;
5832
5833 // Don't check when reading keys from a script, :normal or feedkeys().
5834 // That would break the test scripts. But do check for keys when called
5835 // from complete_check().
5836 if (!in_compl_func && (using_script() || ex_normal_busy))
5837 return;
5838
5839 // Only do this at regular intervals
5840 if (++count < frequency)
5841 return;
5842 count = 0;
5843
5844 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5845 // can't do its work correctly.
5846 c = vpeekc_any();
5847 if (c != NUL)
5848 {
5849 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5850 {
5851 c = safe_vgetc(); // Eat the character
5852 compl_shows_dir = ins_compl_key2dir(c);
5853 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5854 c != K_UP && c != K_DOWN, in_compl_func);
5855 }
5856 else
5857 {
5858 // Need to get the character to have KeyTyped set. We'll put it
5859 // back with vungetc() below. But skip K_IGNORE.
5860 c = safe_vgetc();
5861 if (c != K_IGNORE)
5862 {
5863 // Don't interrupt completion when the character wasn't typed,
5864 // e.g., when doing @q to replay keys.
5865 if (c != Ctrl_R && KeyTyped)
5866 compl_interrupted = TRUE;
5867
5868 vungetc(c);
5869 }
5870 }
5871 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005872 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005873 {
5874 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5875
5876 compl_pending = 0;
5877 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5878 }
5879}
5880
5881/*
5882 * Decide the direction of Insert mode complete from the key typed.
5883 * Returns BACKWARD or FORWARD.
5884 */
5885 static int
5886ins_compl_key2dir(int c)
5887{
5888 if (c == Ctrl_P || c == Ctrl_L
5889 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5890 return BACKWARD;
5891 return FORWARD;
5892}
5893
5894/*
5895 * Return TRUE for keys that are used for completion only when the popup menu
5896 * is visible.
5897 */
5898 static int
5899ins_compl_pum_key(int c)
5900{
5901 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5902 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5903 || c == K_UP || c == K_DOWN);
5904}
5905
5906/*
5907 * Decide the number of completions to move forward.
5908 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5909 */
5910 static int
5911ins_compl_key2count(int c)
5912{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005913 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5914 {
glepnir19e1dd62025-05-08 22:50:38 +02005915 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005916 if (h > 3)
5917 h -= 2; // keep some context
5918 return h;
5919 }
5920 return 1;
5921}
5922
5923/*
5924 * Return TRUE if completion with "c" should insert the match, FALSE if only
5925 * to change the currently selected completion.
5926 */
5927 static int
5928ins_compl_use_match(int c)
5929{
5930 switch (c)
5931 {
5932 case K_UP:
5933 case K_DOWN:
5934 case K_PAGEDOWN:
5935 case K_KPAGEDOWN:
5936 case K_S_DOWN:
5937 case K_PAGEUP:
5938 case K_KPAGEUP:
5939 case K_S_UP:
5940 return FALSE;
5941 }
5942 return TRUE;
5943}
5944
5945/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005946 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5947 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005948 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005949 * Uses the global variables: compl_cont_status and ctrl_x_mode
5950 */
5951 static int
5952get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5953{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005954 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005955 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005956 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005957 {
5958 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5959 ;
5960 compl_col += ++startcol;
5961 compl_length = curs_col - startcol;
5962 }
5963 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005964 {
John Marriott5e6ea922024-11-23 14:01:57 +01005965 compl_pattern.string = str_foldcase(line + compl_col,
5966 compl_length, NULL, 0);
5967 if (compl_pattern.string == NULL)
5968 {
5969 compl_pattern.length = 0;
5970 return FAIL;
5971 }
5972 compl_pattern.length = STRLEN(compl_pattern.string);
5973 }
5974 else
5975 {
5976 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5977 if (compl_pattern.string == NULL)
5978 {
5979 compl_pattern.length = 0;
5980 return FAIL;
5981 }
5982 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005983 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005984 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005985 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005986 {
5987 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005988 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005989 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005990
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005991 if (!vim_iswordp(line + compl_col)
5992 || (compl_col > 0
5993 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005994 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005995 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005996 prefixlen = 0;
5997 }
John Marriott5e6ea922024-11-23 14:01:57 +01005998
5999 // we need up to 2 extra chars for the prefix
6000 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
6001 compl_pattern.string = alloc(n);
6002 if (compl_pattern.string == NULL)
6003 {
6004 compl_pattern.length = 0;
6005 return FAIL;
6006 }
6007 STRCPY((char *)compl_pattern.string, prefix);
6008 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006009 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006010 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006011 }
6012 else if (--startcol < 0
6013 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
6014 {
John Marriott5e6ea922024-11-23 14:01:57 +01006015 size_t len = STRLEN_LITERAL("\\<\\k\\k");
6016
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006017 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01006018 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
6019 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006020 {
John Marriott5e6ea922024-11-23 14:01:57 +01006021 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006022 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006023 }
John Marriott5e6ea922024-11-23 14:01:57 +01006024 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006025 compl_col += curs_col;
6026 compl_length = 0;
6027 }
6028 else
6029 {
6030 // Search the point of change class of multibyte character
6031 // or not a word single byte character backward.
6032 if (has_mbyte)
6033 {
6034 int base_class;
6035 int head_off;
6036
6037 startcol -= (*mb_head_off)(line, line + startcol);
6038 base_class = mb_get_class(line + startcol);
6039 while (--startcol >= 0)
6040 {
6041 head_off = (*mb_head_off)(line, line + startcol);
6042 if (base_class != mb_get_class(line + startcol
6043 - head_off))
6044 break;
6045 startcol -= head_off;
6046 }
6047 }
6048 else
glepnir19e1dd62025-05-08 22:50:38 +02006049 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006050 while (--startcol >= 0 && vim_iswordc(line[startcol]))
6051 ;
glepnir19e1dd62025-05-08 22:50:38 +02006052 }
6053
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006054 compl_col += ++startcol;
6055 compl_length = (int)curs_col - startcol;
6056 if (compl_length == 1)
6057 {
6058 // Only match word with at least two chars -- webb
6059 // there's no need to call quote_meta,
6060 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01006061 compl_pattern.string = alloc(7);
6062 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006063 {
John Marriott5e6ea922024-11-23 14:01:57 +01006064 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006065 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006066 }
John Marriott5e6ea922024-11-23 14:01:57 +01006067 STRCPY((char *)compl_pattern.string, "\\<");
6068 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
6069 STRCAT((char *)compl_pattern.string, "\\k");
6070 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006071 }
6072 else
6073 {
John Marriott5e6ea922024-11-23 14:01:57 +01006074 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6075
6076 compl_pattern.string = alloc(n);
6077 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006078 {
John Marriott5e6ea922024-11-23 14:01:57 +01006079 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006080 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006081 }
John Marriott5e6ea922024-11-23 14:01:57 +01006082 STRCPY((char *)compl_pattern.string, "\\<");
6083 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006084 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006085 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006086 }
6087 }
6088
6089 return OK;
6090}
6091
6092/*
6093 * Get the pattern, column and length for whole line completion or for the
6094 * complete() function.
6095 * Sets the global variables: compl_col, compl_length and compl_pattern.
6096 */
6097 static int
6098get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6099{
6100 compl_col = (colnr_T)getwhitecols(line);
6101 compl_length = (int)curs_col - (int)compl_col;
6102 if (compl_length < 0) // cursor in indent: empty pattern
6103 compl_length = 0;
6104 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006105 {
John Marriott5e6ea922024-11-23 14:01:57 +01006106 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6107 NULL, 0);
6108 if (compl_pattern.string == NULL)
6109 {
6110 compl_pattern.length = 0;
6111 return FAIL;
6112 }
6113 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006114 }
John Marriott5e6ea922024-11-23 14:01:57 +01006115 else
6116 {
6117 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6118 if (compl_pattern.string == NULL)
6119 {
6120 compl_pattern.length = 0;
6121 return FAIL;
6122 }
6123 compl_pattern.length = (size_t)compl_length;
6124 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006125
6126 return OK;
6127}
6128
6129/*
6130 * Get the pattern, column and length for filename completion.
6131 * Sets the global variables: compl_col, compl_length and compl_pattern.
6132 */
6133 static int
6134get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6135{
6136 // Go back to just before the first filename character.
6137 if (startcol > 0)
6138 {
6139 char_u *p = line + startcol;
6140
6141 MB_PTR_BACK(line, p);
6142 while (p > line && vim_isfilec(PTR2CHAR(p)))
6143 MB_PTR_BACK(line, p);
6144 if (p == line && vim_isfilec(PTR2CHAR(p)))
6145 startcol = 0;
6146 else
6147 startcol = (int)(p - line) + 1;
6148 }
6149
6150 compl_col += startcol;
6151 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006152 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6153 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006154 {
John Marriott5e6ea922024-11-23 14:01:57 +01006155 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006156 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006157 }
6158
John Marriott5e6ea922024-11-23 14:01:57 +01006159 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006160
6161 return OK;
6162}
6163
6164/*
6165 * Get the pattern, column and length for command-line completion.
6166 * Sets the global variables: compl_col, compl_length and compl_pattern.
6167 */
6168 static int
6169get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6170{
John Marriott5e6ea922024-11-23 14:01:57 +01006171 compl_pattern.string = vim_strnsave(line, curs_col);
6172 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006173 {
John Marriott5e6ea922024-11-23 14:01:57 +01006174 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006175 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006176 }
John Marriott5e6ea922024-11-23 14:01:57 +01006177 compl_pattern.length = curs_col;
6178 set_cmd_context(&compl_xp, compl_pattern.string,
6179 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006180 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6181 || compl_xp.xp_context == EXPAND_NOTHING)
6182 // No completion possible, use an empty pattern to get a
6183 // "pattern not found" message.
6184 compl_col = curs_col;
6185 else
John Marriott5e6ea922024-11-23 14:01:57 +01006186 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006187 compl_length = curs_col - compl_col;
6188
6189 return OK;
6190}
6191
Girish Palya98c29db2025-06-01 19:40:00 +02006192#ifdef FEAT_COMPL_FUNC
6193/*
6194 * Set global variables related to completion:
6195 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6196 */
6197 static int
6198set_compl_globals(
6199 int startcol UNUSED,
6200 colnr_T curs_col UNUSED,
6201 int is_cpt_compl UNUSED)
6202{
6203 char_u *line = NULL;
6204 string_T *pattern = NULL;
6205 int len;
6206
6207 if (startcol < 0 || startcol > curs_col)
6208 startcol = curs_col;
6209 len = curs_col - startcol;
6210
6211 // Re-obtain line in case it has changed
6212 line = ml_get(curwin->w_cursor.lnum);
6213
6214 pattern = is_cpt_compl ? &cpt_compl_pattern : &compl_pattern;
6215 pattern->string = vim_strnsave(line + startcol, (size_t)len);
6216 if (pattern->string == NULL)
6217 {
6218 pattern->length = 0;
6219 return FAIL;
6220 }
6221 pattern->length = (size_t)len;
6222 if (!is_cpt_compl)
6223 {
6224 compl_col = startcol;
6225 compl_length = len;
6226 }
6227 return OK;
6228}
6229#endif
6230
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006231/*
6232 * Get the pattern, column and length for user defined completion ('omnifunc',
6233 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006234 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006235 * Callback function "cb" is set if triggered by a function in the 'cpt'
6236 * option; otherwise, it is NULL.
6237 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006238 */
6239 static int
glepnir19e1dd62025-05-08 22:50:38 +02006240get_userdefined_compl_info(
6241 colnr_T curs_col UNUSED,
6242 callback_T *cb UNUSED,
6243 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006244{
6245 int ret = FAIL;
6246
6247#ifdef FEAT_COMPL_FUNC
6248 // Call user defined function 'completefunc' with "a:findstart"
6249 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006250 typval_T args[3];
6251 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006252 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006253 pos_T pos;
6254 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006255 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006256
Girish Palyacbe53192025-04-14 22:13:15 +02006257 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006258 {
Girish Palyacbe53192025-04-14 22:13:15 +02006259 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6260 // length as a string
6261 funcname = get_complete_funcname(ctrl_x_mode);
6262 if (*funcname == NUL)
6263 {
6264 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6265 ? "completefunc" : "omnifunc");
6266 return FAIL;
6267 }
6268 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006269 }
6270
6271 args[0].v_type = VAR_NUMBER;
6272 args[0].vval.v_number = 1;
6273 args[1].v_type = VAR_STRING;
6274 args[1].vval.v_string = (char_u *)"";
6275 args[2].v_type = VAR_UNKNOWN;
6276 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006277 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006278 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006279 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006280
6281 State = save_State;
6282 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006283 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006284 validate_cursor();
6285 if (!EQUAL_POS(curwin->w_cursor, pos))
6286 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006287 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006288 return FAIL;
6289 }
6290
Girish Palyacbe53192025-04-14 22:13:15 +02006291 if (startcol != NULL)
6292 *startcol = col;
6293
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006294 // Return value -2 means the user complete function wants to cancel the
6295 // complete without an error, do the same if the function did not execute
6296 // successfully.
6297 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006298 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006299
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006300 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006301 if (col == -3)
6302 {
Girish Palyacbe53192025-04-14 22:13:15 +02006303 if (is_cpt_function)
6304 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006305 ctrl_x_mode = CTRL_X_NORMAL;
6306 edit_submode = NULL;
6307 if (!shortmess(SHM_COMPLETIONMENU))
6308 msg_clr_cmdline();
6309 return FAIL;
6310 }
6311
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006312 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006313 // completion.
6314 compl_opt_refresh_always = FALSE;
6315 compl_opt_suppress_empty = FALSE;
6316
Girish Palya98c29db2025-06-01 19:40:00 +02006317 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006318#endif
6319
6320 return ret;
6321}
6322
6323/*
6324 * Get the pattern, column and length for spell completion.
6325 * Sets the global variables: compl_col, compl_length and compl_pattern.
6326 * Uses the global variable: spell_bad_len
6327 */
6328 static int
6329get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6330{
6331 int ret = FAIL;
6332#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006333 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006334
6335 if (spell_bad_len > 0)
6336 compl_col = curs_col - spell_bad_len;
6337 else
6338 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006339
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006340 if (compl_col >= (colnr_T)startcol)
6341 {
6342 compl_length = 0;
6343 compl_col = curs_col;
6344 }
6345 else
6346 {
6347 spell_expand_check_cap(compl_col);
6348 compl_length = (int)curs_col - compl_col;
6349 }
6350 // Need to obtain "line" again, it may have become invalid.
6351 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006352 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6353 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006354 {
John Marriott5e6ea922024-11-23 14:01:57 +01006355 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006356 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006357 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006358
John Marriott5e6ea922024-11-23 14:01:57 +01006359 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006360 ret = OK;
6361#endif
6362
6363 return ret;
6364}
6365
6366/*
6367 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006368 * "startcol" - start column number of the completion pattern/text
6369 * "cur_col" - current cursor column
6370 * On return, "line_invalid" is set to TRUE, if the current line may have
6371 * become invalid and needs to be fetched again.
6372 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006373 */
6374 static int
6375compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6376{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006377 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006378 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6379 && !thesaurus_func_complete(ctrl_x_mode)))
6380 {
6381 return get_normal_compl_info(line, startcol, curs_col);
6382 }
6383 else if (ctrl_x_mode_line_or_eval())
6384 {
6385 return get_wholeline_compl_info(line, curs_col);
6386 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006387 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006388 {
6389 return get_filename_compl_info(line, startcol, curs_col);
6390 }
6391 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6392 {
6393 return get_cmdline_compl_info(line, curs_col);
6394 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006395 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006396 || thesaurus_func_complete(ctrl_x_mode))
6397 {
Girish Palyacbe53192025-04-14 22:13:15 +02006398 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006399 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006400 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006401 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006402 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006403 {
6404 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6405 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006406 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006407 }
glepnir05460682025-05-26 18:23:27 +02006408 else if (ctrl_x_mode_register())
6409 {
6410 return get_normal_compl_info(line, startcol, curs_col);
6411 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006412 else
6413 {
6414 internal_error("ins_complete()");
6415 return FAIL;
6416 }
6417
6418 return OK;
6419}
6420
6421/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006422 * Continue an interrupted completion mode search in "line".
6423 *
6424 * If this same ctrl_x_mode has been interrupted use the text from
6425 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6426 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6427 * the same line as the cursor then fix it (the line has been split because it
6428 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6429 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006430 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006431 static void
6432ins_compl_continue_search(char_u *line)
6433{
6434 // it is a continued search
6435 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006436 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6437 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006438 {
6439 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6440 {
6441 // line (probably) wrapped, set compl_startpos to the
6442 // first non_blank in the line, if it is not a wordchar
6443 // include it to get a better pattern, but then we don't
6444 // want the "\\<" prefix, check it below
6445 compl_col = (colnr_T)getwhitecols(line);
6446 compl_startpos.col = compl_col;
6447 compl_startpos.lnum = curwin->w_cursor.lnum;
6448 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6449 }
6450 else
6451 {
6452 // S_IPOS was set when we inserted a word that was at the
6453 // beginning of the line, which means that we'll go to SOL
6454 // mode but first we need to redefine compl_startpos
6455 if (compl_cont_status & CONT_S_IPOS)
6456 {
6457 compl_cont_status |= CONT_SOL;
6458 compl_startpos.col = (colnr_T)(skipwhite(
6459 line + compl_length
6460 + compl_startpos.col) - line);
6461 }
6462 compl_col = compl_startpos.col;
6463 }
6464 compl_length = curwin->w_cursor.col - (int)compl_col;
6465 // IObuff is used to add a "word from the next line" would we
6466 // have enough space? just being paranoid
6467#define MIN_SPACE 75
6468 if (compl_length > (IOSIZE - MIN_SPACE))
6469 {
6470 compl_cont_status &= ~CONT_SOL;
6471 compl_length = (IOSIZE - MIN_SPACE);
6472 compl_col = curwin->w_cursor.col - compl_length;
6473 }
6474 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6475 if (compl_length < 1)
6476 compl_cont_status &= CONT_LOCAL;
6477 }
6478 else if (ctrl_x_mode_line_or_eval())
6479 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6480 else
6481 compl_cont_status = 0;
6482}
6483
6484/*
6485 * start insert mode completion
6486 */
6487 static int
6488ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006489{
glepnir19e1dd62025-05-08 22:50:38 +02006490 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006491 int startcol = 0; // column where searched text starts
6492 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006493 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006494 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006495 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006496
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006497 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006498 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006499 did_si = FALSE;
6500 can_si = FALSE;
6501 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006502 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006503 return FAIL;
6504
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006505 line = ml_get(curwin->w_cursor.lnum);
6506 curs_col = curwin->w_cursor.col;
6507 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006508 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006509
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006510 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6511 && compl_cont_mode == ctrl_x_mode)
6512 // this same ctrl-x_mode was interrupted previously. Continue the
6513 // completion.
6514 ins_compl_continue_search(line);
6515 else
6516 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006517
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006518 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006519 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006520 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006521 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006522 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6523 compl_cont_status = 0;
6524 compl_cont_status |= CONT_N_ADDS;
6525 compl_startpos = curwin->w_cursor;
6526 startcol = (int)curs_col;
6527 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006528 }
6529
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006530 // Work out completion pattern and original text -- webb
6531 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6532 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006533 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6534 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006535 // restore did_ai, so that adding comment leader works
6536 did_ai = save_did_ai;
6537 return FAIL;
6538 }
6539 // If "line" was changed while getting completion info get it again.
6540 if (line_invalid)
6541 line = ml_get(curwin->w_cursor.lnum);
6542
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006543 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006544 {
6545 edit_submode_pre = (char_u *)_(" Adding");
6546 if (ctrl_x_mode_line_or_eval())
6547 {
6548 // Insert a new line, keep indentation but ignore 'comments'.
6549 char_u *old = curbuf->b_p_com;
6550
6551 curbuf->b_p_com = (char_u *)"";
6552 compl_startpos.lnum = curwin->w_cursor.lnum;
6553 compl_startpos.col = compl_col;
6554 ins_eol('\r');
6555 curbuf->b_p_com = old;
6556 compl_length = 0;
6557 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006558 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006559 }
glepnircfe502c2025-04-17 20:17:53 +02006560 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006561 {
6562 compl_startpos = curwin->w_cursor;
6563 compl_cont_status &= CONT_S_IPOS;
6564 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006565 }
6566 else
6567 {
6568 edit_submode_pre = NULL;
6569 compl_startpos.col = compl_col;
6570 }
6571
6572 if (compl_cont_status & CONT_LOCAL)
6573 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6574 else
6575 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6576
6577 // If any of the original typed text has been changed we need to fix
6578 // the redo buffer.
6579 ins_compl_fixRedoBufForLeader(NULL);
6580
6581 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006582 VIM_CLEAR_STRING(compl_orig_text);
6583 compl_orig_text.length = (size_t)compl_length;
6584 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006585 if (p_ic)
6586 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006587 if (compl_orig_text.string == NULL
6588 || ins_compl_add(compl_orig_text.string,
6589 (int)compl_orig_text.length,
6590 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006591 {
John Marriott5e6ea922024-11-23 14:01:57 +01006592 VIM_CLEAR_STRING(compl_pattern);
6593 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006594 return FAIL;
6595 }
6596
6597 // showmode might reset the internal line pointers, so it must
6598 // be called before line = ml_get(), or when this address is no
6599 // longer needed. -- Acevedo.
6600 edit_submode_extra = (char_u *)_("-- Searching...");
6601 edit_submode_highl = HLF_COUNT;
6602 showmode();
6603 edit_submode_extra = NULL;
6604 out_flush();
6605
6606 return OK;
6607}
6608
6609/*
6610 * display the completion status message
6611 */
6612 static void
6613ins_compl_show_statusmsg(void)
6614{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006615 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006616 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006617 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006618 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006619 ? (char_u *)_("Hit end of paragraph")
6620 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006621 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006622 }
6623
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006624 if (edit_submode_extra == NULL)
6625 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006626 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006627 {
6628 edit_submode_extra = (char_u *)_("Back at original");
6629 edit_submode_highl = HLF_W;
6630 }
6631 else if (compl_cont_status & CONT_S_IPOS)
6632 {
6633 edit_submode_extra = (char_u *)_("Word from other line");
6634 edit_submode_highl = HLF_COUNT;
6635 }
6636 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6637 {
6638 edit_submode_extra = (char_u *)_("The only match");
6639 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006640 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006641 }
6642 else
6643 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006644#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006645 // Update completion sequence number when needed.
6646 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006647 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006648#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006649 // The match should always have a sequence number now, this is
6650 // just a safety check.
6651 if (compl_curr_match->cp_number != -1)
6652 {
6653 // Space for 10 text chars. + 2x10-digit no.s = 31.
6654 // Translations may need more than twice that.
6655 static char_u match_ref[81];
6656
6657 if (compl_matches > 0)
6658 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006659 _("match %d of %d"),
6660 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006661 else
6662 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006663 _("match %d"),
6664 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006665 edit_submode_extra = match_ref;
6666 edit_submode_highl = HLF_R;
6667 if (dollar_vcol >= 0)
6668 curs_columns(FALSE);
6669 }
6670 }
6671 }
6672
6673 // Show a message about what (completion) mode we're in.
6674 if (!compl_opt_suppress_empty)
6675 {
6676 showmode();
6677 if (!shortmess(SHM_COMPLETIONMENU))
6678 {
6679 if (edit_submode_extra != NULL)
6680 {
6681 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006682 {
6683 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006684 msg_attr((char *)edit_submode_extra,
6685 edit_submode_highl < HLF_COUNT
6686 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006687 msg_hist_off = FALSE;
6688 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006689 }
6690 else
6691 msg_clr_cmdline(); // necessary for "noshowmode"
6692 }
6693 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006694}
6695
6696/*
6697 * Do Insert mode completion.
6698 * Called when character "c" was typed, which has a meaning for completion.
6699 * Returns OK if completion was done, FAIL if something failed (out of mem).
6700 */
6701 int
6702ins_complete(int c, int enable_pum)
6703{
6704 int n;
6705 int save_w_wrow;
6706 int save_w_leftcol;
6707 int insert_match;
6708
6709 compl_direction = ins_compl_key2dir(c);
6710 insert_match = ins_compl_use_match(c);
6711
6712 if (!compl_started)
6713 {
6714 if (ins_compl_start() == FAIL)
6715 return FAIL;
6716 }
6717 else if (insert_match && stop_arrow() == FAIL)
6718 return FAIL;
6719
glepnircf7f0122025-04-15 19:02:00 +02006720 compl_curr_win = curwin;
6721 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006722 compl_shown_match = compl_curr_match;
6723 compl_shows_dir = compl_direction;
6724
6725 // Find next match (and following matches).
6726 save_w_wrow = curwin->w_wrow;
6727 save_w_leftcol = curwin->w_leftcol;
6728 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6729
6730 // may undisplay the popup menu
6731 ins_compl_upd_pum();
6732
6733 if (n > 1) // all matches have been found
6734 compl_matches = n;
6735 compl_curr_match = compl_shown_match;
6736 compl_direction = compl_shows_dir;
6737
6738 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6739 // mode.
6740 if (got_int && !global_busy)
6741 {
6742 (void)vgetc();
6743 got_int = FALSE;
6744 }
6745
6746 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006747 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006748 {
6749 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6750 // because we couldn't expand anything at first place, but if we used
6751 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6752 // (such as M in M'exico) if not tried already. -- Acevedo
6753 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006754 || compl_status_adding()
6755 || (ctrl_x_mode_not_default()
6756 && !ctrl_x_mode_path_patterns()
6757 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006758 compl_cont_status &= ~CONT_N_ADDS;
6759 }
6760
6761 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6762 compl_cont_status |= CONT_S_IPOS;
6763 else
6764 compl_cont_status &= ~CONT_S_IPOS;
6765
6766 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006767
6768 // Show the popup menu, unless we got interrupted.
6769 if (enable_pum && !compl_interrupted)
6770 show_pum(save_w_wrow, save_w_leftcol);
6771
6772 compl_was_interrupted = compl_interrupted;
6773 compl_interrupted = FALSE;
6774
6775 return OK;
6776}
6777
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006778/*
6779 * Remove (if needed) and show the popup menu
6780 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006781 static void
6782show_pum(int prev_w_wrow, int prev_w_leftcol)
6783{
6784 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006785 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006786 RedrawingDisabled = 0;
6787
6788 // If the cursor moved or the display scrolled we need to remove the pum
6789 // first.
6790 setcursor();
6791 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6792 ins_compl_del_pum();
6793
6794 ins_compl_show_pum();
6795 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006796
6797 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006798}
6799
6800/*
6801 * Looks in the first "len" chars. of "src" for search-metachars.
6802 * If dest is not NULL the chars. are copied there quoting (with
6803 * a backslash) the metachars, and dest would be NUL terminated.
6804 * Returns the length (needed) of dest
6805 */
6806 static unsigned
6807quote_meta(char_u *dest, char_u *src, int len)
6808{
6809 unsigned m = (unsigned)len + 1; // one extra for the NUL
6810
6811 for ( ; --len >= 0; src++)
6812 {
6813 switch (*src)
6814 {
6815 case '.':
6816 case '*':
6817 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006818 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006819 break;
6820 // FALLTHROUGH
6821 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006822 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006823 break;
6824 // FALLTHROUGH
6825 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006826 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006827 break;
6828 // FALLTHROUGH
6829 case '^': // currently it's not needed.
6830 case '$':
6831 m++;
6832 if (dest != NULL)
6833 *dest++ = '\\';
6834 break;
6835 }
6836 if (dest != NULL)
6837 *dest++ = *src;
6838 // Copy remaining bytes of a multibyte character.
6839 if (has_mbyte)
6840 {
glepnir19e1dd62025-05-08 22:50:38 +02006841 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006842 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006843 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006844 {
6845 --len;
6846 ++src;
6847 if (dest != NULL)
6848 *dest++ = *src;
6849 }
6850 }
6851 }
6852 if (dest != NULL)
6853 *dest = NUL;
6854
6855 return m;
6856}
6857
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006858#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006859 void
6860free_insexpand_stuff(void)
6861{
John Marriott5e6ea922024-11-23 14:01:57 +01006862 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006863# ifdef FEAT_EVAL
6864 free_callback(&cfu_cb);
6865 free_callback(&ofu_cb);
6866 free_callback(&tsrfu_cb);
6867# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006868}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006869#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006870
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006871#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006872/*
6873 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6874 * spelled word, if there is one.
6875 */
6876 static void
6877spell_back_to_badword(void)
6878{
6879 pos_T tpos = curwin->w_cursor;
6880
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006881 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006882 if (curwin->w_cursor.col != tpos.col)
6883 start_arrow(&tpos);
6884}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006885#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006886
6887/*
6888 * Reset the info associated with completion sources.
6889 */
6890 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006891cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006892{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006893 VIM_CLEAR(cpt_sources_array);
6894 cpt_sources_index = -1;
6895 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006896}
6897
6898/*
Girish Palya98c29db2025-06-01 19:40:00 +02006899 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006900 */
6901 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006902setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006903{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006904 char_u buf[LSIZE];
6905 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006906 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006907 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006908
Girish Palya0ac1eb32025-04-16 20:18:33 +02006909 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006910 {
6911 while (*p == ',' || *p == ' ') // Skip delimiters
6912 p++;
6913 if (*p) // If not end of string, count this segment
6914 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006915 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006916 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006917 }
6918 }
Girish Palya98c29db2025-06-01 19:40:00 +02006919 if (count == 0)
6920 return OK;
6921
Girish Palya0ac1eb32025-04-16 20:18:33 +02006922 cpt_sources_clear();
6923 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006924 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6925 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006926 {
Girish Palya98c29db2025-06-01 19:40:00 +02006927 cpt_sources_count = 0;
6928 return FAIL;
6929 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006930
Girish Palya98c29db2025-06-01 19:40:00 +02006931 for (p = curbuf->b_p_cpt; *p;)
6932 {
6933 while (*p == ',' || *p == ' ') // Skip delimiters
6934 p++;
6935 if (*p) // If not end of string, count this segment
6936 {
6937 char_u *t;
6938
6939 vim_memset(buf, 0, LSIZE);
6940 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6941 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6942 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
6943 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006944 }
Girish Palyacbe53192025-04-14 22:13:15 +02006945 }
6946 return OK;
6947}
6948
6949/*
6950 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6951 */
6952 static int
6953is_cpt_func_refresh_always(void)
6954{
6955#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006956 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02006957 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006958 return TRUE;
6959#endif
6960 return FALSE;
6961}
6962
6963/*
6964 * Make the completion list non-cyclic.
6965 */
6966#ifdef FEAT_COMPL_FUNC
6967 static void
6968ins_compl_make_linear(void)
6969{
6970 compl_T *m;
6971
6972 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6973 return;
6974 m = compl_first_match->cp_prev;
6975 m->cp_next = NULL;
6976 compl_first_match->cp_prev = NULL;
6977}
6978#endif
6979
6980/*
6981 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006982 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006983 */
6984#ifdef FEAT_COMPL_FUNC
6985 static compl_T *
6986remove_old_matches(void)
6987{
6988 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6989 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006990 int compl_shown_removed = FALSE;
6991 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6992
6993 compl_direction = forward ? FORWARD : BACKWARD;
6994 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006995
6996 // Identify the sublist of old matches that needs removal
6997 for (current = compl_first_match; current != NULL; current = current->cp_next)
6998 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006999 if (current->cp_cpt_source_idx < cpt_sources_index &&
7000 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02007001 insert_at = current;
7002
Girish Palya0ac1eb32025-04-16 20:18:33 +02007003 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02007004 {
7005 if (!sublist_start)
7006 sublist_start = current;
7007 sublist_end = current;
7008 if (!compl_shown_removed && compl_shown_match == current)
7009 compl_shown_removed = TRUE;
7010 }
7011
Girish Palya0ac1eb32025-04-16 20:18:33 +02007012 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
7013 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02007014 break;
7015 }
7016
7017 // Re-assign compl_shown_match if necessary
7018 if (compl_shown_removed)
7019 {
7020 if (forward)
7021 compl_shown_match = compl_first_match;
7022 else
7023 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02007024 for (current = compl_first_match; current->cp_next != NULL;
7025 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02007026 ;
7027 compl_shown_match = current;
7028 }
7029 }
7030
7031 if (!sublist_start) // No nodes to remove
7032 return insert_at;
7033
7034 // Update links to remove sublist
7035 if (sublist_start->cp_prev)
7036 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
7037 else
7038 compl_first_match = sublist_end->cp_next;
7039
7040 if (sublist_end->cp_next)
7041 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
7042
7043 // Free all nodes in the sublist
7044 sublist_end->cp_next = NULL;
7045 for (current = sublist_start; current != NULL; current = next)
7046 {
7047 next = current->cp_next;
7048 ins_compl_item_free(current);
7049 }
7050
7051 return insert_at;
7052}
7053#endif
7054
7055/*
7056 * Retrieve completion matches using the callback function "cb" and store the
7057 * 'refresh:always' flag.
7058 */
7059#ifdef FEAT_COMPL_FUNC
7060 static void
7061get_cpt_func_completion_matches(callback_T *cb UNUSED)
7062{
Girish Palya98c29db2025-06-01 19:40:00 +02007063 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02007064
7065 VIM_CLEAR_STRING(cpt_compl_pattern);
Girish Palya98c29db2025-06-01 19:40:00 +02007066
7067 if (startcol == -2 || startcol == -3)
7068 return;
7069
7070 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02007071 {
7072 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02007073 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02007074 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02007075 compl_opt_refresh_always = FALSE;
7076 }
7077}
7078#endif
7079
7080/*
7081 * Retrieve completion matches from functions in the 'cpt' option where the
7082 * 'refresh:always' flag is set.
7083 */
7084 static void
7085cpt_compl_refresh(void)
7086{
7087#ifdef FEAT_COMPL_FUNC
7088 char_u *cpt;
7089 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007090 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007091 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007092
7093 // Make the completion list linear (non-cyclic)
7094 ins_compl_make_linear();
7095 // Make a copy of 'cpt' in case the buffer gets wiped out
7096 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007097 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007098
Girish Palya0ac1eb32025-04-16 20:18:33 +02007099 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007100 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007101 {
7102 while (*p == ',' || *p == ' ') // Skip delimiters
7103 p++;
7104
Girish Palya98c29db2025-06-01 19:40:00 +02007105 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007106 {
Girish Palya98c29db2025-06-01 19:40:00 +02007107 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007108 if (cb)
7109 {
7110 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007111 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7112 &startcol);
7113 if (ret == FAIL)
7114 {
7115 if (startcol == -3)
7116 cpt_sources_array[cpt_sources_index].cs_refresh_always
7117 = FALSE;
7118 else
7119 startcol = -2;
7120 }
7121 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7122 if (ret == OK)
7123 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007124 }
7125 }
7126
Girish Palya7c621052025-05-26 19:41:59 +02007127 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7128 if (may_advance_cpt_index(p))
7129 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007130 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007131 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007132
7133 vim_free(cpt);
7134 // Make the list cyclic
7135 compl_matches = ins_compl_make_cyclic();
7136#endif
7137}