blob: 33d00e0c6854ba0292f7410c32a5404cdcc854de [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
glepnir05460682025-05-26 18:23:27 +020041# define CTRL_X_REGISTER 18 // complete words from registers
Bram Moolenaar7591bb32019-03-30 13:53:47 +010042
43# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
44
45// Message for CTRL-X mode, index is ctrl_x_mode.
46static char *ctrl_x_msgs[] =
47{
48 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
glepnir05460682025-05-26 18:23:27 +020049 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010050 NULL, // CTRL_X_SCROLL: depends on state
51 N_(" Whole line completion (^L^N^P)"),
52 N_(" File name completion (^F^N^P)"),
53 N_(" Tag completion (^]^N^P)"),
54 N_(" Path pattern completion (^N^P)"),
55 N_(" Definition completion (^D^N^P)"),
56 NULL, // CTRL_X_FINISHED
57 N_(" Dictionary completion (^K^N^P)"),
58 N_(" Thesaurus completion (^T^N^P)"),
59 N_(" Command-line completion (^V^N^P)"),
60 N_(" User defined completion (^U^N^P)"),
61 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020062 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010063 N_(" Keyword Local completion (^N^P)"),
64 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020065 N_(" Command-line completion (^V^N^P)"),
glepnir05460682025-05-26 18:23:27 +020066 N_(" Register completion (^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010067};
68
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020069#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010070static char *ctrl_x_mode_names[] = {
Hirohito Higashi355db992025-04-28 18:07:02 +020071 "keyword",
72 "ctrl_x",
73 "scroll",
74 "whole_line",
75 "files",
76 "tags",
77 "path_patterns",
78 "path_defines",
79 "unknown", // CTRL_X_FINISHED
80 "dictionary",
81 "thesaurus",
82 "cmdline",
83 "function",
84 "omni",
85 "spell",
86 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
87 "eval",
88 "cmdline",
glepnir05460682025-05-26 18:23:27 +020089 "register",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010090};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020091#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010092
93/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010094 * Structure used to store one match for insert completion.
95 */
96typedef struct compl_S compl_T;
97struct compl_S
98{
99 compl_T *cp_next;
100 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +0100101 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +0100102 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200103 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100104#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100105 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100106#endif
glepnir0fe17f82024-10-08 22:26:44 +0200107 char_u *cp_fname; // file containing the match, allocated when
108 // cp_flags has CP_FREE_FNAME
109 int cp_flags; // CP_ values
110 int cp_number; // sequence number
Girish Palyab1565882025-04-15 20:16:00 +0200111 int cp_score; // fuzzy match score or proximity score
glepnird4088ed2024-12-31 10:55:22 +0100112 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200113 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200114 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palya0ac1eb32025-04-16 20:18:33 +0200115 int cp_cpt_source_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100116};
117
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200118// values for cp_flags
119# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
120# define CP_FREE_FNAME 2 // cp_fname is allocated
121# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
122# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
123# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200124# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100125
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126/*
127 * All the current matches are stored in a list.
128 * "compl_first_match" points to the start of the list.
129 * "compl_curr_match" points to the currently selected entry.
130 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200131 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000132 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100133 */
134static compl_T *compl_first_match = NULL;
135static compl_T *compl_curr_match = NULL;
136static compl_T *compl_shown_match = NULL;
137static compl_T *compl_old_match = NULL;
138
glepnirf31cfa22025-03-06 21:59:13 +0100139// list used to store the compl_T which have the max score
140// used for completefuzzycollect
141static compl_T **compl_best_matches = NULL;
142static int compl_num_bests = 0;
143// inserted a longest when completefuzzycollect enabled
144static int compl_cfc_longest_ins = FALSE;
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// After using a cursor key <Enter> selects a match in the popup menu,
147// otherwise it inserts a line break.
148static int compl_enter_selects = FALSE;
149
150// When "compl_leader" is not NULL only matches that start with this string
151// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100152static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100153
154static int compl_get_longest = FALSE; // put longest common string
155 // in compl_leader
156
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100157// Selected one of the matches. When FALSE the match was edited or using the
158// longest common string.
159static int compl_used_match;
160
161// didn't finish finding completions.
162static int compl_was_interrupted = FALSE;
163
164// Set when character typed while looking for matches and it means we should
165// stop looking for matches.
166static int compl_interrupted = FALSE;
167
168static int compl_restarting = FALSE; // don't insert match
169
170// When the first completion is done "compl_started" is set. When it's
171// FALSE the word to be completed must be located.
172static int compl_started = FALSE;
173
174// Which Ctrl-X mode are we in?
175static int ctrl_x_mode = CTRL_X_NORMAL;
176
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000177static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200178static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
179#ifdef FEAT_COMPL_FUNC
180static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
181#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100182static int compl_direction = FORWARD;
183static int compl_shows_dir = FORWARD;
184static int compl_pending = 0; // > 1 for postponed CTRL-N
185static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000186// Length in bytes of the text being completed (this is deleted to be replaced
187// by the match.)
188static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100189static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100190static colnr_T compl_col = 0; // column where the text starts
191 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100192static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100193static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100194 // completion started
195static int compl_cont_mode = 0;
196static expand_T compl_xp;
197
glepnircf7f0122025-04-15 19:02:00 +0200198static win_T *compl_curr_win = NULL; // win where completion is active
199static buf_T *compl_curr_buf = NULL; // buf where completion is active
200
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000201// List of flags for method of completion.
202static int compl_cont_status = 0;
203# define CONT_ADDING 1 // "normal" or "adding" expansion
204# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
205 // it's set only iff N_ADDS is set
206# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
207# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
208 // if so, word-wise-expansion will set SOL
209# define CONT_SOL 16 // pattern includes start of line, just for
210 // word-wise expansion, not set for ^X^L
211# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
212 // expansion, (eg use complete=.)
213
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100214static int compl_opt_refresh_always = FALSE;
215static int compl_opt_suppress_empty = FALSE;
216
glepnira218cc62024-06-03 19:32:39 +0200217static int compl_selected_item = -1;
218
glepnir8159fb12024-07-17 20:32:54 +0200219static int *compl_fuzzy_scores;
220
Girish Palya0ac1eb32025-04-16 20:18:33 +0200221// Define the structure for completion source (in 'cpt' option) information
222typedef struct cpt_source_T
223{
Girish Palya98c29db2025-06-01 19:40:00 +0200224 int cs_refresh_always; // Whether 'refresh:always' is set for func
225 int cs_startcol; // Start column returned by func
226 int cs_max_matches; // Max items to display from this source
Girish Palya0ac1eb32025-04-16 20:18:33 +0200227} cpt_source_T;
228
229static cpt_source_T *cpt_sources_array; // Pointer to the array of completion sources
230static int cpt_sources_count; // Total number of completion sources specified in the 'cpt' option
Girish Palya7c621052025-05-26 19:41:59 +0200231static int cpt_sources_index = -1; // Index of the current completion source being expanded
Girish Palyacbe53192025-04-14 22:13:15 +0200232
glepnir6a38aff2024-12-16 21:56:16 +0100233// "compl_match_array" points the currently displayed list of entries in the
234// popup menu. It is NULL when there is no popup menu.
235static pumitem_T *compl_match_array = NULL;
236static int compl_match_arraysize;
237
glepnirf31cfa22025-03-06 21:59:13 +0100238static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup, int *user_hl, int score);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100239static void ins_compl_longest_match(compl_T *match);
240static void ins_compl_del_pum(void);
241static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100243static int ins_compl_need_restart(void);
244static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000245static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100246static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100247static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100248static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
249# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
250static void ins_compl_add_list(list_T *list);
251static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200252static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
Girish Palyacbe53192025-04-14 22:13:15 +0200253static void get_cpt_func_completion_matches(callback_T *cb);
Girish Palya98c29db2025-06-01 19:40:00 +0200254static callback_T *get_callback_if_cpt_func(char_u *p);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100255# endif
Girish Palya98c29db2025-06-01 19:40:00 +0200256static int setup_cpt_sources(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200257static int is_cpt_func_refresh_always(void);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200258static void cpt_sources_clear(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200259static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100260static int ins_compl_key2dir(int c);
261static int ins_compl_pum_key(int c);
262static int ins_compl_key2count(int c);
263static void show_pum(int prev_w_wrow, int prev_w_leftcol);
264static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100265static int ins_compl_has_multiple(void);
266static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100267static void ins_compl_longest_insert(char_u *prefix);
Girish Palya8cd42a52025-06-05 21:04:29 +0200268static void ins_compl_make_linear(void);
269static int ins_compl_make_cyclic(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100270
271#ifdef FEAT_SPELL
272static void spell_back_to_badword(void);
273static int spell_bad_len = 0; // length of located bad word
274#endif
275
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100276/*
277 * CTRL-X pressed in Insert mode.
278 */
279 void
280ins_ctrl_x(void)
281{
zeertzjqdca29d92021-08-31 19:12:51 +0200282 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100283 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000284 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100285 if (compl_cont_status & CONT_N_ADDS)
286 compl_cont_status |= CONT_INTRPT;
287 else
288 compl_cont_status = 0;
289 // We're not sure which CTRL-X mode it will be yet
290 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
291 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
292 edit_submode_pre = NULL;
293 showmode();
294 }
zeertzjqdca29d92021-08-31 19:12:51 +0200295 else
296 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
297 // CTRL-V look like CTRL-N
298 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100299
LemonBoy2bf52dd2022-04-09 18:17:34 +0100300 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301}
302
303/*
304 * Functions to check the current CTRL-X mode.
305 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000306int ctrl_x_mode_none(void)
307 { return ctrl_x_mode == 0; }
308int ctrl_x_mode_normal(void)
309 { return ctrl_x_mode == CTRL_X_NORMAL; }
310int ctrl_x_mode_scroll(void)
311 { return ctrl_x_mode == CTRL_X_SCROLL; }
312int ctrl_x_mode_whole_line(void)
313 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
314int ctrl_x_mode_files(void)
315 { return ctrl_x_mode == CTRL_X_FILES; }
316int ctrl_x_mode_tags(void)
317 { return ctrl_x_mode == CTRL_X_TAGS; }
318int ctrl_x_mode_path_patterns(void)
319 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
320int ctrl_x_mode_path_defines(void)
321 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
322int ctrl_x_mode_dictionary(void)
323 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
324int ctrl_x_mode_thesaurus(void)
325 { return ctrl_x_mode == CTRL_X_THESAURUS; }
326int ctrl_x_mode_cmdline(void)
327 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200328 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000329int ctrl_x_mode_function(void)
330 { return ctrl_x_mode == CTRL_X_FUNCTION; }
331int ctrl_x_mode_omni(void)
332 { return ctrl_x_mode == CTRL_X_OMNI; }
333int ctrl_x_mode_spell(void)
334 { return ctrl_x_mode == CTRL_X_SPELL; }
335static int ctrl_x_mode_eval(void)
336 { return ctrl_x_mode == CTRL_X_EVAL; }
337int ctrl_x_mode_line_or_eval(void)
338 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
glepnir05460682025-05-26 18:23:27 +0200339int ctrl_x_mode_register(void)
340 { return ctrl_x_mode == CTRL_X_REGISTER; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100341
342/*
343 * Whether other than default completion has been selected.
344 */
345 int
346ctrl_x_mode_not_default(void)
347{
348 return ctrl_x_mode != CTRL_X_NORMAL;
349}
350
351/*
zeertzjqdca29d92021-08-31 19:12:51 +0200352 * Whether CTRL-X was typed without a following character,
353 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100354 */
355 int
356ctrl_x_mode_not_defined_yet(void)
357{
358 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
359}
360
361/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000362 * Return TRUE if currently in "normal" or "adding" insert completion matches
363 * state
364 */
365 int
366compl_status_adding(void)
367{
368 return compl_cont_status & CONT_ADDING;
369}
370
371/*
372 * Return TRUE if the completion pattern includes start of line, just for
373 * word-wise expansion.
374 */
375 int
376compl_status_sol(void)
377{
378 return compl_cont_status & CONT_SOL;
379}
380
381/*
382 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
383 */
384 int
385compl_status_local(void)
386{
387 return compl_cont_status & CONT_LOCAL;
388}
389
390/*
391 * Clear the completion status flags
392 */
393 void
394compl_status_clear(void)
395{
396 compl_cont_status = 0;
397}
398
399/*
400 * Return TRUE if completion is using the forward direction matches
401 */
402 static int
403compl_dir_forward(void)
404{
405 return compl_direction == FORWARD;
406}
407
408/*
409 * Return TRUE if currently showing forward completion matches
410 */
411 static int
412compl_shows_dir_forward(void)
413{
414 return compl_shows_dir == FORWARD;
415}
416
417/*
418 * Return TRUE if currently showing backward completion matches
419 */
420 static int
421compl_shows_dir_backward(void)
422{
423 return compl_shows_dir == BACKWARD;
424}
425
426/*
427 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100428 */
429 int
430has_compl_option(int dict_opt)
431{
432 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200433#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200435#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100436 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100437 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
438#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100439 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100440#endif
441 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100442 {
443 ctrl_x_mode = CTRL_X_NORMAL;
444 edit_submode = NULL;
445 msg_attr(dict_opt ? _("'dictionary' option is empty")
446 : _("'thesaurus' option is empty"),
447 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100448 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100449 {
450 vim_beep(BO_COMPL);
451 setcursor();
452 out_flush();
453#ifdef FEAT_EVAL
454 if (!get_vim_var_nr(VV_TESTING))
455#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100456 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100457 }
458 return FALSE;
459 }
460 return TRUE;
461}
462
463/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000464 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100465 * This depends on the current mode.
466 */
467 int
468vim_is_ctrl_x_key(int c)
469{
470 // Always allow ^R - let its results then be checked
glepnir05460682025-05-26 18:23:27 +0200471 if (c == Ctrl_R && ctrl_x_mode != CTRL_X_REGISTER)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100472 return TRUE;
473
474 // Accept <PageUp> and <PageDown> if the popup menu is visible.
475 if (ins_compl_pum_key(c))
476 return TRUE;
477
478 switch (ctrl_x_mode)
479 {
480 case 0: // Not in any CTRL-X mode
481 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
482 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200483 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100484 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
485 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
486 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
487 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
488 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200489 || c == Ctrl_S || c == Ctrl_K || c == 's'
glepnir05460682025-05-26 18:23:27 +0200490 || c == Ctrl_Z || c == Ctrl_R);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100491 case CTRL_X_SCROLL:
492 return (c == Ctrl_Y || c == Ctrl_E);
493 case CTRL_X_WHOLE_LINE:
494 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
495 case CTRL_X_FILES:
496 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
497 case CTRL_X_DICTIONARY:
498 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
499 case CTRL_X_THESAURUS:
500 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
501 case CTRL_X_TAGS:
502 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
503#ifdef FEAT_FIND_ID
504 case CTRL_X_PATH_PATTERNS:
505 return (c == Ctrl_P || c == Ctrl_N);
506 case CTRL_X_PATH_DEFINES:
507 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
508#endif
509 case CTRL_X_CMDLINE:
510 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
511 || c == Ctrl_X);
512#ifdef FEAT_COMPL_FUNC
513 case CTRL_X_FUNCTION:
514 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
515 case CTRL_X_OMNI:
516 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
517#endif
518 case CTRL_X_SPELL:
519 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
520 case CTRL_X_EVAL:
521 return (c == Ctrl_P || c == Ctrl_N);
glepnir05460682025-05-26 18:23:27 +0200522 case CTRL_X_REGISTER:
523 return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100524 }
525 internal_error("vim_is_ctrl_x_key()");
526 return FALSE;
527}
528
529/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000530 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000531 */
532 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000533match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000534{
535 return match->cp_flags & CP_ORIGINAL_TEXT;
536}
537
538/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000539 * Returns TRUE if "match" is the first match in the completion list.
540 */
541 static int
542is_first_match(compl_T *match)
543{
544 return match == compl_first_match;
545}
546
547/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100548 * Return TRUE when character "c" is part of the item currently being
549 * completed. Used to decide whether to abandon complete mode when the menu
550 * is visible.
551 */
552 int
553ins_compl_accept_char(int c)
554{
555 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
556 // When expanding an identifier only accept identifier chars.
557 return vim_isIDc(c);
558
559 switch (ctrl_x_mode)
560 {
561 case CTRL_X_FILES:
562 // When expanding file name only accept file name chars. But not
563 // path separators, so that "proto/<Tab>" expands files in
564 // "proto", not "proto/" as a whole
565 return vim_isfilec(c) && !vim_ispathsep(c);
566
567 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200568 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100569 case CTRL_X_OMNI:
570 // Command line and Omni completion can work with just about any
571 // printable character, but do stop at white space.
572 return vim_isprintc(c) && !VIM_ISWHITE(c);
573
574 case CTRL_X_WHOLE_LINE:
575 // For while line completion a space can be part of the line.
576 return vim_isprintc(c);
577 }
578 return vim_iswordc(c);
579}
580
581/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100583 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000584 */
585 static char_u *
586ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200587 char_u *str,
588 int char_len,
589 int compl_char_len,
590 int min_len,
591 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000592{
593 int *wca; // Wide character array.
594 char_u *p;
595 int i, c;
596 int has_lower = FALSE;
597 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100598 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000599
600 IObuff[0] = NUL;
601
602 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100603 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000604 if (wca == NULL)
605 return IObuff;
606
607 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100608 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100609 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000610 if (has_mbyte)
611 wca[i] = mb_ptr2char_adv(&p);
612 else
613 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100614 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000615
616 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100617 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000618 for (i = 0; i < min_len; ++i)
619 {
glepnir6e199932024-12-14 21:13:27 +0100620 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000621 if (MB_ISLOWER(c))
622 {
623 has_lower = TRUE;
624 if (MB_ISUPPER(wca[i]))
625 {
626 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100627 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000628 wca[i] = MB_TOLOWER(wca[i]);
629 break;
630 }
631 }
632 }
633
634 // Rule 2: No lower case, 2nd consecutive letter converted to
635 // upper case.
636 if (!has_lower)
637 {
John Marriott5e6ea922024-11-23 14:01:57 +0100638 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000639 for (i = 0; i < min_len; ++i)
640 {
glepnir6e199932024-12-14 21:13:27 +0100641 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000642 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
643 {
644 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100645 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000646 wca[i] = MB_TOUPPER(wca[i]);
647 break;
648 }
649 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
650 }
651 }
652
653 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100654 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000655 for (i = 0; i < min_len; ++i)
656 {
glepnir6e199932024-12-14 21:13:27 +0100657 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000658 if (MB_ISLOWER(c))
659 wca[i] = MB_TOLOWER(wca[i]);
660 else if (MB_ISUPPER(c))
661 wca[i] = MB_TOUPPER(wca[i]);
662 }
663
664 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000665 p = IObuff;
666 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100667 ga_init2(&gap, 1, 500);
668 while (i < char_len)
669 {
670 if (gap.ga_data != NULL)
671 {
672 if (ga_grow(&gap, 10) == FAIL)
673 {
674 ga_clear(&gap);
675 return (char_u *)"[failed]";
676 }
677 p = (char_u *)gap.ga_data + gap.ga_len;
678 if (has_mbyte)
679 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
680 else
681 {
682 *p = wca[i++];
683 ++gap.ga_len;
684 }
685 }
686 else if ((p - IObuff) + 6 >= IOSIZE)
687 {
688 // Multi-byte characters can occupy up to five bytes more than
689 // ASCII characters, and we also need one byte for NUL, so when
690 // getting to six bytes from the edge of IObuff switch to using a
691 // growarray. Add the character in the next round.
692 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100693 {
694 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100696 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100697 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100699 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100700 }
701 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000702 p += (*mb_char2bytes)(wca[i++], p);
703 else
704 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100705 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000706 vim_free(wca);
707
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100708 if (gap.ga_data != NULL)
709 {
710 *tofree = gap.ga_data;
711 return gap.ga_data;
712 }
713
714 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000715 return IObuff;
716}
717
718/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
720 * case of the originally typed text is used, and the case of the completed
721 * text is inferred, ie this tries to work out what case you probably wanted
722 * the rest of the word to be in -- webb
723 */
724 int
725ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200726 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100727 int len,
728 int icase,
729 char_u *fname,
730 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100731 int cont_s_ipos, // next ^X<> will set initial_pos
732 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200734 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 int char_len; // count multi-byte characters
737 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100738 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200739 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 int res;
741 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742
743 if (p_ic && curbuf->b_p_inf && len > 0)
744 {
745 // Infer case of completed part.
746
747 // Find actual length of completion.
748 if (has_mbyte)
749 {
750 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100751 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752 while (*p != NUL)
753 {
754 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100755 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100756 }
757 }
758 else
glepnir6e199932024-12-14 21:13:27 +0100759 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100760 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100761 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762
763 // Find actual length of original text.
764 if (has_mbyte)
765 {
John Marriott5e6ea922024-11-23 14:01:57 +0100766 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100767 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100768 while (*p != NUL)
769 {
770 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100771 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100772 }
773 }
774 else
glepnir6e199932024-12-14 21:13:27 +0100775 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100776 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100777 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100778
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100779 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100781 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100782
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100783 str = ins_compl_infercase_gettext(str, char_len,
784 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100785 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200786 if (cont_s_ipos)
787 flags |= CP_CONT_S_IPOS;
788 if (icase)
789 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200790
glepnirf31cfa22025-03-06 21:59:13 +0100791 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100792 vim_free(tofree);
793 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100794}
795
796/*
glepnirf31cfa22025-03-06 21:59:13 +0100797 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
798 */
799 static int
800cfc_has_mode(void)
801{
glepnir58760162025-03-13 21:39:51 +0100802 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
803 return (cfc_flags & CFC_KEYWORD) != 0;
804 else if (ctrl_x_mode_files())
805 return (cfc_flags & CFC_FILES) != 0;
806 else if (ctrl_x_mode_whole_line())
807 return (cfc_flags & CFC_WHOLELINE) != 0;
808 else
809 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100810}
811
812/*
Girish Palyab1565882025-04-15 20:16:00 +0200813 * Returns TRUE if matches should be sorted based on proximity to the cursor.
814 */
815 static int
816is_nearest_active(void)
817{
glepnirc3fbaa02025-05-08 23:05:10 +0200818 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200819}
820
821/*
822 * Repositions a match in the completion list based on its proximity score.
823 * If the match is at the head and has a higher score than the next node,
824 * or if it's in the middle/tail and has a lower score than the previous node,
825 * it is moved to the correct position while maintaining ascending order.
826 */
827 static void
828reposition_match(compl_T *match)
829{
830 compl_T *insert_before = NULL;
831 compl_T *insert_after = NULL;
832
833 // Node is at head and score is too big
834 if (!match->cp_prev)
835 {
836 if (match->cp_next && match->cp_next->cp_score > 0 &&
837 match->cp_next->cp_score < match->cp_score)
838 {
839 // <c-p>: compl_first_match is at head and newly inserted node
840 compl_first_match = compl_curr_match = match->cp_next;
841 // Find the correct position in ascending order
842 insert_before = match->cp_next;
843 do
844 {
845 insert_after = insert_before;
846 insert_before = insert_before->cp_next;
847 } while (insert_before && insert_before->cp_score > 0 &&
848 insert_before->cp_score < match->cp_score);
849 }
850 else
851 return;
852 }
853 // Node is at tail or in the middle but score is too small
854 else
855 {
856 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
857 {
858 // <c-n>: compl_curr_match (and newly inserted match) is at tail
859 if (!match->cp_next)
860 compl_curr_match = compl_curr_match->cp_prev;
861 // Find the correct position in ascending order
862 insert_after = match->cp_prev;
863 do
864 {
865 insert_before = insert_after;
866 insert_after = insert_after->cp_prev;
867 } while (insert_after && insert_after->cp_score > 0 &&
868 insert_after->cp_score > match->cp_score);
869 }
870 else
871 return;
872 }
873
874 if (insert_after)
875 {
876 // Remove the match from its current position
877 if (match->cp_prev)
878 match->cp_prev->cp_next = match->cp_next;
879 else
880 compl_first_match = match->cp_next;
881 if (match->cp_next)
882 match->cp_next->cp_prev = match->cp_prev;
883
884 // Insert the match at the correct position
885 match->cp_next = insert_before;
886 match->cp_prev = insert_after;
887 insert_after->cp_next = match;
888 insert_before->cp_prev = match;
889 }
890}
891
892/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000893 * Add a match to the list of matches. The arguments are:
894 * str - text of the match to add
895 * len - length of "str". If -1, then the length of "str" is
896 * computed.
897 * fname - file name to associate with this match.
898 * cptext - list of strings to use with this match (for abbr, menu, info
899 * and kind)
900 * user_data - user supplied data (any vim type) for this match
901 * cdir - match direction. If 0, use "compl_direction".
902 * flags_arg - match flags (cp_flags)
903 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100904 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000905 * If "cdir" is FORWARD, then the match is added after the current match.
906 * Otherwise, it is added before the current match.
907 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100908 * If the given string is already in the list of completions, then return
909 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
910 * maybe because alloc() returns NULL, then FAIL is returned.
911 */
912 static int
913ins_compl_add(
914 char_u *str,
915 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100916 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100917 char_u **cptext, // extra text for popup menu or NULL
918 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100919 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200920 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200921 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100922 int *user_hl, // user abbr/kind hlattr
923 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100924{
glepnirf31cfa22025-03-06 21:59:13 +0100925 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200927 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100928 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100929
Bram Moolenaarceb06192021-04-04 15:05:22 +0200930 if (flags & CP_FAST)
931 fast_breakcheck();
932 else
933 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100934 if (got_int)
935 return FAIL;
936 if (len < 0)
937 len = (int)STRLEN(str);
938
939 // If the same match is already present, don't add it.
940 if (compl_first_match != NULL && !adup)
941 {
942 match = compl_first_match;
943 do
944 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000945 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100946 && STRNCMP(match->cp_str.string, str, len) == 0
947 && ((int)match->cp_str.length <= len
948 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200949 {
950 if (is_nearest_active() && score > 0 && score < match->cp_score)
951 {
952 match->cp_score = score;
953 reposition_match(match);
954 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100955 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200956 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100957 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000958 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100959 }
960
961 // Remove any popup menu before changing the list of matches.
962 ins_compl_del_pum();
963
964 // Allocate a new match structure.
965 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200966 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100967 if (match == NULL)
968 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100969 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100970 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100971 {
972 vim_free(match);
973 return FAIL;
974 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100975
John Marriott5e6ea922024-11-23 14:01:57 +0100976 match->cp_str.length = len;
977
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100978 // match-fname is:
979 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200980 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100981 // - NULL otherwise. --Acevedo
982 if (fname != NULL
983 && compl_curr_match != NULL
984 && compl_curr_match->cp_fname != NULL
985 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
986 match->cp_fname = compl_curr_match->cp_fname;
987 else if (fname != NULL)
988 {
989 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200990 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100991 }
992 else
993 match->cp_fname = NULL;
994 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100995 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
996 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100997 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200998 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100999
1000 if (cptext != NULL)
1001 {
glepnir19e1dd62025-05-08 22:50:38 +02001002 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +01001003 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001004 if (cptext[i] != NULL && *cptext[i] != NUL)
1005 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +01001006 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001007 }
Bram Moolenaarab782c52020-01-04 19:00:11 +01001008#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001009 if (user_data != NULL)
1010 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +01001011#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001012
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001013 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1014 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001015 if (compl_first_match == NULL)
1016 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001017 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1018 {
1019 current = compl_first_match->cp_next;
1020 prev = compl_first_match;
1021 inserted = FALSE;
1022 // The direction is ignored when using longest and
1023 // completefuzzycollect, because matches are inserted
1024 // and sorted by score.
1025 while (current != NULL && current != compl_first_match)
1026 {
1027 if (current->cp_score < score)
1028 {
Hirohito Higashi355db992025-04-28 18:07:02 +02001029 match->cp_next = current;
1030 match->cp_prev = current->cp_prev;
1031 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +01001032 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +02001033 current->cp_prev = match;
1034 inserted = TRUE;
1035 break;
glepnirf31cfa22025-03-06 21:59:13 +01001036 }
1037 prev = current;
1038 current = current->cp_next;
1039 }
1040 if (!inserted)
1041 {
1042 prev->cp_next = match;
1043 match->cp_prev = prev;
1044 match->cp_next = compl_first_match;
1045 compl_first_match->cp_prev = match;
1046 }
1047 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001048 else if (dir == FORWARD)
1049 {
1050 match->cp_next = compl_curr_match->cp_next;
1051 match->cp_prev = compl_curr_match;
1052 }
1053 else // BACKWARD
1054 {
1055 match->cp_next = compl_curr_match;
1056 match->cp_prev = compl_curr_match->cp_prev;
1057 }
1058 if (match->cp_next)
1059 match->cp_next->cp_prev = match;
1060 if (match->cp_prev)
1061 match->cp_prev->cp_next = match;
1062 else // if there's nothing before, it is the first match
1063 compl_first_match = match;
1064 compl_curr_match = match;
1065
Girish Palyab1565882025-04-15 20:16:00 +02001066 if (is_nearest_active() && score > 0)
1067 reposition_match(match);
1068
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001069 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001070 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001071 ins_compl_longest_match(match);
1072
1073 return OK;
1074}
1075
1076/*
1077 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001078 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001079 */
1080 static int
1081ins_compl_equal(compl_T *match, char_u *str, int len)
1082{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001083 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001084 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001085 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001086 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1087 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001088}
1089
1090/*
glepnir6a38aff2024-12-16 21:56:16 +01001091 * when len is -1 mean use whole length of p otherwise part of p
1092 */
1093 static void
1094ins_compl_insert_bytes(char_u *p, int len)
1095{
1096 if (len == -1)
1097 len = (int)STRLEN(p);
1098 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001099 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001100}
1101
1102/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001103 * Checks if the column is within the currently inserted completion text
1104 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001105 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001106 */
1107 int
glepnir76bdb822025-02-08 19:04:51 +01001108ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001109{
glepnir76bdb822025-02-08 19:04:51 +01001110 int start_col;
1111 int attr;
1112
1113 if ((get_cot_flags() & COT_FUZZY)
1114 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001115 return -1;
1116
glepnir76bdb822025-02-08 19:04:51 +01001117 start_col = compl_col + (int)ins_compl_leader_len();
1118 if (!ins_compl_has_multiple())
1119 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1120
1121 // Multiple lines
1122 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1123 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1124 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1125 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001126
1127 return -1;
1128}
1129
1130/*
glepnir76bdb822025-02-08 19:04:51 +01001131 * Returns TRUE if the current completion string contains newline characters,
1132 * indicating it's a multi-line completion.
1133 */
1134 static int
1135ins_compl_has_multiple(void)
1136{
1137 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1138}
1139
1140/*
1141 * Returns TRUE if the given line number falls within the range of a multi-line
1142 * completion, i.e. between the starting line (compl_lnum) and current cursor
1143 * line. Always returns FALSE for single-line completions.
1144 */
1145 int
1146ins_compl_lnum_in_range(linenr_T lnum)
1147{
1148 if (!ins_compl_has_multiple())
1149 return FALSE;
1150 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1151}
1152
1153/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001154 * Reduce the longest common string for match "match".
1155 */
1156 static void
1157ins_compl_longest_match(compl_T *match)
1158{
1159 char_u *p, *s;
1160 int c1, c2;
1161 int had_match;
1162
John Marriott5e6ea922024-11-23 14:01:57 +01001163 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001164 {
1165 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001166 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1167 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001168 return;
1169
John Marriott5e6ea922024-11-23 14:01:57 +01001170 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001171 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001172 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001173
1174 // When the match isn't there (to avoid matching itself) remove it
1175 // again after redrawing.
1176 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001177 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001178 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001179
1180 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001181 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001182
1183 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001184 p = compl_leader.string;
1185 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001186 while (*p != NUL)
1187 {
1188 if (has_mbyte)
1189 {
1190 c1 = mb_ptr2char(p);
1191 c2 = mb_ptr2char(s);
1192 }
1193 else
1194 {
1195 c1 = *p;
1196 c2 = *s;
1197 }
1198 if ((match->cp_flags & CP_ICASE)
1199 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1200 break;
1201 if (has_mbyte)
1202 {
1203 MB_PTR_ADV(p);
1204 MB_PTR_ADV(s);
1205 }
1206 else
1207 {
1208 ++p;
1209 ++s;
1210 }
1211 }
1212
1213 if (*p != NUL)
1214 {
1215 // Leader was shortened, need to change the inserted text.
1216 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001217 compl_leader.length = (size_t)(p - compl_leader.string);
1218
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001219 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001220 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001221
1222 // When the match isn't there (to avoid matching itself) remove it
1223 // again after redrawing.
1224 if (!had_match)
1225 ins_compl_delete();
1226 }
1227
1228 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001229}
1230
1231/*
1232 * Add an array of matches to the list of matches.
1233 * Frees matches[].
1234 */
1235 static void
1236ins_compl_add_matches(
1237 int num_matches,
1238 char_u **matches,
1239 int icase)
1240{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001241 int add_r = OK;
1242 int dir = compl_direction;
1243
glepnir19e1dd62025-05-08 22:50:38 +02001244 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001245 {
1246 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001247 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001248 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001249 // if dir was BACKWARD then honor it just once
1250 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001251 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001252 FreeWild(num_matches, matches);
1253}
1254
1255/*
1256 * Make the completion list cyclic.
1257 * Return the number of matches (excluding the original).
1258 */
1259 static int
1260ins_compl_make_cyclic(void)
1261{
1262 compl_T *match;
1263 int count = 0;
1264
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001265 if (compl_first_match == NULL)
1266 return 0;
1267
1268 // Find the end of the list.
1269 match = compl_first_match;
1270 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001271 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001272 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001273 match = match->cp_next;
1274 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001275 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001276 match->cp_next = compl_first_match;
1277 compl_first_match->cp_prev = match;
1278
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001279 return count;
1280}
1281
1282/*
1283 * Return whether there currently is a shown match.
1284 */
1285 int
1286ins_compl_has_shown_match(void)
1287{
1288 return compl_shown_match == NULL
1289 || compl_shown_match != compl_shown_match->cp_next;
1290}
1291
1292/*
1293 * Return whether the shown match is long enough.
1294 */
1295 int
1296ins_compl_long_shown_match(void)
1297{
John Marriott5e6ea922024-11-23 14:01:57 +01001298 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299 > curwin->w_cursor.col - compl_col;
1300}
1301
1302/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001304 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001305 unsigned int
1306get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001307{
zeertzjq529b9ad2024-06-05 20:27:06 +02001308 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001309}
1310
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001311/*
1312 * Update the screen and when there is any scrolling remove the popup menu.
1313 */
1314 static void
1315ins_compl_upd_pum(void)
1316{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001317 if (compl_match_array == NULL)
1318 return;
1319
glepnir19e1dd62025-05-08 22:50:38 +02001320 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001321 // Update the screen later, before drawing the popup menu over it.
1322 pum_call_update_screen();
1323 if (h != curwin->w_cline_height)
1324 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001325}
1326
1327/*
1328 * Remove any popup menu.
1329 */
1330 static void
1331ins_compl_del_pum(void)
1332{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001333 if (compl_match_array == NULL)
1334 return;
1335
1336 pum_undisplay();
1337 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001338}
1339
1340/*
1341 * Return TRUE if the popup menu should be displayed.
1342 */
1343 int
1344pum_wanted(void)
1345{
1346 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001347 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001348 return FALSE;
1349
1350 // The display looks bad on a B&W display.
1351 if (t_colors < 8
1352#ifdef FEAT_GUI
1353 && !gui.in_use
1354#endif
1355 )
1356 return FALSE;
1357 return TRUE;
1358}
1359
1360/*
1361 * Return TRUE if there are two or more matches to be shown in the popup menu.
1362 * One if 'completopt' contains "menuone".
1363 */
1364 static int
1365pum_enough_matches(void)
1366{
1367 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001368 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001369
1370 // Don't display the popup menu if there are no matches or there is only
1371 // one (ignoring the original text).
1372 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001373 do
1374 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001375 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001376 break;
1377 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001378 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001379
zeertzjq529b9ad2024-06-05 20:27:06 +02001380 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001381 return (i >= 1);
1382 return (i >= 2);
1383}
1384
Bram Moolenaar3075a452021-11-17 15:51:52 +00001385#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001386/*
1387 * Allocate Dict for the completed item.
1388 * { word, abbr, menu, kind, info }
1389 */
1390 static dict_T *
1391ins_compl_dict_alloc(compl_T *match)
1392{
1393 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1394
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001395 if (dict == NULL)
1396 return NULL;
1397
John Marriott5e6ea922024-11-23 14:01:57 +01001398 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001399 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1400 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1401 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1402 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1403 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1404 dict_add_string(dict, "user_data", (char_u *)"");
1405 else
1406 dict_add_tv(dict, "user_data", &match->cp_user_data);
1407
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001408 return dict;
1409}
1410
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001411/*
1412 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1413 * completion menu is changed.
1414 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001415 static void
1416trigger_complete_changed_event(int cur)
1417{
1418 dict_T *v_event;
1419 dict_T *item;
1420 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001421 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001422
1423 if (recursive)
1424 return;
1425
glepnir40891ba2025-02-10 22:18:00 +01001426 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001427 if (item == NULL)
1428 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001429 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001430 dict_add_dict(v_event, "completed_item", item);
1431 pum_set_event_info(v_event);
1432 dict_set_items_ro(v_event);
1433
1434 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001435 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001436 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001437 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001438 recursive = FALSE;
1439
Bram Moolenaar3075a452021-11-17 15:51:52 +00001440 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001441}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001442#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001443
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001444/*
Girish Palya8cd42a52025-06-05 21:04:29 +02001445 * Helper functions for mergesort_list().
Girish Palya19ef6b02025-05-28 20:28:21 +02001446 */
Girish Palya8cd42a52025-06-05 21:04:29 +02001447 static void*
1448cp_get_next(void *node)
Girish Palya19ef6b02025-05-28 20:28:21 +02001449{
Girish Palya8cd42a52025-06-05 21:04:29 +02001450 return ((compl_T*)node)->cp_next;
Girish Palya19ef6b02025-05-28 20:28:21 +02001451}
1452
Girish Palya8cd42a52025-06-05 21:04:29 +02001453 static void
1454cp_set_next(void *node, void *next)
glepnira218cc62024-06-03 19:32:39 +02001455{
Girish Palya8cd42a52025-06-05 21:04:29 +02001456 ((compl_T*)node)->cp_next = (compl_T*)next;
1457}
1458
1459 static void*
1460cp_get_prev(void* node)
1461{
1462 return ((compl_T*)node)->cp_prev;
1463}
1464
1465 static void
1466cp_set_prev(void* node, void* prev)
1467{
1468 ((compl_T*)node)->cp_prev = (compl_T*)prev;
1469}
1470
1471 static int
1472cp_compare_fuzzy(const void* a, const void* b)
1473{
1474 int score_a = ((compl_T*)a)->cp_score;
1475 int score_b = ((compl_T*)b)->cp_score;
1476 return (score_b > score_a) ? 1 : (score_b < score_a) ? -1 : 0;
glepnira218cc62024-06-03 19:32:39 +02001477}
1478
1479/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001480 * Build a popup menu to show the completion matches.
1481 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1482 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001483 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001484 static int
1485ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001486{
1487 compl_T *compl;
1488 compl_T *shown_compl = NULL;
1489 int did_find_shown_match = FALSE;
1490 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001491 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001492 int cur = -1;
zeertzjqaa925ee2024-06-09 18:24:05 +02001493 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001494 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001495 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1496 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001497 compl_T *match_head = NULL;
1498 compl_T *match_tail = NULL;
1499 compl_T *match_next = NULL;
Girish Palya8cd42a52025-06-05 21:04:29 +02001500 int *match_count = NULL;
Girish Palya19ef6b02025-05-28 20:28:21 +02001501 int is_forward = compl_shows_dir_forward();
Girish Palya8cd42a52025-06-05 21:04:29 +02001502 int is_cpt_completion = (cpt_sources_array != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001503
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001504 // Need to build the popup menu list.
1505 compl_match_arraysize = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001506
glepnira49c0772024-11-30 10:56:30 +01001507 // If the current match is the original text don't find the first
1508 // match after it, don't highlight anything.
1509 if (match_at_original_text(compl_shown_match))
1510 shown_match_ok = TRUE;
1511
1512 if (compl_leader.string != NULL
1513 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1514 && shown_match_ok == FALSE)
1515 compl_shown_match = compl_no_select ? compl_first_match
1516 : compl_first_match->cp_next;
1517
Girish Palya8cd42a52025-06-05 21:04:29 +02001518 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1519 // set the cp_score for later comparisons.
1520 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
1521 {
1522 compl = compl_first_match;
1523 do
1524 {
1525 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
1526 compl = compl->cp_next;
1527 } while (compl != NULL && !is_first_match(compl));
1528 }
1529
1530 // Sort the linked list based on fuzzy score
1531 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0
1532 && !is_first_match(compl_first_match->cp_next))
1533 {
1534 compl = compl_first_match->cp_prev;
1535 ins_compl_make_linear();
1536 if (is_forward)
1537 {
1538 compl_first_match->cp_next->cp_prev = NULL;
1539 compl_first_match->cp_next = mergesort_list(compl_first_match->cp_next, cp_get_next,
1540 cp_set_next, cp_get_prev, cp_set_prev, cp_compare_fuzzy);
1541 compl_first_match->cp_next->cp_prev = compl_first_match;
1542 }
1543 else
1544 {
1545 compl->cp_prev->cp_next = NULL;
1546 compl_first_match = mergesort_list(compl_first_match, cp_get_next,
1547 cp_set_next, cp_get_prev, cp_set_prev, cp_compare_fuzzy);
1548 compl_T *tail = compl_first_match;
1549 while (tail->cp_next != NULL)
1550 tail = tail->cp_next;
1551 tail->cp_next = compl;
1552 compl->cp_prev = tail;
1553 }
1554 (void)ins_compl_make_cyclic();
1555 }
1556
1557 if (is_cpt_completion)
1558 {
1559 match_count = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1560 if (match_count == NULL)
1561 return -1;
1562 }
1563
1564 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001565 do
1566 {
glepnird4088ed2024-12-31 10:55:22 +01001567 compl->cp_in_match_array = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001568
Girish Palyadc314052025-05-08 23:28:52 +02001569 // Apply 'smartcase' behavior during normal mode
1570 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1571 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1572 compl->cp_flags &= ~CP_ICASE;
1573
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001574 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001575 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001576 || ins_compl_equal(compl, compl_leader.string,
1577 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001578 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001579 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001580 // Limit number of items from each source if max_items is set.
1581 int match_limit_exceeded = FALSE;
1582 int cur_source = compl->cp_cpt_source_idx;
1583 if (is_forward && cur_source != -1 && is_cpt_completion)
glepnira49c0772024-11-30 10:56:30 +01001584 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001585 match_count[cur_source]++;
1586 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
1587 if (max_matches > 0 && match_count[cur_source] > max_matches)
1588 match_limit_exceeded = TRUE;
1589 }
1590
1591 if (!match_limit_exceeded)
1592 {
1593 ++compl_match_arraysize;
1594 compl->cp_in_match_array = TRUE;
1595 if (match_head == NULL)
1596 match_head = compl;
glepnira49c0772024-11-30 10:56:30 +01001597 else
Girish Palya8cd42a52025-06-05 21:04:29 +02001598 match_tail->cp_match_next = compl;
1599 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001600
Girish Palya8cd42a52025-06-05 21:04:29 +02001601 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001602 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001603 if (compl == compl_shown_match || did_find_shown_match)
1604 {
1605 // This item is the shown match or this is the
1606 // first displayed item after the shown match.
1607 compl_shown_match = compl;
1608 did_find_shown_match = TRUE;
1609 shown_match_ok = TRUE;
1610 }
1611 else
1612 // Remember this displayed match for when the
1613 // shown match is just below it.
1614 shown_compl = compl;
glepnira49c0772024-11-30 10:56:30 +01001615 cur = i;
glepnira49c0772024-11-30 10:56:30 +01001616 }
Girish Palya8cd42a52025-06-05 21:04:29 +02001617 else if (fuzzy_filter)
1618 {
1619 if (i == 0)
1620 shown_compl = compl;
1621
1622 if (!shown_match_ok && compl == compl_shown_match)
1623 {
1624 cur = i;
1625 shown_match_ok = TRUE;
1626 }
1627 }
1628 i++;
glepnira49c0772024-11-30 10:56:30 +01001629 }
glepnir80b66202024-11-27 21:53:53 +01001630 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001631
glepnirf400a0c2025-01-23 19:55:14 +01001632 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001633 {
1634 did_find_shown_match = TRUE;
1635
1636 // When the original text is the shown match don't set
1637 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001638 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001639 shown_match_ok = TRUE;
1640
1641 if (!shown_match_ok && shown_compl != NULL)
1642 {
1643 // The shown match isn't displayed, set it to the
1644 // previously displayed match.
1645 compl_shown_match = shown_compl;
1646 shown_match_ok = TRUE;
1647 }
1648 }
glepnira49c0772024-11-30 10:56:30 +01001649 compl = compl->cp_next;
1650 } while (compl != NULL && !is_first_match(compl));
1651
Girish Palya8cd42a52025-06-05 21:04:29 +02001652 vim_free(match_count);
1653
glepnira49c0772024-11-30 10:56:30 +01001654 if (compl_match_arraysize == 0)
1655 return -1;
1656
Girish Palya8cd42a52025-06-05 21:04:29 +02001657 if (fuzzy_filter && !compl_no_select && !shown_match_ok)
glepnirc0b7ca42025-02-13 20:27:44 +01001658 {
1659 compl_shown_match = shown_compl;
1660 shown_match_ok = TRUE;
1661 cur = 0;
1662 }
1663
glepnira49c0772024-11-30 10:56:30 +01001664 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1665 if (compl_match_array == NULL)
1666 return -1;
1667
1668 compl = match_head;
1669 i = 0;
1670 while (compl != NULL)
1671 {
glepnir6e199932024-12-14 21:13:27 +01001672 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1673 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001674 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1675 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
Girish Palya19ef6b02025-05-28 20:28:21 +02001676 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001677 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1678 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001679 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1680 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001681 match_next = compl->cp_match_next;
1682 compl->cp_match_next = NULL;
1683 compl = match_next;
1684 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001685
1686 if (!shown_match_ok) // no displayed match at all
1687 cur = -1;
1688
1689 return cur;
1690}
1691
1692/*
1693 * Show the popup menu for the list of matches.
1694 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1695 */
1696 void
1697ins_compl_show_pum(void)
1698{
1699 int i;
1700 int cur = -1;
1701 colnr_T col;
1702
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001703 if (!pum_wanted() || !pum_enough_matches())
1704 return;
1705
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001706 // Update the screen later, before drawing the popup menu over it.
1707 pum_call_update_screen();
1708
1709 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001710 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001711 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001712 else
1713 {
1714 // popup menu already exists, only need to find the current item.
1715 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001716 {
John Marriott5e6ea922024-11-23 14:01:57 +01001717 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001718 || compl_match_array[i].pum_text
1719 == compl_shown_match->cp_text[CPT_ABBR])
1720 {
1721 cur = i;
1722 break;
1723 }
glepnir19e1dd62025-05-08 22:50:38 +02001724 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001725 }
1726
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001727 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001728 {
1729#ifdef FEAT_EVAL
1730 if (compl_started && has_completechanged())
1731 trigger_complete_changed_event(cur);
1732#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001733 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001734 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001735
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001736 // In Replace mode when a $ is displayed at the end of the line only
1737 // part of the screen would be updated. We do need to redraw here.
1738 dollar_vcol = -1;
1739
1740 // Compute the screen column of the start of the completed text.
1741 // Use the cursor to get all wrapping and other settings right.
1742 col = curwin->w_cursor.col;
1743 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001744 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001745 pum_display(compl_match_array, compl_match_arraysize, cur);
1746 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001747
glepnircbb46b42024-02-03 18:11:13 +01001748 // After adding leader, set the current match to shown match.
1749 if (compl_started && compl_curr_match != compl_shown_match)
1750 compl_curr_match = compl_shown_match;
1751
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001752#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001753 if (has_completechanged())
1754 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001755#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001756}
1757
1758#define DICT_FIRST (1) // use just first element in "dict"
1759#define DICT_EXACT (2) // "dict" is the exact name of a file
1760
1761/*
glepnir40c1c332024-06-11 19:37:04 +02001762 * Get current completion leader
1763 */
1764 char_u *
1765ins_compl_leader(void)
1766{
John Marriott5e6ea922024-11-23 14:01:57 +01001767 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1768}
1769
1770/*
1771 * Get current completion leader length
1772 */
1773 size_t
1774ins_compl_leader_len(void)
1775{
1776 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001777}
1778
1779/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001780 * Add any identifiers that match the given pattern "pat" in the list of
1781 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001782 */
1783 static void
1784ins_compl_dictionaries(
1785 char_u *dict_start,
1786 char_u *pat,
1787 int flags, // DICT_FIRST and/or DICT_EXACT
1788 int thesaurus) // Thesaurus completion
1789{
1790 char_u *dict = dict_start;
1791 char_u *ptr;
1792 char_u *buf;
1793 regmatch_T regmatch;
1794 char_u **files;
1795 int count;
1796 int save_p_scs;
1797 int dir = compl_direction;
1798
1799 if (*dict == NUL)
1800 {
1801#ifdef FEAT_SPELL
1802 // When 'dictionary' is empty and spell checking is enabled use
1803 // "spell".
1804 if (!thesaurus && curwin->w_p_spell)
1805 dict = (char_u *)"spell";
1806 else
1807#endif
1808 return;
1809 }
1810
1811 buf = alloc(LSIZE);
1812 if (buf == NULL)
1813 return;
1814 regmatch.regprog = NULL; // so that we can goto theend
1815
1816 // If 'infercase' is set, don't use 'smartcase' here
1817 save_p_scs = p_scs;
1818 if (curbuf->b_p_inf)
1819 p_scs = FALSE;
1820
1821 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1822 // to only match at the start of a line. Otherwise just match the
1823 // pattern. Also need to double backslashes.
1824 if (ctrl_x_mode_line_or_eval())
1825 {
1826 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001827
1828 if (pat_esc == NULL)
1829 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001830 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001831 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001832 if (ptr == NULL)
1833 {
1834 vim_free(pat_esc);
1835 goto theend;
1836 }
1837 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1838 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1839 vim_free(pat_esc);
1840 vim_free(ptr);
1841 }
1842 else
1843 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001844 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001845 if (regmatch.regprog == NULL)
1846 goto theend;
1847 }
1848
1849 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1850 regmatch.rm_ic = ignorecase(pat);
1851 while (*dict != NUL && !got_int && !compl_interrupted)
1852 {
1853 // copy one dictionary file name into buf
1854 if (flags == DICT_EXACT)
1855 {
1856 count = 1;
1857 files = &dict;
1858 }
1859 else
1860 {
1861 // Expand wildcards in the dictionary name, but do not allow
1862 // backticks (for security, the 'dict' option may have been set in
1863 // a modeline).
1864 copy_option_part(&dict, buf, LSIZE, ",");
1865# ifdef FEAT_SPELL
1866 if (!thesaurus && STRCMP(buf, "spell") == 0)
1867 count = -1;
1868 else
1869# endif
1870 if (vim_strchr(buf, '`') != NULL
1871 || expand_wildcards(1, &buf, &count, &files,
1872 EW_FILE|EW_SILENT) != OK)
1873 count = 0;
1874 }
1875
1876# ifdef FEAT_SPELL
1877 if (count == -1)
1878 {
1879 // Complete from active spelling. Skip "\<" in the pattern, we
1880 // don't use it as a RE.
1881 if (pat[0] == '\\' && pat[1] == '<')
1882 ptr = pat + 2;
1883 else
1884 ptr = pat;
1885 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1886 }
1887 else
1888# endif
1889 if (count > 0) // avoid warning for using "files" uninit
1890 {
1891 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001892 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001893 if (flags != DICT_EXACT)
1894 FreeWild(count, files);
1895 }
1896 if (flags != 0)
1897 break;
1898 }
1899
1900theend:
1901 p_scs = save_p_scs;
1902 vim_regfree(regmatch.regprog);
1903 vim_free(buf);
1904}
1905
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001906/*
1907 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1908 * skipping the word at 'skip_word'. Returns OK on success.
1909 */
1910 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001911thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001912 char_u *fname,
1913 char_u **buf_arg,
1914 int dir,
1915 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001916{
1917 int status = OK;
1918 char_u *ptr;
1919 char_u *wstart;
1920
1921 // Add the other matches on the line
1922 ptr = *buf_arg;
1923 while (!got_int)
1924 {
1925 // Find start of the next word. Skip white
1926 // space and punctuation.
1927 ptr = find_word_start(ptr);
1928 if (*ptr == NUL || *ptr == NL)
1929 break;
1930 wstart = ptr;
1931
1932 // Find end of the word.
1933 if (has_mbyte)
1934 // Japanese words may have characters in
1935 // different classes, only separate words
1936 // with single-byte non-word characters.
1937 while (*ptr != NUL)
1938 {
1939 int l = (*mb_ptr2len)(ptr);
1940
1941 if (l < 2 && !vim_iswordc(*ptr))
1942 break;
1943 ptr += l;
1944 }
1945 else
1946 ptr = find_word_end(ptr);
1947
1948 // Add the word. Skip the regexp match.
1949 if (wstart != skip_word)
1950 {
1951 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001952 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001953 if (status == FAIL)
1954 break;
1955 }
1956 }
1957
1958 *buf_arg = ptr;
1959 return status;
1960}
1961
1962/*
1963 * Process "count" dictionary/thesaurus "files" and add the text matching
1964 * "regmatch".
1965 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001966 static void
1967ins_compl_files(
1968 int count,
1969 char_u **files,
1970 int thesaurus,
1971 int flags,
1972 regmatch_T *regmatch,
1973 char_u *buf,
1974 int *dir)
1975{
1976 char_u *ptr;
1977 int i;
1978 FILE *fp;
1979 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001980 char_u *leader = NULL;
1981 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001982 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001983 int score = 0;
1984 int len = 0;
1985 char_u *line_end = NULL;
1986
1987 if (in_fuzzy_collect)
1988 {
1989 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001990 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001991 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001992
1993 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1994 {
1995 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001996 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001997 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001998 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001999 vim_snprintf((char *)IObuff, IOSIZE,
2000 _("Scanning dictionary: %s"), (char *)files[i]);
2001 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2002 }
2003
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002004 if (fp == NULL)
2005 continue;
2006
2007 // Read dictionary file line by line.
2008 // Check each line for a match.
2009 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002010 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002011 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01002012 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002013 {
glepnirf31cfa22025-03-06 21:59:13 +01002014 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002015 {
glepnirf31cfa22025-03-06 21:59:13 +01002016 ptr = regmatch->startp[0];
2017 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
2018 : find_word_end(ptr);
2019 add_r = ins_compl_add_infercase(regmatch->startp[0],
2020 (int)(ptr - regmatch->startp[0]),
2021 p_ic, files[i], *dir, FALSE, 0);
2022 if (thesaurus)
2023 {
2024 // For a thesaurus, add all the words in the line
2025 ptr = buf;
2026 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
2027 regmatch->startp[0]);
2028 }
2029 if (add_r == OK)
2030 // if dir was BACKWARD then honor it just once
2031 *dir = FORWARD;
2032 else if (add_r == FAIL)
2033 break;
2034 // avoid expensive call to vim_regexec() when at end
2035 // of line
2036 if (*ptr == '\n' || got_int)
2037 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002038 }
glepnirf31cfa22025-03-06 21:59:13 +01002039 }
2040 else if (in_fuzzy_collect && leader_len > 0)
2041 {
2042 line_end = find_line_end(ptr);
2043 while (ptr < line_end)
2044 {
2045 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
2046 {
2047 char_u *end_ptr = ctrl_x_mode_line_or_eval()
2048 ? find_line_end(ptr) : find_word_end(ptr);
2049 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2050 p_ic, files[i], *dir, FALSE, score);
2051 if (add_r == FAIL)
2052 break;
2053 ptr = end_ptr; // start from next word
2054 if (compl_get_longest && ctrl_x_mode_normal()
2055 && compl_first_match->cp_next
2056 && score == compl_first_match->cp_next->cp_score)
2057 compl_num_bests++;
2058 }
glepnirf31cfa22025-03-06 21:59:13 +01002059 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002060 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002061 line_breakcheck();
2062 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002063 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002064 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002065 }
2066}
2067
2068/*
2069 * Find the start of the next word.
2070 * Returns a pointer to the first char of the word. Also stops at a NUL.
2071 */
2072 char_u *
2073find_word_start(char_u *ptr)
2074{
2075 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002076 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002077 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2078 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002079 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002080 else
glepnir19e1dd62025-05-08 22:50:38 +02002081 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002082 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2083 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002084 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002085 return ptr;
2086}
2087
2088/*
2089 * Find the end of the word. Assumes it starts inside a word.
2090 * Returns a pointer to just after the word.
2091 */
2092 char_u *
2093find_word_end(char_u *ptr)
2094{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002095 if (has_mbyte)
2096 {
glepnir19e1dd62025-05-08 22:50:38 +02002097 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098 if (start_class > 1)
2099 while (*ptr != NUL)
2100 {
2101 ptr += (*mb_ptr2len)(ptr);
2102 if (mb_get_class(ptr) != start_class)
2103 break;
2104 }
2105 }
2106 else
2107 while (vim_iswordc(*ptr))
2108 ++ptr;
2109 return ptr;
2110}
2111
2112/*
2113 * Find the end of the line, omitting CR and NL at the end.
2114 * Returns a pointer to just after the line.
2115 */
glepnirdd42b052025-03-08 16:52:55 +01002116 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002117find_line_end(char_u *ptr)
2118{
glepnir19e1dd62025-05-08 22:50:38 +02002119 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002120 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2121 --s;
2122 return s;
2123}
2124
2125/*
Girish Palyacbe53192025-04-14 22:13:15 +02002126 * Free a completion item in the list
2127 */
2128 static void
2129ins_compl_item_free(compl_T *match)
2130{
Girish Palyacbe53192025-04-14 22:13:15 +02002131 VIM_CLEAR_STRING(match->cp_str);
2132 // several entries may use the same fname, free it just once.
2133 if (match->cp_flags & CP_FREE_FNAME)
2134 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002135 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002136 vim_free(match->cp_text[i]);
2137#ifdef FEAT_EVAL
2138 clear_tv(&match->cp_user_data);
2139#endif
2140 vim_free(match);
2141}
2142
2143/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002144 * Free the list of completions
2145 */
2146 static void
2147ins_compl_free(void)
2148{
2149 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002150
John Marriott5e6ea922024-11-23 14:01:57 +01002151 VIM_CLEAR_STRING(compl_pattern);
2152 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002153
2154 if (compl_first_match == NULL)
2155 return;
2156
2157 ins_compl_del_pum();
2158 pum_clear();
2159
2160 compl_curr_match = compl_first_match;
2161 do
2162 {
2163 match = compl_curr_match;
2164 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002165 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002166 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002167 compl_first_match = compl_curr_match = NULL;
2168 compl_shown_match = NULL;
2169 compl_old_match = NULL;
2170}
2171
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002172/*
2173 * Reset/clear the completion state.
2174 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002175 void
2176ins_compl_clear(void)
2177{
2178 compl_cont_status = 0;
2179 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002180 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002181 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002182 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002183 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002184 compl_curr_win = NULL;
2185 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002186 VIM_CLEAR_STRING(compl_pattern);
2187 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002188 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002189 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002190 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002191 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002192#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002193 // clear v:completed_item
2194 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002195#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002196}
2197
2198/*
2199 * Return TRUE when Insert completion is active.
2200 */
2201 int
2202ins_compl_active(void)
2203{
2204 return compl_started;
2205}
2206
2207/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002208 * Return True when wp is the actual completion window
2209 */
2210 int
glepnircf7f0122025-04-15 19:02:00 +02002211ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002212{
glepnircf7f0122025-04-15 19:02:00 +02002213 return ins_compl_active() && wp == compl_curr_win
2214 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002215}
2216
2217/*
Girish Palyacbe53192025-04-14 22:13:15 +02002218 * Selected one of the matches. When FALSE, the match was either edited or
2219 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002220 */
2221 int
2222ins_compl_used_match(void)
2223{
2224 return compl_used_match;
2225}
2226
2227/*
2228 * Initialize get longest common string.
2229 */
2230 void
2231ins_compl_init_get_longest(void)
2232{
2233 compl_get_longest = FALSE;
2234}
2235
2236/*
2237 * Returns TRUE when insert completion is interrupted.
2238 */
2239 int
2240ins_compl_interrupted(void)
2241{
2242 return compl_interrupted;
2243}
2244
2245/*
2246 * Returns TRUE if the <Enter> key selects a match in the completion popup
2247 * menu.
2248 */
2249 int
2250ins_compl_enter_selects(void)
2251{
2252 return compl_enter_selects;
2253}
2254
2255/*
2256 * Return the column where the text starts that is being completed
2257 */
2258 colnr_T
2259ins_compl_col(void)
2260{
2261 return compl_col;
2262}
2263
2264/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002265 * Return the length in bytes of the text being completed
2266 */
2267 int
2268ins_compl_len(void)
2269{
2270 return compl_length;
2271}
2272
2273/*
glepnir94a045e2025-03-01 16:12:23 +01002274 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2275 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002276 */
2277 static int
2278ins_compl_has_preinsert(void)
2279{
glepnira2c55592025-02-28 17:43:42 +01002280 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002281 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2282 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002283}
2284
2285/*
2286 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2287 * the `compl_ins_end_col` range.
2288 */
2289 int
2290ins_compl_preinsert_effect(void)
2291{
2292 if (!ins_compl_has_preinsert())
2293 return FALSE;
2294
2295 return curwin->w_cursor.col < compl_ins_end_col;
2296}
2297
2298/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002299 * Delete one character before the cursor and show the subset of the matches
2300 * that match the word that is now before the cursor.
2301 * Returns the character to be used, NUL if the work is done and another char
2302 * to be got from the user.
2303 */
2304 int
2305ins_compl_bs(void)
2306{
2307 char_u *line;
2308 char_u *p;
2309
glepniredd4ac32025-01-29 18:53:51 +01002310 if (ins_compl_preinsert_effect())
2311 ins_compl_delete();
2312
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002313 line = ml_get_curline();
2314 p = line + curwin->w_cursor.col;
2315 MB_PTR_BACK(line, p);
2316
2317 // Stop completion when the whole word was deleted. For Omni completion
2318 // allow the word to be deleted, we won't match everything.
2319 // Respect the 'backspace' option.
2320 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002321 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2322 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002323 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2324 - compl_length < 0))
2325 return K_BS;
2326
2327 // Deleted more than what was used to find matches or didn't finish
2328 // finding all matches: need to look for matches all over again.
2329 if (curwin->w_cursor.col <= compl_col + compl_length
2330 || ins_compl_need_restart())
2331 ins_compl_restart();
2332
John Marriott5e6ea922024-11-23 14:01:57 +01002333 VIM_CLEAR_STRING(compl_leader);
2334 compl_leader.length = (size_t)((p - line) - compl_col);
2335 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2336 if (compl_leader.string == NULL)
2337 {
2338 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002339 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002340 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002341
2342 ins_compl_new_leader();
2343 if (compl_shown_match != NULL)
2344 // Make sure current match is not a hidden item.
2345 compl_curr_match = compl_shown_match;
2346 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002347}
2348
2349/*
2350 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2351 * be called.
2352 */
2353 static int
2354ins_compl_need_restart(void)
2355{
2356 // Return TRUE if we didn't complete finding matches or when the
2357 // 'completefunc' returned "always" in the "refresh" dictionary item.
2358 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002359 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002360 && compl_opt_refresh_always);
2361}
2362
2363/*
2364 * Called after changing "compl_leader".
2365 * Show the popup menu with a different set of matches.
2366 * May also search for matches again if the previous search was interrupted.
2367 */
2368 static void
2369ins_compl_new_leader(void)
2370{
2371 ins_compl_del_pum();
2372 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002373 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002374 compl_used_match = FALSE;
2375
2376 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002377 {
John Marriott5e6ea922024-11-23 14:01:57 +01002378 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002379 if (is_cpt_func_refresh_always())
2380 cpt_compl_refresh();
2381 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002382 else
2383 {
2384#ifdef FEAT_SPELL
2385 spell_bad_len = 0; // need to redetect bad word
2386#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002387 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002388 // the popup menu display the changed text before the cursor. Set
2389 // "compl_restarting" to avoid that the first match is inserted.
2390 pum_call_update_screen();
2391#ifdef FEAT_GUI
2392 if (gui.in_use)
2393 {
2394 // Show the cursor after the match, not after the redrawn text.
2395 setcursor();
2396 out_flush_cursor(FALSE, FALSE);
2397 }
2398#endif
2399 compl_restarting = TRUE;
2400 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2401 compl_cont_status = 0;
2402 compl_restarting = FALSE;
2403 }
2404
glepnir44180412025-02-20 22:09:48 +01002405 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002406
2407 // Show the popup menu with a different set of matches.
2408 ins_compl_show_pum();
2409
2410 // Don't let Enter select the original text when there is no popup menu.
2411 if (compl_match_array == NULL)
2412 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002413 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2414 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002415}
2416
2417/*
2418 * Return the length of the completion, from the completion start column to
2419 * the cursor column. Making sure it never goes below zero.
2420 */
2421 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002422get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002423{
2424 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002425 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002426}
2427
2428/*
2429 * Append one character to the match leader. May reduce the number of
2430 * matches.
2431 */
2432 void
2433ins_compl_addleader(int c)
2434{
glepnir19e1dd62025-05-08 22:50:38 +02002435 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002436
glepniredd4ac32025-01-29 18:53:51 +01002437 if (ins_compl_preinsert_effect())
2438 ins_compl_delete();
2439
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002440 if (stop_arrow() == FAIL)
2441 return;
2442 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2443 {
2444 char_u buf[MB_MAXBYTES + 1];
2445
2446 (*mb_char2bytes)(c, buf);
2447 buf[cc] = NUL;
2448 ins_char_bytes(buf, cc);
2449 if (compl_opt_refresh_always)
2450 AppendToRedobuff(buf);
2451 }
2452 else
2453 {
2454 ins_char(c);
2455 if (compl_opt_refresh_always)
2456 AppendCharToRedobuff(c);
2457 }
2458
2459 // If we didn't complete finding matches we must search again.
2460 if (ins_compl_need_restart())
2461 ins_compl_restart();
2462
2463 // When 'always' is set, don't reset compl_leader. While completing,
2464 // cursor doesn't point original position, changing compl_leader would
2465 // break redo.
2466 if (!compl_opt_refresh_always)
2467 {
John Marriott5e6ea922024-11-23 14:01:57 +01002468 VIM_CLEAR_STRING(compl_leader);
2469 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2470 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2471 compl_leader.length);
2472 if (compl_leader.string == NULL)
2473 {
2474 compl_leader.length = 0;
2475 return;
2476 }
2477
2478 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002479 }
2480}
2481
2482/*
2483 * Setup for finding completions again without leaving CTRL-X mode. Used when
2484 * BS or a key was typed while still searching for matches.
2485 */
2486 static void
2487ins_compl_restart(void)
2488{
2489 ins_compl_free();
2490 compl_started = FALSE;
2491 compl_matches = 0;
2492 compl_cont_status = 0;
2493 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002494 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002495}
2496
2497/*
2498 * Set the first match, the original text.
2499 */
2500 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002501ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002502{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002503 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002504 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2505 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002506 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002507 {
John Marriott5e6ea922024-11-23 14:01:57 +01002508 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002509 if (p != NULL)
2510 {
John Marriott5e6ea922024-11-23 14:01:57 +01002511 VIM_CLEAR_STRING(compl_first_match->cp_str);
2512 compl_first_match->cp_str.string = p;
2513 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002514 }
2515 }
2516 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002517 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002518 {
John Marriott5e6ea922024-11-23 14:01:57 +01002519 char_u *p = vim_strnsave(str, len);
2520 if (p != NULL)
2521 {
2522 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2523 compl_first_match->cp_prev->cp_str.string = p;
2524 compl_first_match->cp_prev->cp_str.length = len;
2525 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002526 }
2527}
2528
2529/*
2530 * Append one character to the match leader. May reduce the number of
2531 * matches.
2532 */
2533 void
2534ins_compl_addfrommatch(void)
2535{
2536 char_u *p;
2537 int len = (int)curwin->w_cursor.col - (int)compl_col;
2538 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002539
John Marriott5e6ea922024-11-23 14:01:57 +01002540 p = compl_shown_match->cp_str.string;
2541 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002542 {
John Marriott5e6ea922024-11-23 14:01:57 +01002543 size_t plen;
2544 compl_T *cp;
2545
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002546 // When still at the original match use the first entry that matches
2547 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002548 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002549 return;
2550
2551 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002552 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002553 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002554 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002555 {
John Marriott5e6ea922024-11-23 14:01:57 +01002556 if (compl_leader.string == NULL
2557 || ins_compl_equal(cp, compl_leader.string,
2558 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002559 {
John Marriott5e6ea922024-11-23 14:01:57 +01002560 p = cp->cp_str.string;
2561 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002562 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002563 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002564 }
John Marriott5e6ea922024-11-23 14:01:57 +01002565 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002566 return;
2567 }
2568 p += len;
2569 c = PTR2CHAR(p);
2570 ins_compl_addleader(c);
2571}
2572
2573/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002574 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002575 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2576 * compl_cont_mode and compl_cont_status.
2577 * Returns TRUE when the character is not to be inserted.
2578 */
2579 static int
2580set_ctrl_x_mode(int c)
2581{
glepnir05460682025-05-26 18:23:27 +02002582 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002583
2584 switch (c)
2585 {
2586 case Ctrl_E:
2587 case Ctrl_Y:
2588 // scroll the window one line up or down
2589 ctrl_x_mode = CTRL_X_SCROLL;
2590 if (!(State & REPLACE_FLAG))
2591 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2592 else
2593 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2594 edit_submode_pre = NULL;
2595 showmode();
2596 break;
2597 case Ctrl_L:
2598 // complete whole line
2599 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2600 break;
2601 case Ctrl_F:
2602 // complete filenames
2603 ctrl_x_mode = CTRL_X_FILES;
2604 break;
2605 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002606 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002607 ctrl_x_mode = CTRL_X_DICTIONARY;
2608 break;
2609 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002610 // When CTRL-R is followed by '=', don't trigger register completion
2611 // This allows expressions like <C-R>=func()<CR> to work normally
2612 if (vpeekc() == '=')
2613 break;
2614 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002615 break;
2616 case Ctrl_T:
2617 // complete words from a thesaurus
2618 ctrl_x_mode = CTRL_X_THESAURUS;
2619 break;
2620#ifdef FEAT_COMPL_FUNC
2621 case Ctrl_U:
2622 // user defined completion
2623 ctrl_x_mode = CTRL_X_FUNCTION;
2624 break;
2625 case Ctrl_O:
2626 // omni completion
2627 ctrl_x_mode = CTRL_X_OMNI;
2628 break;
2629#endif
2630 case 's':
2631 case Ctrl_S:
2632 // complete spelling suggestions
2633 ctrl_x_mode = CTRL_X_SPELL;
2634#ifdef FEAT_SPELL
2635 ++emsg_off; // Avoid getting the E756 error twice.
2636 spell_back_to_badword();
2637 --emsg_off;
2638#endif
2639 break;
2640 case Ctrl_RSB:
2641 // complete tag names
2642 ctrl_x_mode = CTRL_X_TAGS;
2643 break;
2644#ifdef FEAT_FIND_ID
2645 case Ctrl_I:
2646 case K_S_TAB:
2647 // complete keywords from included files
2648 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2649 break;
2650 case Ctrl_D:
2651 // complete definitions from included files
2652 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2653 break;
2654#endif
2655 case Ctrl_V:
2656 case Ctrl_Q:
2657 // complete vim commands
2658 ctrl_x_mode = CTRL_X_CMDLINE;
2659 break;
2660 case Ctrl_Z:
2661 // stop completion
2662 ctrl_x_mode = CTRL_X_NORMAL;
2663 edit_submode = NULL;
2664 showmode();
2665 retval = TRUE;
2666 break;
2667 case Ctrl_P:
2668 case Ctrl_N:
2669 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2670 // just started ^X mode, or there were enough ^X's to cancel
2671 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2672 // do normal expansion when interrupting a different mode (say
2673 // ^X^F^X^P or ^P^X^X^P, see below)
2674 // nothing changes if interrupting mode 0, (eg, the flag
2675 // doesn't change when going to ADDING mode -- Acevedo
2676 if (!(compl_cont_status & CONT_INTRPT))
2677 compl_cont_status |= CONT_LOCAL;
2678 else if (compl_cont_mode != 0)
2679 compl_cont_status &= ~CONT_LOCAL;
2680 // FALLTHROUGH
2681 default:
2682 // If we have typed at least 2 ^X's... for modes != 0, we set
2683 // compl_cont_status = 0 (eg, as if we had just started ^X
2684 // mode).
2685 // For mode 0, we set "compl_cont_mode" to an impossible
2686 // value, in both cases ^X^X can be used to restart the same
2687 // mode (avoiding ADDING mode).
2688 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2689 // 'complete' and local ^P expansions respectively.
2690 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2691 // mode -- Acevedo
2692 if (c == Ctrl_X)
2693 {
2694 if (compl_cont_mode != 0)
2695 compl_cont_status = 0;
2696 else
2697 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2698 }
2699 ctrl_x_mode = CTRL_X_NORMAL;
2700 edit_submode = NULL;
2701 showmode();
2702 break;
2703 }
2704
2705 return retval;
2706}
2707
2708/*
glepnir1c5a1202024-12-04 20:27:34 +01002709 * Trigger CompleteDone event and adds relevant information to v:event
2710 */
2711 static void
2712trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2713{
2714#if defined(FEAT_EVAL)
2715 save_v_event_T save_v_event;
2716 dict_T *v_event = get_v_event(&save_v_event);
2717 char_u *mode_str = NULL;
2718
2719 mode = mode & ~CTRL_X_WANT_IDENT;
2720 if (ctrl_x_mode_names[mode])
2721 mode_str = (char_u *)ctrl_x_mode_names[mode];
2722
2723 (void)dict_add_string(v_event, "complete_word",
2724 word == NULL ? (char_u *)"" : word);
2725 (void)dict_add_string(v_event, "complete_type",
2726 mode_str != NULL ? mode_str : (char_u *)"");
2727
2728 dict_set_items_ro(v_event);
2729#endif
2730 ins_apply_autocmds(EVENT_COMPLETEDONE);
2731
2732#if defined(FEAT_EVAL)
2733 restore_v_event(v_event, &save_v_event);
2734#endif
2735}
2736
2737/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002738 * Stop insert completion mode
2739 */
2740 static int
2741ins_compl_stop(int c, int prev_mode, int retval)
2742{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002743 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002744 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002745
glepnir84a75032025-03-15 09:59:22 +01002746 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002747 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002748 ins_compl_delete();
2749
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002750 // Get here when we have finished typing a sequence of ^N and
2751 // ^P or other completion characters in CTRL-X mode. Free up
2752 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002753 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002754 {
glepnir40891ba2025-02-10 22:18:00 +01002755 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002756
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002757 // If any of the original typed text has been changed, eg when
2758 // ignorecase is set, we must add back-spaces to the redo
2759 // buffer. We add as few as necessary to delete just the part
2760 // of the original text that has changed.
2761 // When using the longest match, edited the match or used
2762 // CTRL-E then don't use the current match.
2763 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002764 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002765 ins_compl_fixRedoBufForLeader(ptr);
2766 }
2767
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002768 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002769
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002770 // When completing whole lines: fix indent for 'cindent'.
2771 // Otherwise, break line if it's too long.
2772 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2773 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002774 // re-indent the current line
2775 if (want_cindent)
2776 {
2777 do_c_expr_indent();
2778 want_cindent = FALSE; // don't do it again
2779 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002780 }
2781 else
2782 {
2783 int prev_col = curwin->w_cursor.col;
2784
2785 // put the cursor on the last char, for 'tw' formatting
2786 if (prev_col > 0)
2787 dec_cursor();
2788 // only format when something was inserted
2789 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2790 insertchar(NUL, 0, -1);
2791 if (prev_col > 0
2792 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2793 inc_cursor();
2794 }
2795
2796 // If the popup menu is displayed pressing CTRL-Y means accepting
2797 // the selection without inserting anything. When
2798 // compl_enter_selects is set the Enter key does the same.
2799 if ((c == Ctrl_Y || (compl_enter_selects
2800 && (c == CAR || c == K_KENTER || c == NL)))
2801 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002802 {
2803 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002804 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002805 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002806
2807 // CTRL-E means completion is Ended, go back to the typed text.
2808 // but only do this, if the Popup is still visible
2809 if (c == Ctrl_E)
2810 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002811 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002812 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002813
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002814 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002815 if (compl_leader.string != NULL)
2816 {
2817 p = compl_leader.string;
2818 plen = compl_leader.length;
2819 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002820 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002821 {
2822 p = compl_orig_text.string;
2823 plen = compl_orig_text.length;
2824 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002825 if (p != NULL)
2826 {
2827 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002828
John Marriott5e6ea922024-11-23 14:01:57 +01002829 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002830 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002831 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002832 retval = TRUE;
2833 }
2834
2835 auto_format(FALSE, TRUE);
2836
2837 // Trigger the CompleteDonePre event to give scripts a chance to
2838 // act upon the completion before clearing the info, and restore
2839 // ctrl_x_mode, so that complete_info() can be used.
2840 ctrl_x_mode = prev_mode;
2841 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2842
2843 ins_compl_free();
2844 compl_started = FALSE;
2845 compl_matches = 0;
2846 if (!shortmess(SHM_COMPLETIONMENU))
2847 msg_clr_cmdline(); // necessary for "noshowmode"
2848 ctrl_x_mode = CTRL_X_NORMAL;
2849 compl_enter_selects = FALSE;
2850 if (edit_submode != NULL)
2851 {
2852 edit_submode = NULL;
2853 showmode();
2854 }
2855
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002856 if (c == Ctrl_C && cmdwin_type != 0)
2857 // Avoid the popup menu remains displayed when leaving the
2858 // command line window.
2859 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002860 // Indent now if a key was typed that is in 'cinkeys'.
2861 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2862 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002863 // Trigger the CompleteDone event to give scripts a chance to act
2864 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002865 trigger_complete_done_event(prev_mode, word);
2866 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002867
2868 return retval;
2869}
2870
2871/*
glepnircf7f0122025-04-15 19:02:00 +02002872 * Cancel completion.
2873 */
2874 int
2875ins_compl_cancel(void)
2876{
2877 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2878}
2879
2880/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002881 * Prepare for Insert mode completion, or stop it.
2882 * Called just after typing a character in Insert mode.
2883 * Returns TRUE when the character is not to be inserted;
2884 */
2885 int
2886ins_compl_prep(int c)
2887{
glepnir19e1dd62025-05-08 22:50:38 +02002888 int retval = FALSE;
2889 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002890
2891 // Forget any previous 'special' messages if this is actually
2892 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2893 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2894 edit_submode_extra = NULL;
2895
zeertzjq440d4cb2023-03-02 17:51:32 +00002896 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002897 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002898 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002899 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002900 return retval;
2901
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002902#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002903 // Ignore mouse events in a popup window
2904 if (is_mouse_key(c))
2905 {
2906 // Ignore drag and release events, the position does not need to be in
2907 // the popup and it may have just closed.
2908 if (c == K_LEFTRELEASE
2909 || c == K_LEFTRELEASE_NM
2910 || c == K_MIDDLERELEASE
2911 || c == K_RIGHTRELEASE
2912 || c == K_X1RELEASE
2913 || c == K_X2RELEASE
2914 || c == K_LEFTDRAG
2915 || c == K_MIDDLEDRAG
2916 || c == K_RIGHTDRAG
2917 || c == K_X1DRAG
2918 || c == K_X2DRAG)
2919 return retval;
2920 if (popup_visible)
2921 {
2922 int row = mouse_row;
2923 int col = mouse_col;
2924 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2925
2926 if (wp != NULL && WIN_IS_POPUP(wp))
2927 return retval;
2928 }
2929 }
2930#endif
2931
zeertzjqdca29d92021-08-31 19:12:51 +02002932 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2933 {
2934 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2935 || !vim_is_ctrl_x_key(c))
2936 {
2937 // Not starting another completion mode.
2938 ctrl_x_mode = CTRL_X_CMDLINE;
2939
2940 // CTRL-X CTRL-Z should stop completion without inserting anything
2941 if (c == Ctrl_Z)
2942 retval = TRUE;
2943 }
2944 else
2945 {
2946 ctrl_x_mode = CTRL_X_CMDLINE;
2947
2948 // Other CTRL-X keys first stop completion, then start another
2949 // completion mode.
2950 ins_compl_prep(' ');
2951 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2952 }
2953 }
2954
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002955 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002956 if (ctrl_x_mode_not_defined_yet()
2957 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002958 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002959 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002960 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002961 }
2962
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002963 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002964 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2965 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002966 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002967 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002968 {
2969 // We're already in CTRL-X mode, do we stay in it?
2970 if (!vim_is_ctrl_x_key(c))
2971 {
glepnir40891ba2025-02-10 22:18:00 +01002972 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002973 edit_submode = NULL;
2974 }
2975 showmode();
2976 }
2977
2978 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2979 {
2980 // Show error message from attempted keyword completion (probably
2981 // 'Pattern not found') until another key is hit, then go back to
2982 // showing what mode we are in.
2983 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002984 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002985 && c != Ctrl_R && !ins_compl_pum_key(c))
2986 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002987 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002988 }
2989 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2990 // Trigger the CompleteDone event to give scripts a chance to act
2991 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002992 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002993
LemonBoy2bf52dd2022-04-09 18:17:34 +01002994 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002995
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002996 // reset continue_* if we left expansion-mode, if we stay they'll be
2997 // (re)set properly in ins_complete()
2998 if (!vim_is_ctrl_x_key(c))
2999 {
3000 compl_cont_status = 0;
3001 compl_cont_mode = 0;
3002 }
3003
3004 return retval;
3005}
3006
3007/*
3008 * Fix the redo buffer for the completion leader replacing some of the typed
3009 * text. This inserts backspaces and appends the changed text.
3010 * "ptr" is the known leader text or NUL.
3011 */
3012 static void
3013ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
3014{
John Marriott5e6ea922024-11-23 14:01:57 +01003015 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003016 char_u *p;
3017 char_u *ptr = ptr_arg;
3018
3019 if (ptr == NULL)
3020 {
John Marriott5e6ea922024-11-23 14:01:57 +01003021 if (compl_leader.string != NULL)
3022 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003023 else
3024 return; // nothing to do
3025 }
John Marriott5e6ea922024-11-23 14:01:57 +01003026 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003027 {
John Marriott5e6ea922024-11-23 14:01:57 +01003028 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01003029 // Find length of common prefix between original text and new completion
3030 while (p[len] != NUL && p[len] == ptr[len])
3031 len++;
3032 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003033 if (len > 0)
3034 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01003035 // Add backspace characters for each remaining character in
3036 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003037 for (p += len; *p != NUL; MB_PTR_ADV(p))
3038 AppendCharToRedobuff(K_BS);
3039 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003040 if (ptr != NULL)
3041 AppendToRedobuffLit(ptr + len, -1);
3042}
3043
3044/*
3045 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3046 * (depending on flag) starting from buf and looking for a non-scanned
3047 * buffer (other than curbuf). curbuf is special, if it is called with
3048 * buf=curbuf then it has to be the first call for a given flag/expansion.
3049 *
3050 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3051 */
3052 static buf_T *
3053ins_compl_next_buf(buf_T *buf, int flag)
3054{
glepnir19e1dd62025-05-08 22:50:38 +02003055 static win_T *wp = NULL;
3056 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003057
3058 if (flag == 'w') // just windows
3059 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003060 if (buf == curbuf || !win_valid(wp))
3061 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003062 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003063
3064 while (TRUE)
3065 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003066 // Move to next window (wrap to first window if at the end)
3067 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3068 // Break if we're back at start or found an unscanned buffer
3069 if (wp == curwin || !wp->w_buffer->b_scanned)
3070 break;
glepnir40891ba2025-02-10 22:18:00 +01003071 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003072 buf = wp->w_buffer;
3073 }
3074 else
glepnir40891ba2025-02-10 22:18:00 +01003075 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003076 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3077 // (unlisted buffers)
3078 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003079 while (TRUE)
3080 {
3081 // Move to next buffer (wrap to first buffer if at the end)
3082 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3083 // Break if we're back at start buffer
3084 if (buf == curbuf)
3085 break;
3086
3087 // Check buffer conditions based on flag
3088 if (flag == 'U')
3089 skip_buffer = buf->b_p_bl;
3090 else
3091 skip_buffer = !buf->b_p_bl ||
3092 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3093
3094 // Break if we found a buffer that matches our criteria
3095 if (!skip_buffer && !buf->b_scanned)
3096 break;
3097 }
3098 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003099 return buf;
3100}
3101
3102#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003103
3104# ifdef FEAT_EVAL
3105static callback_T cfu_cb; // 'completefunc' callback function
3106static callback_T ofu_cb; // 'omnifunc' callback function
3107static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3108# endif
3109
3110/*
3111 * Copy a global callback function to a buffer local callback.
3112 */
3113 static void
3114copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3115{
3116 free_callback(bufcb);
3117 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3118 copy_callback(bufcb, globcb);
3119}
3120
3121/*
3122 * Parse the 'completefunc' option value and set the callback function.
3123 * Invoked when the 'completefunc' option is set. The option value can be a
3124 * name of a function (string), or function(<name>) or funcref(<name>) or a
3125 * lambda expression.
3126 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003127 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003128did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003129{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003130 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3131 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003132
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003133 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003134
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003135 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003136}
3137
3138/*
3139 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003140 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003141 */
3142 void
3143set_buflocal_cfu_callback(buf_T *buf UNUSED)
3144{
3145# ifdef FEAT_EVAL
3146 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3147# endif
3148}
3149
3150/*
3151 * Parse the 'omnifunc' option value and set the callback function.
3152 * Invoked when the 'omnifunc' option is set. The option value can be a
3153 * name of a function (string), or function(<name>) or funcref(<name>) or a
3154 * lambda expression.
3155 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003156 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003157did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003158{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003159 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3160 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003161
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003162 set_buflocal_ofu_callback(curbuf);
3163 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003164}
3165
3166/*
3167 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003168 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003169 */
3170 void
3171set_buflocal_ofu_callback(buf_T *buf UNUSED)
3172{
3173# ifdef FEAT_EVAL
3174 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3175# endif
3176}
3177
3178/*
3179 * Parse the 'thesaurusfunc' option value and set the callback function.
3180 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3181 * name of a function (string), or function(<name>) or funcref(<name>) or a
3182 * lambda expression.
3183 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003184 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003185did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003186{
3187 int retval;
3188
zeertzjq6eda2692024-11-03 09:23:33 +01003189 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003190 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003191 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3192 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003193 else
3194 {
3195 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003196 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003197 // when using :set, free the local callback
3198 if (!(args->os_flags & OPT_GLOBAL))
3199 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003200 }
3201
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003202 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003203}
3204
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003205/*
3206 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003207 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003208 */
3209 int
3210set_ref_in_insexpand_funcs(int copyID)
3211{
glepnir19e1dd62025-05-08 22:50:38 +02003212 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003213 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3214 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3215
3216 return abort;
3217}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003218
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003219/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003220 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003221 */
3222 static char_u *
3223get_complete_funcname(int type)
3224{
3225 switch (type)
3226 {
3227 case CTRL_X_FUNCTION:
3228 return curbuf->b_p_cfu;
3229 case CTRL_X_OMNI:
3230 return curbuf->b_p_ofu;
3231 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003232 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003233 default:
3234 return (char_u *)"";
3235 }
3236}
3237
3238/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003239 * Get the callback to use for insert mode completion.
3240 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003241 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003242get_insert_callback(int type)
3243{
3244 if (type == CTRL_X_FUNCTION)
3245 return &curbuf->b_cfu_cb;
3246 if (type == CTRL_X_OMNI)
3247 return &curbuf->b_ofu_cb;
3248 // CTRL_X_THESAURUS
3249 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3250}
3251
3252/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003253 * Execute user defined complete function 'completefunc', 'omnifunc' or
3254 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003255 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3256 * Callback function "cb" is set if triggered by a function in the 'cpt'
3257 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003258 */
3259 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003260expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003261{
3262 list_T *matchlist = NULL;
3263 dict_T *matchdict = NULL;
3264 typval_T args[3];
3265 char_u *funcname;
3266 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003267 typval_T rettv;
3268 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003269 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003270 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003271
Girish Palyacbe53192025-04-14 22:13:15 +02003272 if (!is_cpt_function)
3273 {
3274 funcname = get_complete_funcname(type);
3275 if (*funcname == NUL)
3276 return;
3277 cb = get_insert_callback(type);
3278 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003279
3280 // Call 'completefunc' to obtain the list of matches.
3281 args[0].v_type = VAR_NUMBER;
3282 args[0].vval.v_number = 0;
3283 args[1].v_type = VAR_STRING;
3284 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3285 args[2].v_type = VAR_UNKNOWN;
3286
3287 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003288 // Lock the text to avoid weird things from happening. Also disallow
3289 // switching to another window, it should not be needed and may end up in
3290 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003291 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003292
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003293 retval = call_callback(cb, 0, &rettv, 2, args);
3294
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003295 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003296 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003297 {
3298 switch (rettv.v_type)
3299 {
3300 case VAR_LIST:
3301 matchlist = rettv.vval.v_list;
3302 break;
3303 case VAR_DICT:
3304 matchdict = rettv.vval.v_dict;
3305 break;
3306 case VAR_SPECIAL:
3307 if (rettv.vval.v_number == VVAL_NONE)
3308 compl_opt_suppress_empty = TRUE;
3309 // FALLTHROUGH
3310 default:
3311 // TODO: Give error message?
3312 clear_tv(&rettv);
3313 break;
3314 }
3315 }
zeertzjqcfe45652022-05-27 17:26:55 +01003316 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003317
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003318 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003319 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003320 validate_cursor();
3321 if (!EQUAL_POS(curwin->w_cursor, pos))
3322 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003323 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003324 goto theend;
3325 }
3326
3327 if (matchlist != NULL)
3328 ins_compl_add_list(matchlist);
3329 else if (matchdict != NULL)
3330 ins_compl_add_dict(matchdict);
3331
3332theend:
3333 // Restore State, it might have been changed.
3334 State = save_State;
3335
3336 if (matchdict != NULL)
3337 dict_unref(matchdict);
3338 if (matchlist != NULL)
3339 list_unref(matchlist);
3340}
3341#endif // FEAT_COMPL_FUNC
3342
3343#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003344
3345 static inline int
3346get_user_highlight_attr(char_u *hlname)
3347{
3348 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003349 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003350 return -1;
3351}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003352/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003353 * Add a match to the list of matches from a typeval_T.
3354 * If the given string is already in the list of completions, then return
3355 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3356 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003357 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003358 */
3359 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003360ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003361{
3362 char_u *word;
3363 int dup = FALSE;
3364 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003365 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003366 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003367 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003368 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003369 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003370 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003371 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003372
Bram Moolenaar08928322020-01-04 14:32:48 +01003373 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003374 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3375 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003376 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3377 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3378 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3379 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3380 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003381
glepnir0fe17f82024-10-08 22:26:44 +02003382 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003383 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003384
3385 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003386 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003387
Bram Moolenaard61efa52022-07-23 09:52:04 +01003388 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3389 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3390 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003391 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003392 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3393 dup = dict_get_number(tv->vval.v_dict, "dup");
3394 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3395 empty = dict_get_number(tv->vval.v_dict, "empty");
3396 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3397 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003398 flags |= CP_EQUAL;
3399 }
3400 else
3401 {
3402 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003403 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003404 }
3405 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003406 {
3407 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003408 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003409 }
glepnir508e7852024-07-25 21:39:08 +02003410 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003411 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003412 if (status != OK)
3413 clear_tv(&user_data);
3414 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003415}
3416
3417/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003418 * Add completions from a list.
3419 */
3420 static void
3421ins_compl_add_list(list_T *list)
3422{
3423 listitem_T *li;
3424 int dir = compl_direction;
3425
3426 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003427 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003428 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003429 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003430 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003431 // if dir was BACKWARD then honor it just once
3432 dir = FORWARD;
3433 else if (did_emsg)
3434 break;
3435 }
3436}
3437
3438/*
3439 * Add completions from a dict.
3440 */
3441 static void
3442ins_compl_add_dict(dict_T *dict)
3443{
3444 dictitem_T *di_refresh;
3445 dictitem_T *di_words;
3446
3447 // Check for optional "refresh" item.
3448 compl_opt_refresh_always = FALSE;
3449 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3450 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3451 {
3452 char_u *v = di_refresh->di_tv.vval.v_string;
3453
3454 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3455 compl_opt_refresh_always = TRUE;
3456 }
3457
3458 // Add completions from a "words" list.
3459 di_words = dict_find(dict, (char_u *)"words", 5);
3460 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3461 ins_compl_add_list(di_words->di_tv.vval.v_list);
3462}
3463
3464/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003465 * Start completion for the complete() function.
3466 * "startcol" is where the matched text starts (1 is first column).
3467 * "list" is the list of matches.
3468 */
3469 static void
3470set_completion(colnr_T startcol, list_T *list)
3471{
3472 int save_w_wrow = curwin->w_wrow;
3473 int save_w_leftcol = curwin->w_leftcol;
3474 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003475 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003476 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3477 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3478 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003479
3480 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003481 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003482 ins_compl_prep(' ');
3483 ins_compl_clear();
3484 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003485 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003486
3487 compl_direction = FORWARD;
3488 if (startcol > curwin->w_cursor.col)
3489 startcol = curwin->w_cursor.col;
3490 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003491 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003492 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3493 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003494 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3495 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003496 if (p_ic)
3497 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003498 if (compl_orig_text.string == NULL)
3499 {
3500 compl_orig_text.length = 0;
3501 return;
3502 }
3503 compl_orig_text.length = (size_t)compl_length;
3504 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003505 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3506 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003507 return;
3508
3509 ctrl_x_mode = CTRL_X_EVAL;
3510
3511 ins_compl_add_list(list);
3512 compl_matches = ins_compl_make_cyclic();
3513 compl_started = TRUE;
3514 compl_used_match = TRUE;
3515 compl_cont_status = 0;
3516
3517 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003518 int no_select = compl_no_select || compl_longest;
3519 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003520 {
3521 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003522 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003523 // Down/Up has no real effect.
3524 ins_complete(K_UP, FALSE);
3525 }
3526 else
3527 ins_complete(Ctrl_N, FALSE);
3528 compl_enter_selects = compl_no_insert;
3529
3530 // Lazily show the popup menu, unless we got interrupted.
3531 if (!compl_interrupted)
3532 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003533 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003534 out_flush();
3535}
3536
3537/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003538 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003539 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003540 void
3541f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003542{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003543 if (in_vim9script()
3544 && (check_for_number_arg(argvars, 0) == FAIL
3545 || check_for_list_arg(argvars, 1) == FAIL))
3546 return;
3547
Bram Moolenaar24959102022-05-07 20:01:16 +01003548 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003549 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003550 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003551 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003552 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003553
3554 // Check for undo allowed here, because if something was already inserted
3555 // the line was already saved for undo and this check isn't done.
3556 if (!undo_allowed())
3557 return;
3558
Bram Moolenaard83392a2022-09-01 12:22:46 +01003559 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003560 {
glepnir19e1dd62025-05-08 22:50:38 +02003561 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003562 if (startcol > 0)
3563 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003564 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003565}
3566
3567/*
3568 * "complete_add()" function
3569 */
3570 void
3571f_complete_add(typval_T *argvars, typval_T *rettv)
3572{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003573 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003574 return;
3575
Bram Moolenaar440cf092021-04-03 20:13:30 +02003576 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003577}
3578
3579/*
3580 * "complete_check()" function
3581 */
3582 void
3583f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3584{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003585 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003586 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003587
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003588 ins_compl_check_keys(0, TRUE);
3589 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003590
3591 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003592}
3593
3594/*
glepnirbcd59952025-04-24 21:48:35 +02003595 * Add match item to the return list.
3596 * Returns FAIL if out of memory, OK otherwise.
3597 */
3598 static int
3599add_match_to_list(
3600 typval_T *rettv,
3601 char_u *str,
3602 int len,
3603 int pos)
3604{
3605 list_T *match;
3606 int ret;
3607
3608 match = list_alloc();
3609 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003610 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003611
3612 if ((ret = list_append_number(match, pos + 1)) == FAIL
3613 || (ret = list_append_string(match, str, len)) == FAIL
3614 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3615 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003616 vim_free(match);
3617 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003618 }
3619
3620 return OK;
3621}
3622
3623/*
3624 * "complete_match()" function
3625 */
3626 void
3627f_complete_match(typval_T *argvars, typval_T *rettv)
3628{
3629 linenr_T lnum;
3630 colnr_T col;
3631 char_u *line = NULL;
3632 char_u *ise = NULL;
3633 regmatch_T regmatch;
3634 char_u *before_cursor = NULL;
3635 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003636 int bytepos = 0;
3637 char_u part[MAXPATHL];
3638 int ret;
3639
3640 if (rettv_list_alloc(rettv) == FAIL)
3641 return;
3642
3643 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3644
3645 if (argvars[0].v_type == VAR_UNKNOWN)
3646 {
3647 lnum = curwin->w_cursor.lnum;
3648 col = curwin->w_cursor.col;
3649 }
3650 else if (argvars[1].v_type == VAR_UNKNOWN)
3651 {
3652 emsg(_(e_invalid_argument));
3653 return;
3654 }
3655 else
3656 {
3657 lnum = (linenr_T)tv_get_number(&argvars[0]);
3658 col = (colnr_T)tv_get_number(&argvars[1]);
3659 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3660 {
3661 semsg(_(e_invalid_line_number_nr), lnum);
3662 return;
3663 }
3664 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3665 {
3666 semsg(_(e_invalid_column_number_nr), col + 1);
3667 return;
3668 }
3669 }
3670
3671 line = ml_get_buf(curbuf, lnum, FALSE);
3672 if (line == NULL)
3673 return;
3674
3675 before_cursor = vim_strnsave(line, col);
3676 if (before_cursor == NULL)
3677 return;
3678
3679 if (ise == NULL || *ise == NUL)
3680 {
3681 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3682 if (regmatch.regprog != NULL)
3683 {
3684 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3685 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003686 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003687 regmatch.endp[0] - regmatch.startp[0]);
3688 if (trig == NULL)
3689 {
3690 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003691 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003692 return;
3693 }
3694
Christian Brabandt3accf042025-04-25 19:01:06 +02003695 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003696 ret = add_match_to_list(rettv, trig, -1, bytepos);
3697 vim_free(trig);
3698 if (ret == FAIL)
3699 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003700 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003701 vim_regfree(regmatch.regprog);
3702 return;
3703 }
3704 }
3705 vim_regfree(regmatch.regprog);
3706 }
3707 }
3708 else
3709 {
glepnir08db2f42025-05-14 20:26:19 +02003710 char_u *p = ise;
3711 char_u *p_space = NULL;
3712
glepnirbcd59952025-04-24 21:48:35 +02003713 cur_end = before_cursor + (int)STRLEN(before_cursor);
3714
3715 while (*p != NUL)
3716 {
glepnir8d0e42b2025-05-12 20:28:28 +02003717 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003718 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003719 {
glepnir08db2f42025-05-14 20:26:19 +02003720 len = p - p_space - 1;
3721 memcpy(part, p_space + 1, len);
3722 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003723 }
3724 else
glepnir08db2f42025-05-14 20:26:19 +02003725 {
3726 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3727 if (next_comma && *(next_comma + 1) == ' ')
3728 p_space = next_comma;
3729
glepnir8d0e42b2025-05-12 20:28:28 +02003730 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003731 }
glepnirbcd59952025-04-24 21:48:35 +02003732
3733 if (len > 0 && len <= col)
3734 {
3735 if (STRNCMP(cur_end - len, part, len) == 0)
3736 {
3737 bytepos = col - len;
3738 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3739 {
3740 vim_free(before_cursor);
3741 return;
3742 }
3743 }
3744 }
3745 }
3746 }
3747
3748 vim_free(before_cursor);
3749}
3750
3751/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003752 * Return Insert completion mode name string
3753 */
3754 static char_u *
3755ins_compl_mode(void)
3756{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003757 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003758 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3759
3760 return (char_u *)"";
3761}
3762
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003763/*
3764 * Assign the sequence number to all the completion matches which don't have
3765 * one assigned yet.
3766 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003767 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003768ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003769{
3770 int number = 0;
3771 compl_T *match;
3772
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003773 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003774 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003775 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003776 // This should normally succeed already at the first loop
3777 // cycle, so it's fast!
3778 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003779 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003780 if (match->cp_number != -1)
3781 {
3782 number = match->cp_number;
3783 break;
3784 }
3785 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003786 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003787 for (match = match->cp_next;
3788 match != NULL && match->cp_number == -1;
3789 match = match->cp_next)
3790 match->cp_number = ++number;
3791 }
3792 else // BACKWARD
3793 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003794 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003795 // number. This should normally succeed already at the
3796 // first loop cycle, so it's fast!
3797 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003798 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003799 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003800 if (match->cp_number != -1)
3801 {
3802 number = match->cp_number;
3803 break;
3804 }
glepnir40891ba2025-02-10 22:18:00 +01003805 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003806 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003807 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003808 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003809 for (match = match->cp_prev; match
3810 && match->cp_number == -1;
3811 match = match->cp_prev)
3812 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003813 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003814 }
3815}
3816
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003817/*
glepnir037b0282025-01-16 14:37:44 +01003818 * Fill the dict of complete_info
3819 */
3820 static void
3821fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3822{
3823 dict_add_string(di, "word", match->cp_str.string);
3824 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3825 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3826 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3827 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3828 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003829 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003830 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003831 // Add an empty string for backwards compatibility
3832 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003833 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003834 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003835}
3836
3837/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003838 * Get complete information
3839 */
3840 static void
3841get_complete_info(list_T *what_list, dict_T *retdict)
3842{
3843 int ret = OK;
3844 listitem_T *item;
3845#define CI_WHAT_MODE 0x01
3846#define CI_WHAT_PUM_VISIBLE 0x02
3847#define CI_WHAT_ITEMS 0x04
3848#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003849#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003850#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003851#define CI_WHAT_ALL 0xff
3852 int what_flag;
3853
3854 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003855 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003856 else
3857 {
3858 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003859 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003860 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003861 {
3862 char_u *what = tv_get_string(&item->li_tv);
3863
3864 if (STRCMP(what, "mode") == 0)
3865 what_flag |= CI_WHAT_MODE;
3866 else if (STRCMP(what, "pum_visible") == 0)
3867 what_flag |= CI_WHAT_PUM_VISIBLE;
3868 else if (STRCMP(what, "items") == 0)
3869 what_flag |= CI_WHAT_ITEMS;
3870 else if (STRCMP(what, "selected") == 0)
3871 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003872 else if (STRCMP(what, "completed") == 0)
3873 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003874 else if (STRCMP(what, "matches") == 0)
3875 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003876 }
3877 }
3878
3879 if (ret == OK && (what_flag & CI_WHAT_MODE))
3880 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3881
3882 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3883 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3884
glepnir037b0282025-01-16 14:37:44 +01003885 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3886 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003887 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003888 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003889 dict_T *di;
3890 compl_T *match;
3891 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003892 int has_items = what_flag & CI_WHAT_ITEMS;
3893 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003894 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003895
glepnird4088ed2024-12-31 10:55:22 +01003896 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003897 {
3898 li = list_alloc();
3899 if (li == NULL)
3900 return;
glepnird4088ed2024-12-31 10:55:22 +01003901 ret = dict_add_list(retdict, (has_matches && !has_items)
3902 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003903 }
3904 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3905 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3906 ins_compl_update_sequence_numbers();
3907 if (ret == OK && compl_first_match != NULL)
3908 {
3909 int list_idx = 0;
3910 match = compl_first_match;
3911 do
3912 {
3913 if (!match_at_original_text(match))
3914 {
glepnird4088ed2024-12-31 10:55:22 +01003915 if (has_items
3916 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003917 {
3918 di = dict_alloc();
3919 if (di == NULL)
3920 return;
3921 ret = list_append_dict(li, di);
3922 if (ret != OK)
3923 return;
glepnir037b0282025-01-16 14:37:44 +01003924 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003925 }
glepnird4088ed2024-12-31 10:55:22 +01003926 if (compl_curr_match != NULL
3927 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003928 selected_idx = list_idx;
Girish Palya8cd42a52025-06-05 21:04:29 +02003929 if (match->cp_in_match_array)
Girish Palya0ac1eb32025-04-16 20:18:33 +02003930 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003931 }
3932 match = match->cp_next;
3933 }
3934 while (match != NULL && !is_first_match(match));
3935 }
3936 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3937 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003938
glepnir037b0282025-01-16 14:37:44 +01003939 if (ret == OK && selected_idx != -1 && has_completed)
3940 {
3941 di = dict_alloc();
3942 if (di == NULL)
3943 return;
3944 fill_complete_info_dict(di, compl_curr_match, FALSE);
3945 ret = dict_add_dict(retdict, "completed", di);
3946 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003947 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003948}
3949
3950/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003951 * "complete_info()" function
3952 */
3953 void
3954f_complete_info(typval_T *argvars, typval_T *rettv)
3955{
3956 list_T *what_list = NULL;
3957
Bram Moolenaar93a10962022-06-16 11:42:09 +01003958 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003959 return;
3960
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003961 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3962 return;
3963
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003964 if (argvars[0].v_type != VAR_UNKNOWN)
3965 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003966 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003967 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003968 what_list = argvars[0].vval.v_list;
3969 }
3970 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003971}
3972#endif
3973
3974/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003975 * Returns TRUE when using a user-defined function for thesaurus completion.
3976 */
3977 static int
3978thesaurus_func_complete(int type UNUSED)
3979{
3980#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003981 return type == CTRL_X_THESAURUS
3982 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003983#else
3984 return FALSE;
3985#endif
3986}
3987
3988/*
Girish Palya7c621052025-05-26 19:41:59 +02003989 * Check if 'cpt' list index can be advanced to the next completion source.
3990 */
3991 static int
3992may_advance_cpt_index(char_u *cpt)
3993{
3994 char_u *p = cpt;
3995
Girish Palya98c29db2025-06-01 19:40:00 +02003996 if (cpt_sources_index == -1)
3997 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02003998 while (*p == ',' || *p == ' ') // Skip delimiters
3999 p++;
4000 return (*p != NUL);
4001}
4002
4003/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004004 * Return value of process_next_cpt_value()
4005 */
4006enum
4007{
4008 INS_COMPL_CPT_OK = 1,
4009 INS_COMPL_CPT_CONT,
4010 INS_COMPL_CPT_END
4011};
4012
4013/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004014 * state information used for getting the next set of insert completion
4015 * matches.
4016 */
4017typedef struct
4018{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004019 char_u *e_cpt_copy; // copy of 'complete'
4020 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004021 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004022 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004023 pos_T prev_match_pos; // previous match position
4024 int set_match_pos; // save first_match_pos/last_match_pos
4025 pos_T first_match_pos; // first match position
4026 pos_T last_match_pos; // last match position
4027 int found_all; // found all matches of a certain type.
4028 char_u *dict; // dictionary file to search
4029 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02004030 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004031} ins_compl_next_state_T;
4032
4033/*
4034 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004035 *
4036 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004037 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004038 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004039 * st->found_all - all matches of this type are found
4040 * st->ins_buf - search for completions in this buffer
4041 * st->first_match_pos - position of the first completion match
4042 * st->last_match_pos - position of the last completion match
4043 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004044 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004045 * st->dict - name of the dictionary or thesaurus file to search
4046 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004047 *
4048 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004049 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4050 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004051 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004052 */
4053 static int
4054process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004055 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004056 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004057 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004058 int fuzzy_collect,
4059 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004060{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004061 int compl_type = -1;
4062 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004063
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004064 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004065 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004066
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004067 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4068 st->e_cpt++;
4069
4070 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004071 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004072 st->ins_buf = curbuf;
4073 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004074 // Move the cursor back one character so that ^N can match the
4075 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004076 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004077 {
4078 // Move the cursor to after the last character in the
4079 // buffer, so that word at start of buffer is found
4080 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004081 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004082 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004083 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004084 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004085 compl_type = 0;
4086
4087 // Remember the first match so that the loop stops when we
4088 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004089 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004090 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004091 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004092 && (st->ins_buf = ins_compl_next_buf(
4093 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004094 {
4095 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004096 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004097 {
4098 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004099 st->first_match_pos.col = st->last_match_pos.col = 0;
4100 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4101 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004102 compl_type = 0;
4103 }
4104 else // unloaded buffer, scan like dictionary
4105 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004106 st->found_all = TRUE;
4107 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004108 {
4109 status = INS_COMPL_CPT_CONT;
4110 goto done;
4111 }
4112 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004113 st->dict = st->ins_buf->b_fname;
4114 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004115 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004116 if (!shortmess(SHM_COMPLETIONSCAN))
4117 {
4118 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4119 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4120 st->ins_buf->b_fname == NULL
4121 ? buf_spname(st->ins_buf)
4122 : st->ins_buf->b_sfname == NULL
4123 ? st->ins_buf->b_fname
4124 : st->ins_buf->b_sfname);
4125 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4126 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004127 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004128 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004129 status = INS_COMPL_CPT_END;
4130 else
4131 {
4132 if (ctrl_x_mode_line_or_eval())
4133 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004134 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004135 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004136 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004137 compl_type = CTRL_X_DICTIONARY;
4138 else
4139 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004140 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004141 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004142 st->dict = st->e_cpt;
4143 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004144 }
4145 }
Girish Palyacbe53192025-04-14 22:13:15 +02004146#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004147 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004148 {
4149 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004150 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004151 if (!st->func_cb)
4152 compl_type = -1;
4153 }
4154#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004155#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004156 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004157 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004158 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004159 compl_type = CTRL_X_PATH_DEFINES;
4160#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004161 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004162 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004163 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004164 if (!shortmess(SHM_COMPLETIONSCAN))
4165 {
4166 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4167 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4168 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4169 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004170 }
4171 else
4172 compl_type = -1;
4173
4174 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004175 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004176 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004177
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004178 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004179 if (compl_type == -1)
4180 status = INS_COMPL_CPT_CONT;
4181 }
4182
4183done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004184 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004185 return status;
4186}
4187
4188#ifdef FEAT_FIND_ID
4189/*
4190 * Get the next set of identifiers or defines matching "compl_pattern" in
4191 * included files.
4192 */
4193 static void
4194get_next_include_file_completion(int compl_type)
4195{
John Marriott5e6ea922024-11-23 14:01:57 +01004196 find_pattern_in_path(compl_pattern.string, compl_direction,
4197 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004198 (compl_type == CTRL_X_PATH_DEFINES
4199 && !(compl_cont_status & CONT_SOL))
4200 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004201 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004202}
4203#endif
4204
4205/*
4206 * Get the next set of words matching "compl_pattern" in dictionary or
4207 * thesaurus files.
4208 */
4209 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004210get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004211{
4212#ifdef FEAT_COMPL_FUNC
4213 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004214 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004215 else
4216#endif
4217 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004218 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004219 : (compl_type == CTRL_X_THESAURUS
4220 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4221 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004222 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004223 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004224 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004225}
4226
4227/*
4228 * Get the next set of tag names matching "compl_pattern".
4229 */
4230 static void
4231get_next_tag_completion(void)
4232{
4233 int save_p_ic;
4234 char_u **matches;
4235 int num_matches;
4236
4237 // set p_ic according to p_ic, p_scs and pat for find_tags().
4238 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004239 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004240
4241 // Find up to TAG_MANY matches. Avoids that an enormous number
4242 // of matches is found when compl_pattern is empty
4243 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004244 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004245 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004246 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004247 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4248 ins_compl_add_matches(num_matches, matches, p_ic);
4249 g_tag_at_cursor = FALSE;
4250 p_ic = save_p_ic;
4251}
4252
4253/*
glepnir8159fb12024-07-17 20:32:54 +02004254 * Compare function for qsort
4255 */
glepnirf31cfa22025-03-06 21:59:13 +01004256 static int
4257compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004258{
4259 int idx_a = *(const int *)a;
4260 int idx_b = *(const int *)b;
4261 int score_a = compl_fuzzy_scores[idx_a];
4262 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004263 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4264 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004265}
4266
4267/*
glepnirf31cfa22025-03-06 21:59:13 +01004268 * insert prefix with redraw
4269 */
4270 static void
4271ins_compl_longest_insert(char_u *prefix)
4272{
4273 ins_compl_delete();
4274 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4275 ins_redraw(FALSE);
4276}
4277
4278/*
4279 * Calculate the longest common prefix among the best fuzzy matches
4280 * stored in compl_best_matches, and insert it as the longest.
4281 */
4282 static void
4283fuzzy_longest_match(void)
4284{
4285 char_u *prefix = NULL;
4286 int prefix_len = 0;
4287 int i = 0;
4288 int j = 0;
4289 char_u *match_str = NULL;
4290 char_u *prefix_ptr = NULL;
4291 char_u *match_ptr = NULL;
4292 char_u *leader = NULL;
4293 size_t leader_len = 0;
4294 compl_T *compl = NULL;
4295 int more_candidates = FALSE;
4296 compl_T *nn_compl = NULL;
4297
4298 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004299 return;
glepnirf31cfa22025-03-06 21:59:13 +01004300
4301 nn_compl = compl_first_match->cp_next->cp_next;
4302 if (nn_compl && nn_compl != compl_first_match)
4303 more_candidates = TRUE;
4304
4305 compl = ctrl_x_mode_whole_line() ? compl_first_match
4306 : compl_first_match->cp_next;
4307 if (compl_num_bests == 1)
4308 {
4309 // no more candidates insert the match str
4310 if (!more_candidates)
4311 {
4312 ins_compl_longest_insert(compl->cp_str.string);
4313 compl_num_bests = 0;
4314 }
4315 compl_num_bests = 0;
4316 return;
4317 }
4318
4319 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4320 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004321 return;
glepnirf31cfa22025-03-06 21:59:13 +01004322 while (compl != NULL && i < compl_num_bests)
4323 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004324 compl_best_matches[i] = compl;
4325 compl = compl->cp_next;
4326 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004327 }
4328
4329 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004330 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004331
4332 for (i = 1; i < compl_num_bests; i++)
4333 {
4334 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004335 prefix_ptr = prefix;
4336 match_ptr = match_str;
4337 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004338
4339 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4340 {
4341 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4342 break;
4343
4344 MB_PTR_ADV(prefix_ptr);
4345 MB_PTR_ADV(match_ptr);
4346 j++;
4347 }
4348
4349 if (j > 0)
4350 prefix_len = j;
4351 }
4352
4353 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004354 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004355
4356 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004357 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004358 goto end;
4359
zeertzjq4422de62025-03-07 19:06:02 +01004360 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004361 if (prefix != NULL)
4362 {
4363 ins_compl_longest_insert(prefix);
4364 compl_cfc_longest_ins = TRUE;
4365 vim_free(prefix);
4366 }
4367
4368end:
4369 vim_free(compl_best_matches);
4370 compl_best_matches = NULL;
4371 compl_num_bests = 0;
4372}
4373
4374/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004375 * Get the next set of filename matching "compl_pattern".
4376 */
4377 static void
4378get_next_filename_completion(void)
4379{
4380 char_u **matches;
4381 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004382 char_u *ptr;
4383 garray_T fuzzy_indices;
4384 int i;
4385 int score;
4386 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004387 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004388 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004389 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004390 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004391 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4392 int max_score = 0;
4393 int current_score = 0;
4394 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004395
glepnirb9de1a02024-08-02 19:14:38 +02004396#ifdef BACKSLASH_IN_FILENAME
4397 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4398 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4399#else
4400 char pathsep = PATHSEP;
4401#endif
4402
glepnirf31cfa22025-03-06 21:59:13 +01004403 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004404 {
glepnirb9de1a02024-08-02 19:14:38 +02004405#ifdef BACKSLASH_IN_FILENAME
4406 if (curbuf->b_p_csl[0] == 's')
4407 {
John Marriott5e6ea922024-11-23 14:01:57 +01004408 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004409 {
4410 if (leader[i] == '\\')
4411 leader[i] = '/';
4412 }
4413 }
4414 else if (curbuf->b_p_csl[0] == 'b')
4415 {
John Marriott5e6ea922024-11-23 14:01:57 +01004416 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004417 {
4418 if (leader[i] == '/')
4419 leader[i] = '\\';
4420 }
4421 }
4422#endif
4423 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004424 if (last_sep == NULL)
4425 {
4426 // No path separator or separator is the last character,
4427 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004428 VIM_CLEAR_STRING(compl_pattern);
4429 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4430 if (compl_pattern.string == NULL)
4431 return;
4432 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004433 }
4434 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004435 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004436 else
4437 {
4438 // Split leader into path and file parts
4439 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004440 char_u *path_with_wildcard;
4441
4442 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004443 if (path_with_wildcard != NULL)
4444 {
John Marriott5e6ea922024-11-23 14:01:57 +01004445 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4446 VIM_CLEAR_STRING(compl_pattern);
4447 compl_pattern.string = path_with_wildcard;
4448 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004449
4450 // Move leader to the file part
4451 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004452 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004453 }
4454 }
glepnir8159fb12024-07-17 20:32:54 +02004455 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004456
John Marriott5e6ea922024-11-23 14:01:57 +01004457 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004458 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4459 return;
4460
4461 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004462 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004463#ifdef BACKSLASH_IN_FILENAME
4464 if (curbuf->b_p_csl[0] != NUL)
4465 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004466 for (i = 0; i < num_matches; ++i)
4467 {
glepnir8159fb12024-07-17 20:32:54 +02004468 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004469 while (*ptr != NUL)
4470 {
4471 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4472 *ptr = '/';
4473 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4474 *ptr = '\\';
4475 ptr += (*mb_ptr2len)(ptr);
4476 }
4477 }
4478 }
4479#endif
glepnir8159fb12024-07-17 20:32:54 +02004480
glepnirf31cfa22025-03-06 21:59:13 +01004481 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004482 {
4483 ga_init2(&fuzzy_indices, sizeof(int), 10);
4484 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4485
4486 for (i = 0; i < num_matches; i++)
4487 {
4488 ptr = matches[i];
4489 score = fuzzy_match_str(ptr, leader);
4490 if (score > 0)
4491 {
4492 if (ga_grow(&fuzzy_indices, 1) == OK)
4493 {
4494 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4495 compl_fuzzy_scores[i] = score;
4496 fuzzy_indices.ga_len++;
4497 }
4498 }
4499 }
4500
Christian Brabandt220474d2024-07-20 13:26:44 +02004501 // prevent qsort from deref NULL pointer
4502 if (fuzzy_indices.ga_len > 0)
4503 {
glepnirf31cfa22025-03-06 21:59:13 +01004504 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004505 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4506 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004507
Christian Brabandt220474d2024-07-20 13:26:44 +02004508 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004509 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004510 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004511 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4512 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004513 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4514 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004515 dir = FORWARD;
4516
4517 if (need_collect_bests)
4518 {
4519 if (i == 0 || current_score == max_score)
4520 {
4521 compl_num_bests++;
4522 max_score = current_score;
4523 }
4524 }
4525 }
glepnir8159fb12024-07-17 20:32:54 +02004526
Christian Brabandt220474d2024-07-20 13:26:44 +02004527 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004528 }
glepnir6b6280c2024-07-27 16:25:45 +02004529 else if (leader_len > 0)
4530 {
4531 FreeWild(num_matches, matches);
4532 num_matches = 0;
4533 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004534
glepnir8159fb12024-07-17 20:32:54 +02004535 vim_free(compl_fuzzy_scores);
4536 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004537
4538 if (compl_num_bests > 0 && compl_get_longest)
4539 fuzzy_longest_match();
4540 return;
glepnir8159fb12024-07-17 20:32:54 +02004541 }
4542
glepnir6b6280c2024-07-27 16:25:45 +02004543 if (num_matches > 0)
4544 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004545}
4546
4547/*
4548 * Get the next set of command-line completions matching "compl_pattern".
4549 */
4550 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004551get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004552{
4553 char_u **matches;
4554 int num_matches;
4555
John Marriott5e6ea922024-11-23 14:01:57 +01004556 if (expand_cmdline(&compl_xp, compl_pattern.string,
4557 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004558 ins_compl_add_matches(num_matches, matches, FALSE);
4559}
4560
4561/*
4562 * Get the next set of spell suggestions matching "compl_pattern".
4563 */
4564 static void
4565get_next_spell_completion(linenr_T lnum UNUSED)
4566{
4567#ifdef FEAT_SPELL
4568 char_u **matches;
4569 int num_matches;
4570
John Marriott5e6ea922024-11-23 14:01:57 +01004571 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004572 if (num_matches > 0)
4573 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004574 else
4575 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004576#endif
4577}
4578
4579/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004580 * Return the next word or line from buffer "ins_buf" at position
4581 * "cur_match_pos" for completion. The length of the match is set in "len".
4582 */
4583 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004584ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004585 buf_T *ins_buf, // buffer being scanned
4586 pos_T *cur_match_pos, // current match position
4587 int *match_len,
4588 int *cont_s_ipos) // next ^X<> will set initial_pos
4589{
4590 char_u *ptr;
4591 int len;
4592
4593 *match_len = 0;
4594 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4595 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004596 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004597 if (ctrl_x_mode_line_or_eval())
4598 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004599 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004600 {
4601 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4602 return NULL;
4603 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004604 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004605 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004606 {
4607 char_u *tmp_ptr = ptr;
4608
4609 ptr = skipwhite(tmp_ptr);
4610 len -= (int)(ptr - tmp_ptr);
4611 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004612 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004613 }
4614 else
4615 {
4616 char_u *tmp_ptr = ptr;
4617
John Marriott5e6ea922024-11-23 14:01:57 +01004618 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004619 {
4620 tmp_ptr += compl_length;
4621 // Skip if already inside a word.
4622 if (vim_iswordp(tmp_ptr))
4623 return NULL;
4624 // Find start of next word.
4625 tmp_ptr = find_word_start(tmp_ptr);
4626 }
4627 // Find end of this word.
4628 tmp_ptr = find_word_end(tmp_ptr);
4629 len = (int)(tmp_ptr - ptr);
4630
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004631 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004632 {
4633 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4634 {
4635 // Try next line, if any. the new word will be
4636 // "join" as if the normal command "J" was used.
4637 // IOSIZE is always greater than
4638 // compl_length, so the next STRNCPY always
4639 // works -- Acevedo
4640 STRNCPY(IObuff, ptr, len);
4641 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4642 tmp_ptr = ptr = skipwhite(ptr);
4643 // Find start of next word.
4644 tmp_ptr = find_word_start(tmp_ptr);
4645 // Find end of next word.
4646 tmp_ptr = find_word_end(tmp_ptr);
4647 if (tmp_ptr > ptr)
4648 {
4649 if (*ptr != ')' && IObuff[len - 1] != TAB)
4650 {
4651 if (IObuff[len - 1] != ' ')
4652 IObuff[len++] = ' ';
4653 // IObuf =~ "\k.* ", thus len >= 2
4654 if (p_js
4655 && (IObuff[len - 2] == '.'
4656 || (vim_strchr(p_cpo, CPO_JOINSP)
4657 == NULL
4658 && (IObuff[len - 2] == '?'
4659 || IObuff[len - 2] == '!'))))
4660 IObuff[len++] = ' ';
4661 }
4662 // copy as much as possible of the new word
4663 if (tmp_ptr - ptr >= IOSIZE - len)
4664 tmp_ptr = ptr + IOSIZE - len - 1;
4665 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4666 len += (int)(tmp_ptr - ptr);
4667 *cont_s_ipos = TRUE;
4668 }
4669 IObuff[len] = NUL;
4670 ptr = IObuff;
4671 }
4672 if (len == compl_length)
4673 return NULL;
4674 }
4675 }
4676
4677 *match_len = len;
4678 return ptr;
4679}
4680
4681/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004682 * Get the next set of words matching "compl_pattern" for default completion(s)
4683 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004684 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4685 * position "st->start_pos" in the "compl_direction" direction. If
4686 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4687 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004688 * Returns OK if a new next match is found, otherwise returns FAIL.
4689 */
4690 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004691get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004692{
4693 int found_new_match = FAIL;
4694 int save_p_scs;
4695 int save_p_ws;
4696 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004697 char_u *ptr = NULL;
4698 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004699 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004700 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004701 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004702 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004703
4704 // If 'infercase' is set, don't use 'smartcase' here
4705 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004706 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004707 p_scs = FALSE;
4708
4709 // Buffers other than curbuf are scanned from the beginning or the
4710 // end but never from the middle, thus setting nowrapscan in this
4711 // buffer is a good idea, on the other hand, we always set
4712 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4713 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004714 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004715 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004716 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004717 p_ws = TRUE;
4718 looped_around = FALSE;
4719 for (;;)
4720 {
4721 int cont_s_ipos = FALSE;
4722
4723 ++msg_silent; // Don't want messages for wrapscan.
4724
glepnirf31cfa22025-03-06 21:59:13 +01004725 if (in_collect)
4726 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004727 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004728 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004729 start_pos, &len, &ptr, &score);
4730 }
4731 // ctrl_x_mode_line_or_eval() || word-wise search that
4732 // has added a word that was at the beginning of the line
4733 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4734 found_new_match = search_for_exact_line(st->ins_buf,
4735 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004736 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004737 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004738 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004739 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004740 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004741 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004742 {
4743 // set "compl_started" even on fail
4744 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004745 st->first_match_pos = *st->cur_match_pos;
4746 st->last_match_pos = *st->cur_match_pos;
4747 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004748 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004749 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4750 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004751 {
4752 found_new_match = FAIL;
4753 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004754 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004755 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4756 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4757 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004758 {
4759 if (looped_around)
4760 found_new_match = FAIL;
4761 else
4762 looped_around = TRUE;
4763 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004764 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004765 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4766 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4767 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004768 {
4769 if (looped_around)
4770 found_new_match = FAIL;
4771 else
4772 looped_around = TRUE;
4773 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004774 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004775 if (found_new_match == FAIL)
4776 break;
4777
4778 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004779 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004780 && start_pos->lnum == st->cur_match_pos->lnum
4781 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004782 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004783
glepnirf31cfa22025-03-06 21:59:13 +01004784 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004785 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4786 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004787 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004788 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004789
Girish Palyab1565882025-04-15 20:16:00 +02004790 if (is_nearest_active() && in_curbuf)
4791 {
4792 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4793 if (score < 0)
4794 score = -score;
4795 score++;
4796 }
4797
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004798 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004799 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004800 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004801 {
glepnirf31cfa22025-03-06 21:59:13 +01004802 if (in_collect && score == compl_first_match->cp_next->cp_score)
4803 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004804 found_new_match = OK;
4805 break;
4806 }
4807 }
4808 p_scs = save_p_scs;
4809 p_ws = save_p_ws;
4810
4811 return found_new_match;
4812}
4813
Girish Palyacbe53192025-04-14 22:13:15 +02004814#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004815/*
4816 * Return the callback function associated with "p" if it points to a
4817 * userfunc.
4818 */
Girish Palyacbe53192025-04-14 22:13:15 +02004819 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004820get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004821{
4822 static callback_T cb;
4823 char_u buf[LSIZE];
4824 int slen;
4825
Girish Palya98c29db2025-06-01 19:40:00 +02004826 if (*p == 'o')
4827 return &curbuf->b_ofu_cb;
4828 if (*p == 'F')
4829 {
4830 if (*++p != ',' && *p != NUL)
4831 {
4832 free_callback(&cb);
4833 slen = copy_option_part(&p, buf, LSIZE, ",");
4834 if (slen > 0 && option_set_callback_func(buf, &cb))
4835 return &cb;
4836 return NULL;
4837 }
4838 else
4839 return &curbuf->b_cfu_cb;
4840 }
Girish Palyacbe53192025-04-14 22:13:15 +02004841 return NULL;
4842}
4843
4844/*
4845 * Retrieve new completion matches by invoking callback "cb".
4846 */
4847 static void
4848expand_cpt_function(callback_T *cb)
4849{
4850 // Re-insert the text removed by ins_compl_delete().
4851 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4852 // Get matches
4853 get_cpt_func_completion_matches(cb);
4854 // Undo insertion
4855 ins_compl_delete();
4856}
4857#endif
4858
4859/*
glepnir05460682025-05-26 18:23:27 +02004860 * Get completion matches from register contents.
4861 * Extracts words from all available registers and adds them to the completion list.
4862 */
4863 static void
4864get_register_completion(void)
4865{
4866 int dir = compl_direction;
4867 yankreg_T *reg = NULL;
4868 void *reg_ptr = NULL;
glepnir86d46a72025-06-03 21:04:44 +02004869 int adding_mode = compl_status_adding();
glepnir05460682025-05-26 18:23:27 +02004870
4871 for (int i = 0; i < NUM_REGISTERS; i++)
4872 {
4873 int regname = 0;
glepnir05460682025-05-26 18:23:27 +02004874 if (i == 0)
4875 regname = '"'; // unnamed register
4876 else if (i < 10)
4877 regname = '0' + i;
4878 else if (i == DELETION_REGISTER)
4879 regname = '-';
4880#ifdef FEAT_CLIPBOARD
4881 else if (i == STAR_REGISTER)
4882 regname = '*';
4883 else if (i == PLUS_REGISTER)
4884 regname = '+';
4885#endif
4886 else
4887 regname = 'a' + i - 10;
4888
4889 // Skip invalid or black hole register
4890 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4891 continue;
4892
4893 reg_ptr = get_register(regname, FALSE);
4894 if (reg_ptr == NULL)
4895 continue;
4896
4897 reg = (yankreg_T *)reg_ptr;
4898
glepnir86d46a72025-06-03 21:04:44 +02004899 for (int j = 0; j < reg->y_size; j++)
glepnir05460682025-05-26 18:23:27 +02004900 {
glepnir86d46a72025-06-03 21:04:44 +02004901 char_u *str = reg->y_array[j].string;
4902 if (str == NULL)
4903 continue;
glepnir05460682025-05-26 18:23:27 +02004904
glepnir86d46a72025-06-03 21:04:44 +02004905 if (adding_mode)
4906 {
glepnird5fdfa52025-06-02 19:45:41 +02004907 int str_len = (int)STRLEN(str);
4908 if (str_len == 0)
4909 continue;
glepnir05460682025-05-26 18:23:27 +02004910
glepnird5fdfa52025-06-02 19:45:41 +02004911 if (!compl_orig_text.string
4912 || (p_ic ? STRNICMP(str, compl_orig_text.string,
4913 compl_orig_text.length) == 0
4914 : STRNCMP(str, compl_orig_text.string,
4915 compl_orig_text.length) == 0))
glepnir05460682025-05-26 18:23:27 +02004916 {
glepnir86d46a72025-06-03 21:04:44 +02004917 if (ins_compl_add_infercase(str, str_len, p_ic, NULL,
4918 dir, FALSE, 0) == OK)
glepnir05460682025-05-26 18:23:27 +02004919 dir = FORWARD;
4920 }
glepnird5fdfa52025-06-02 19:45:41 +02004921 }
glepnir86d46a72025-06-03 21:04:44 +02004922 else
glepnird5fdfa52025-06-02 19:45:41 +02004923 {
glepnird5fdfa52025-06-02 19:45:41 +02004924 // Calculate the safe end of string to avoid null byte issues
4925 char_u *str_end = str + STRLEN(str);
4926 char_u *p = str;
4927
4928 // Safely iterate through the string
4929 while (p < str_end && *p != NUL)
4930 {
4931 char_u *old_p = p;
4932 p = find_word_start(p);
4933 if (p >= str_end || *p == NUL)
4934 break;
4935
4936 char_u *word_end = find_word_end(p);
4937
4938 if (word_end <= p)
4939 {
4940 if (has_mbyte)
4941 word_end = p + (*mb_ptr2len)(p);
4942 else
4943 word_end = p + 1;
4944 }
4945
4946 if (word_end > str_end)
4947 word_end = str_end;
4948
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 if (p <= old_p)
4964 {
4965 p = old_p + 1;
4966 if (has_mbyte && p < str_end)
4967 p = old_p + (*mb_ptr2len)(old_p);
4968 }
4969 }
glepnir05460682025-05-26 18:23:27 +02004970 }
4971 }
4972
4973 // Free the register copy
4974 put_register(regname, reg_ptr);
4975 }
4976}
4977
4978/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004979 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004980 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004981 */
4982 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004983get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004984{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004985 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004986
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004987 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004988 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004989 case -1:
4990 break;
4991#ifdef FEAT_FIND_ID
4992 case CTRL_X_PATH_PATTERNS:
4993 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004994 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004995 break;
4996#endif
4997
4998 case CTRL_X_DICTIONARY:
4999 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005000 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
5001 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005002 break;
5003
5004 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005005 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005006 break;
5007
5008 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005009 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005010 break;
5011
5012 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02005013 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005014 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005015 break;
5016
5017#ifdef FEAT_COMPL_FUNC
5018 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02005019 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
5020 expand_cpt_function(st->func_cb);
5021 else
5022 expand_by_function(type, compl_pattern.string, NULL);
5023 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005024 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02005025 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005026 break;
5027#endif
5028
5029 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005030 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005031 break;
5032
glepnir05460682025-05-26 18:23:27 +02005033 case CTRL_X_REGISTER:
5034 get_register_completion();
5035 break;
5036
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005037 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005038 found_new_match = get_next_default_completion(st, ini);
5039 if (found_new_match == FAIL && st->ins_buf == curbuf)
5040 st->found_all = TRUE;
5041 }
5042
5043 // check if compl_curr_match has changed, (e.g. other type of
5044 // expansion added something)
5045 if (type != 0 && compl_curr_match != compl_old_match)
5046 found_new_match = OK;
5047
5048 return found_new_match;
5049}
5050
5051/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005052 * Strips carets followed by numbers. This suffix typically represents the
5053 * max_matches setting.
5054 */
5055 static void
5056strip_caret_numbers_in_place(char_u *str)
5057{
5058 char_u *read = str, *write = str, *p;
5059
5060 if (str == NULL)
5061 return;
5062
5063 while (*read)
5064 {
5065 if (*read == '^')
5066 {
5067 p = read + 1;
5068 while (vim_isdigit(*p))
5069 p++;
5070 if ((*p == ',' || *p == '\0') && p != read + 1)
5071 {
5072 read = p;
5073 continue;
5074 }
5075 else
5076 *write++ = *read++;
5077 }
5078 else
5079 *write++ = *read++;
5080 }
5081 *write = '\0';
5082}
5083
5084/*
Girish Palya98c29db2025-06-01 19:40:00 +02005085 * Call functions specified in the 'cpt' option with findstart=1,
5086 * and retrieve the startcol.
5087 */
5088 static void
5089prepare_cpt_compl_funcs(void)
5090{
5091#ifdef FEAT_COMPL_FUNC
5092 char_u *cpt;
5093 char_u *p;
5094 callback_T *cb = NULL;
5095 int idx = 0;
5096 int startcol;
5097
5098 // Make a copy of 'cpt' in case the buffer gets wiped out
5099 cpt = vim_strsave(curbuf->b_p_cpt);
5100 strip_caret_numbers_in_place(cpt);
5101
5102 // Re-insert the text removed by ins_compl_delete().
5103 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5104
5105 for (p = cpt; *p;)
5106 {
5107 while (*p == ',' || *p == ' ') // Skip delimiters
5108 p++;
5109 cb = get_callback_if_cpt_func(p);
5110 if (cb)
5111 {
5112 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5113 == FAIL)
5114 {
5115 if (startcol == -3)
5116 cpt_sources_array[idx].cs_refresh_always = FALSE;
5117 else
5118 startcol = -2;
5119 }
5120 cpt_sources_array[idx].cs_startcol = startcol;
5121 }
5122 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5123 idx++;
5124 }
5125
5126 // Undo insertion
5127 ins_compl_delete();
5128
5129 vim_free(cpt);
5130#endif
5131}
5132
5133/*
Girish Palya7c621052025-05-26 19:41:59 +02005134 * Safely advance the cpt_sources_index by one.
5135 */
5136 static int
5137advance_cpt_sources_index_safe(void)
5138{
5139 if (cpt_sources_index < cpt_sources_count - 1)
5140 {
5141 cpt_sources_index++;
5142 return OK;
5143 }
5144#ifdef FEAT_EVAL
5145 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5146#endif
5147 return FAIL;
5148}
5149
5150/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005151 * Get the next expansion(s), using "compl_pattern".
5152 * The search starts at position "ini" in curbuf and in the direction
5153 * compl_direction.
5154 * When "compl_started" is FALSE start at that position, otherwise continue
5155 * where we stopped searching before.
5156 * This may return before finding all the matches.
5157 * Return the total number of matches or -1 if still unknown -- Acevedo
5158 */
5159 static int
5160ins_compl_get_exp(pos_T *ini)
5161{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005162 static ins_compl_next_state_T st;
5163 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005164 int i;
5165 int found_new_match;
5166 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005167 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005168
5169 if (!compl_started)
5170 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005171 buf_T *buf;
5172
5173 FOR_ALL_BUFFERS(buf)
5174 buf->b_scanned = 0;
5175 if (!st_cleared)
5176 {
5177 CLEAR_FIELD(st);
5178 st_cleared = TRUE;
5179 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005180 st.found_all = FALSE;
5181 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005182 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005183 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005184 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5185 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005186 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005187 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005188 st.last_match_pos = st.first_match_pos = *ini;
5189 }
5190 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5191 st.ins_buf = curbuf; // In case the buffer was wiped out.
5192
5193 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005194 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005195 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005196
Girish Palya98c29db2025-06-01 19:40:00 +02005197 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5198 !(compl_cont_status & CONT_LOCAL))
5199 {
5200 // ^N completion, not ^X^L or complete() or ^X^N
5201 if (!compl_started) // Before showing menu the first time
5202 {
5203 if (setup_cpt_sources() == FAIL)
5204 return FAIL;
5205 }
5206 prepare_cpt_compl_funcs();
5207 cpt_sources_index = 0;
5208 }
5209
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005210 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005211 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005212 {
5213 found_new_match = FAIL;
5214 st.set_match_pos = FALSE;
5215
5216 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5217 // or if found_all says this entry is done. For ^X^L only use the
5218 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005219 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005220 && (!compl_started || st.found_all))
5221 {
Girish Palya7c621052025-05-26 19:41:59 +02005222 int status = process_next_cpt_value(&st, &type, ini,
5223 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005224
5225 if (status == INS_COMPL_CPT_END)
5226 break;
5227 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005228 {
Girish Palya7c621052025-05-26 19:41:59 +02005229 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5230 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005231 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005232 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005233 }
5234
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005235 // If complete() was called then compl_pattern has been reset. The
5236 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005237 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005238 break;
5239
5240 // get the next set of completion matches
5241 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005242
Girish Palya7c621052025-05-26 19:41:59 +02005243 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5244 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005245
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005246 // break the loop for specialized modes (use 'complete' just for the
5247 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5248 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005249 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5250 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005251 {
5252 if (got_int)
5253 break;
5254 // Fill the popup menu as soon as possible.
5255 if (type != -1)
5256 ins_compl_check_keys(0, FALSE);
5257
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005258 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005259 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5260 break;
5261 compl_started = TRUE;
5262 }
5263 else
5264 {
5265 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005266 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005267 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005268
5269 compl_started = FALSE;
5270 }
5271 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005272 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005273 compl_started = TRUE;
5274
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005275 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005276 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005277 found_new_match = FAIL;
5278
5279 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005280 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005281 && !ctrl_x_mode_line_or_eval()))
5282 i = ins_compl_make_cyclic();
5283
glepnirf31cfa22025-03-06 21:59:13 +01005284 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5285 fuzzy_longest_match();
5286
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005287 if (compl_old_match != NULL)
5288 {
5289 // If several matches were added (FORWARD) or the search failed and has
5290 // just been made cyclic then we have to move compl_curr_match to the
5291 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005292 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005293 : compl_old_match->cp_prev;
5294 if (compl_curr_match == NULL)
5295 compl_curr_match = compl_old_match;
5296 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005297 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005298
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005299 return i;
5300}
5301
5302/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005303 * Update "compl_shown_match" to the actually shown match, it may differ when
5304 * "compl_leader" is used to omit some of the matches.
5305 */
5306 static void
5307ins_compl_update_shown_match(void)
5308{
5309 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005310 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005311 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005312 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005313 compl_shown_match = compl_shown_match->cp_next;
5314
5315 // If we didn't find it searching forward, and compl_shows_dir is
5316 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005317 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005318 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005319 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005320 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005321 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005322 {
5323 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005324 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005325 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005326 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005327 compl_shown_match = compl_shown_match->cp_prev;
5328 }
5329}
5330
5331/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005332 * Delete the old text being completed.
5333 */
5334 void
5335ins_compl_delete(void)
5336{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005337 // In insert mode: Delete the typed part.
5338 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005339 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005340 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005341 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005342 int has_preinsert = ins_compl_preinsert_effect();
5343 if (has_preinsert)
5344 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005345 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005346 curwin->w_cursor.col = compl_ins_end_col;
5347 }
5348
glepnir76bdb822025-02-08 19:04:51 +01005349 if (curwin->w_cursor.lnum > compl_lnum)
5350 {
5351 if (curwin->w_cursor.col < ml_get_curline_len())
5352 {
John Marriottf4b36412025-02-23 09:09:59 +01005353 char_u *line = ml_get_cursor();
5354 remaining.length = ml_get_cursor_len();
5355 remaining.string = vim_strnsave(line, remaining.length);
5356 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005357 return;
5358 }
5359 while (curwin->w_cursor.lnum > compl_lnum)
5360 {
5361 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5362 {
John Marriottf4b36412025-02-23 09:09:59 +01005363 if (remaining.string)
5364 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005365 return;
5366 }
zeertzjq060e6552025-02-21 20:06:26 +01005367 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005368 curwin->w_cursor.lnum--;
5369 }
5370 // move cursor to end of line
5371 curwin->w_cursor.col = ml_get_curline_len();
5372 }
5373
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005374 if ((int)curwin->w_cursor.col > col)
5375 {
5376 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005377 {
John Marriottf4b36412025-02-23 09:09:59 +01005378 if (remaining.string)
5379 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005380 return;
glepnire3647c82025-02-10 21:16:32 +01005381 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005382 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005383 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005384 }
5385
John Marriottf4b36412025-02-23 09:09:59 +01005386 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005387 {
5388 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005389 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005390 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005391 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005392 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005393 // TODO: is this sufficient for redrawing? Redrawing everything causes
5394 // flicker, thus we can't do that.
5395 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005396#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005397 // clear v:completed_item
5398 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005399#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005400}
5401
5402/*
glepnir76bdb822025-02-08 19:04:51 +01005403 * Insert a completion string that contains newlines.
5404 * The string is split and inserted line by line.
5405 */
5406 static void
5407ins_compl_expand_multiple(char_u *str)
5408{
5409 char_u *start = str;
5410 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005411 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005412
5413 while (*curr != NUL)
5414 {
5415 if (*curr == '\n')
5416 {
5417 // Insert the text chunk before newline
5418 if (curr > start)
5419 ins_char_bytes(start, (int)(curr - start));
5420
5421 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005422 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005423 start = curr + 1;
5424 }
5425 curr++;
5426 }
5427
5428 // Handle remaining text after last newline (if any)
5429 if (curr > start)
5430 ins_char_bytes(start, (int)(curr - start));
5431
5432 compl_ins_end_col = curwin->w_cursor.col;
5433}
5434
5435/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005436 * Insert the new text being completed.
5437 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005438 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5439 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005440 */
5441 void
glepniredd4ac32025-01-29 18:53:51 +01005442ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005443{
glepnir76bdb822025-02-08 19:04:51 +01005444 int compl_len = get_compl_len();
5445 int preinsert = ins_compl_has_preinsert();
5446 char_u *cp_str = compl_shown_match->cp_str.string;
5447 size_t cp_str_len = compl_shown_match->cp_str.length;
5448 size_t leader_len = ins_compl_leader_len();
5449 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005450
5451 // Make sure we don't go over the end of the string, this can happen with
5452 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005453 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005454 {
glepnir76bdb822025-02-08 19:04:51 +01005455 if (has_multiple)
5456 ins_compl_expand_multiple(cp_str + compl_len);
5457 else
5458 {
5459 ins_compl_insert_bytes(cp_str + compl_len, -1);
5460 if (preinsert && move_cursor)
5461 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5462 }
glepniredd4ac32025-01-29 18:53:51 +01005463 }
5464 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005465 compl_used_match = FALSE;
5466 else
5467 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005468#ifdef FEAT_EVAL
5469 {
5470 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5471
5472 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5473 }
5474#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005475 if (!in_compl_func)
5476 compl_curr_match = compl_shown_match;
5477}
5478
5479/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005480 * show the file name for the completion match (if any). Truncate the file
5481 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005482 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005483 static void
5484ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005485{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005486 char *lead = _("match in file");
5487 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5488 char_u *s;
5489 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005491 if (space <= 0)
5492 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005493
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005494 // We need the tail that fits. With double-byte encoding going
5495 // back from the end is very slow, thus go from the start and keep
5496 // the text that fits in "space" between "s" and "e".
5497 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005498 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005499 space -= ptr2cells(e);
5500 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005501 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005502 space += ptr2cells(s);
5503 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005504 }
5505 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005506 msg_hist_off = TRUE;
5507 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5508 s > compl_shown_match->cp_fname ? "<" : "", s);
5509 msg((char *)IObuff);
5510 msg_hist_off = FALSE;
5511 redraw_cmdline = FALSE; // don't overwrite!
5512}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005513
glepnirdca57fb2024-06-04 22:01:21 +02005514/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005515 * Find the appropriate completion item when 'complete' ('cpt') includes
5516 * a 'max_matches' postfix. In this case, we search for a match where
5517 * 'cp_in_match_array' is set, indicating that the match is also present
5518 * in 'compl_match_array'.
5519 */
5520 static compl_T *
5521find_comp_when_cpt_sources(void)
5522{
5523 int is_forward = compl_shows_dir_forward();
5524 compl_T *match = compl_shown_match;
5525
5526 do
5527 match = is_forward ? match->cp_next : match->cp_prev;
5528 while (match->cp_next && !match->cp_in_match_array
5529 && !match_at_original_text(match));
5530 return match;
5531}
5532
5533/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005534 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005535 * times. The number of matches found is returned in 'num_matches'.
5536 *
5537 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5538 * get more completions. If it is FALSE, then do nothing when there are no more
5539 * completions in the given direction.
5540 *
5541 * If "advance" is TRUE, then completion will move to the first match.
5542 * Otherwise, the original text will be shown.
5543 *
5544 * Returns OK on success and -1 if the number of matches are unknown.
5545 */
5546 static int
5547find_next_completion_match(
5548 int allow_get_expansion,
5549 int todo, // repeat completion this many times
5550 int advance,
5551 int *num_matches)
5552{
5553 int found_end = FALSE;
5554 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005555 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005556 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5557 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005558 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005559
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005560 while (--todo >= 0)
5561 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005562 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005563 {
Girish Palya8cd42a52025-06-05 21:04:29 +02005564 if (cpt_sources_active)
Girish Palya0ac1eb32025-04-16 20:18:33 +02005565 compl_shown_match = find_comp_when_cpt_sources();
5566 else
5567 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005568 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005569 && (is_first_match(compl_shown_match->cp_next)
5570 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005571 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005572 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005573 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005574 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005575 found_end = is_first_match(compl_shown_match);
Girish Palya8cd42a52025-06-05 21:04:29 +02005576 if (cpt_sources_active)
Girish Palya0ac1eb32025-04-16 20:18:33 +02005577 compl_shown_match = find_comp_when_cpt_sources();
5578 else
5579 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005580 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005581 }
5582 else
5583 {
5584 if (!allow_get_expansion)
5585 {
5586 if (advance)
5587 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005588 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005589 compl_pending -= todo + 1;
5590 else
5591 compl_pending += todo + 1;
5592 }
5593 return -1;
5594 }
5595
5596 if (!compl_no_select && advance)
5597 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005598 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005599 --compl_pending;
5600 else
5601 ++compl_pending;
5602 }
5603
5604 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005605 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005606
5607 // handle any pending completions
5608 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005609 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005610 {
5611 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5612 {
5613 compl_shown_match = compl_shown_match->cp_next;
5614 --compl_pending;
5615 }
5616 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5617 {
5618 compl_shown_match = compl_shown_match->cp_prev;
5619 ++compl_pending;
5620 }
5621 else
5622 break;
5623 }
5624 found_end = FALSE;
5625 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005626 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005627 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005628 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005629 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005630 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005631 ++todo;
5632 else
5633 // Remember a matching item.
5634 found_compl = compl_shown_match;
5635
5636 // Stop at the end of the list when we found a usable match.
5637 if (found_end)
5638 {
5639 if (found_compl != NULL)
5640 {
5641 compl_shown_match = found_compl;
5642 break;
5643 }
5644 todo = 1; // use first usable match after wrapping around
5645 }
5646 }
5647
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005648 return OK;
5649}
5650
5651/*
5652 * Fill in the next completion in the current direction.
5653 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5654 * get more completions. If it is FALSE, then we just do nothing when there
5655 * are no more completions in a given direction. The latter case is used when
5656 * we are still in the middle of finding completions, to allow browsing
5657 * through the ones found so far.
5658 * Return the total number of matches, or -1 if still unknown -- webb.
5659 *
5660 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5661 * compl_shown_match here.
5662 *
5663 * Note that this function may be called recursively once only. First with
5664 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5665 * calls this function with "allow_get_expansion" FALSE.
5666 */
5667 static int
5668ins_compl_next(
5669 int allow_get_expansion,
5670 int count, // repeat completion this many times; should
5671 // be at least 1
5672 int insert_match, // Insert the newly selected match
5673 int in_compl_func) // called from complete_check()
5674{
5675 int num_matches = -1;
5676 int todo = count;
5677 int advance;
5678 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005679 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005680 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005681 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5682 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005683 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005684
5685 // When user complete function return -1 for findstart which is next
5686 // time of 'always', compl_shown_match become NULL.
5687 if (compl_shown_match == NULL)
5688 return -1;
5689
John Marriott5e6ea922024-11-23 14:01:57 +01005690 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005691 && !match_at_original_text(compl_shown_match)
5692 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005693 // Update "compl_shown_match" to the actually shown match
5694 ins_compl_update_shown_match();
5695
5696 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005697 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005698 // Delete old text to be replaced
5699 ins_compl_delete();
5700
5701 // When finding the longest common text we stick at the original text,
5702 // don't let CTRL-N or CTRL-P move to the first match.
5703 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5704
5705 // When restarting the search don't insert the first match either.
5706 if (compl_restarting)
5707 {
5708 advance = FALSE;
5709 compl_restarting = FALSE;
5710 }
5711
5712 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5713 // around.
5714 if (find_next_completion_match(allow_get_expansion, todo, advance,
5715 &num_matches) == -1)
5716 return -1;
5717
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005718 if (curbuf != orig_curbuf)
5719 {
5720 // In case some completion function switched buffer, don't want to
5721 // insert the completion elsewhere.
5722 return -1;
5723 }
5724
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005725 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005726 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005727 {
glepnir6a38aff2024-12-16 21:56:16 +01005728 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005729 compl_used_match = FALSE;
5730 }
5731 else if (insert_match)
5732 {
5733 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005734 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005735 else
glepnir6a38aff2024-12-16 21:56:16 +01005736 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005737 }
5738 else
5739 compl_used_match = FALSE;
5740
5741 if (!allow_get_expansion)
5742 {
5743 // may undisplay the popup menu first
5744 ins_compl_upd_pum();
5745
5746 if (pum_enough_matches())
5747 // Will display the popup menu, don't redraw yet to avoid flicker.
5748 pum_call_update_screen();
5749 else
5750 // Not showing the popup menu yet, redraw to show the user what was
5751 // inserted.
5752 update_screen(0);
5753
5754 // display the updated popup menu
5755 ins_compl_show_pum();
5756#ifdef FEAT_GUI
5757 if (gui.in_use)
5758 {
5759 // Show the cursor after the match, not after the redrawn text.
5760 setcursor();
5761 out_flush_cursor(FALSE, FALSE);
5762 }
5763#endif
5764
5765 // Delete old text to be replaced, since we're still searching and
5766 // don't want to match ourselves!
5767 ins_compl_delete();
5768 }
5769
5770 // Enter will select a match when the match wasn't inserted and the popup
5771 // menu is visible.
5772 if (compl_no_insert && !started)
5773 compl_enter_selects = TRUE;
5774 else
5775 compl_enter_selects = !insert_match && compl_match_array != NULL;
5776
5777 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005778 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005779 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005780
5781 return num_matches;
5782}
5783
5784/*
5785 * Call this while finding completions, to check whether the user has hit a key
5786 * that should change the currently displayed completion, or exit completion
5787 * mode. Also, when compl_pending is not zero, show a completion as soon as
5788 * possible. -- webb
5789 * "frequency" specifies out of how many calls we actually check.
5790 * "in_compl_func" is TRUE when called from complete_check(), don't set
5791 * compl_curr_match.
5792 */
5793 void
5794ins_compl_check_keys(int frequency, int in_compl_func)
5795{
5796 static int count = 0;
5797 int c;
5798
5799 // Don't check when reading keys from a script, :normal or feedkeys().
5800 // That would break the test scripts. But do check for keys when called
5801 // from complete_check().
5802 if (!in_compl_func && (using_script() || ex_normal_busy))
5803 return;
5804
5805 // Only do this at regular intervals
5806 if (++count < frequency)
5807 return;
5808 count = 0;
5809
5810 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5811 // can't do its work correctly.
5812 c = vpeekc_any();
5813 if (c != NUL)
5814 {
5815 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5816 {
5817 c = safe_vgetc(); // Eat the character
5818 compl_shows_dir = ins_compl_key2dir(c);
5819 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5820 c != K_UP && c != K_DOWN, in_compl_func);
5821 }
5822 else
5823 {
5824 // Need to get the character to have KeyTyped set. We'll put it
5825 // back with vungetc() below. But skip K_IGNORE.
5826 c = safe_vgetc();
5827 if (c != K_IGNORE)
5828 {
5829 // Don't interrupt completion when the character wasn't typed,
5830 // e.g., when doing @q to replay keys.
5831 if (c != Ctrl_R && KeyTyped)
5832 compl_interrupted = TRUE;
5833
5834 vungetc(c);
5835 }
5836 }
5837 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005838 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005839 {
5840 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5841
5842 compl_pending = 0;
5843 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5844 }
5845}
5846
5847/*
5848 * Decide the direction of Insert mode complete from the key typed.
5849 * Returns BACKWARD or FORWARD.
5850 */
5851 static int
5852ins_compl_key2dir(int c)
5853{
5854 if (c == Ctrl_P || c == Ctrl_L
5855 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5856 return BACKWARD;
5857 return FORWARD;
5858}
5859
5860/*
5861 * Return TRUE for keys that are used for completion only when the popup menu
5862 * is visible.
5863 */
5864 static int
5865ins_compl_pum_key(int c)
5866{
5867 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5868 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5869 || c == K_UP || c == K_DOWN);
5870}
5871
5872/*
5873 * Decide the number of completions to move forward.
5874 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5875 */
5876 static int
5877ins_compl_key2count(int c)
5878{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005879 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5880 {
glepnir19e1dd62025-05-08 22:50:38 +02005881 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005882 if (h > 3)
5883 h -= 2; // keep some context
5884 return h;
5885 }
5886 return 1;
5887}
5888
5889/*
5890 * Return TRUE if completion with "c" should insert the match, FALSE if only
5891 * to change the currently selected completion.
5892 */
5893 static int
5894ins_compl_use_match(int c)
5895{
5896 switch (c)
5897 {
5898 case K_UP:
5899 case K_DOWN:
5900 case K_PAGEDOWN:
5901 case K_KPAGEDOWN:
5902 case K_S_DOWN:
5903 case K_PAGEUP:
5904 case K_KPAGEUP:
5905 case K_S_UP:
5906 return FALSE;
5907 }
5908 return TRUE;
5909}
5910
5911/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005912 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5913 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005914 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005915 * Uses the global variables: compl_cont_status and ctrl_x_mode
5916 */
5917 static int
5918get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5919{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005920 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005921 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005922 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005923 {
5924 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5925 ;
5926 compl_col += ++startcol;
5927 compl_length = curs_col - startcol;
5928 }
5929 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005930 {
John Marriott5e6ea922024-11-23 14:01:57 +01005931 compl_pattern.string = str_foldcase(line + compl_col,
5932 compl_length, NULL, 0);
5933 if (compl_pattern.string == NULL)
5934 {
5935 compl_pattern.length = 0;
5936 return FAIL;
5937 }
5938 compl_pattern.length = STRLEN(compl_pattern.string);
5939 }
5940 else
5941 {
5942 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5943 if (compl_pattern.string == NULL)
5944 {
5945 compl_pattern.length = 0;
5946 return FAIL;
5947 }
5948 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005949 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005950 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005951 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005952 {
5953 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005954 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005955 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005956
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005957 if (!vim_iswordp(line + compl_col)
5958 || (compl_col > 0
5959 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005960 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005961 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005962 prefixlen = 0;
5963 }
John Marriott5e6ea922024-11-23 14:01:57 +01005964
5965 // we need up to 2 extra chars for the prefix
5966 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5967 compl_pattern.string = alloc(n);
5968 if (compl_pattern.string == NULL)
5969 {
5970 compl_pattern.length = 0;
5971 return FAIL;
5972 }
5973 STRCPY((char *)compl_pattern.string, prefix);
5974 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005975 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005976 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005977 }
5978 else if (--startcol < 0
5979 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5980 {
John Marriott5e6ea922024-11-23 14:01:57 +01005981 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5982
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005983 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005984 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5985 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005986 {
John Marriott5e6ea922024-11-23 14:01:57 +01005987 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005988 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005989 }
John Marriott5e6ea922024-11-23 14:01:57 +01005990 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005991 compl_col += curs_col;
5992 compl_length = 0;
5993 }
5994 else
5995 {
5996 // Search the point of change class of multibyte character
5997 // or not a word single byte character backward.
5998 if (has_mbyte)
5999 {
6000 int base_class;
6001 int head_off;
6002
6003 startcol -= (*mb_head_off)(line, line + startcol);
6004 base_class = mb_get_class(line + startcol);
6005 while (--startcol >= 0)
6006 {
6007 head_off = (*mb_head_off)(line, line + startcol);
6008 if (base_class != mb_get_class(line + startcol
6009 - head_off))
6010 break;
6011 startcol -= head_off;
6012 }
6013 }
6014 else
glepnir19e1dd62025-05-08 22:50:38 +02006015 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006016 while (--startcol >= 0 && vim_iswordc(line[startcol]))
6017 ;
glepnir19e1dd62025-05-08 22:50:38 +02006018 }
6019
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006020 compl_col += ++startcol;
6021 compl_length = (int)curs_col - startcol;
6022 if (compl_length == 1)
6023 {
6024 // Only match word with at least two chars -- webb
6025 // there's no need to call quote_meta,
6026 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01006027 compl_pattern.string = alloc(7);
6028 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006029 {
John Marriott5e6ea922024-11-23 14:01:57 +01006030 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006031 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006032 }
John Marriott5e6ea922024-11-23 14:01:57 +01006033 STRCPY((char *)compl_pattern.string, "\\<");
6034 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
6035 STRCAT((char *)compl_pattern.string, "\\k");
6036 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006037 }
6038 else
6039 {
John Marriott5e6ea922024-11-23 14:01:57 +01006040 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6041
6042 compl_pattern.string = alloc(n);
6043 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006044 {
John Marriott5e6ea922024-11-23 14:01:57 +01006045 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006046 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006047 }
John Marriott5e6ea922024-11-23 14:01:57 +01006048 STRCPY((char *)compl_pattern.string, "\\<");
6049 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006050 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006051 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006052 }
6053 }
6054
6055 return OK;
6056}
6057
6058/*
6059 * Get the pattern, column and length for whole line completion or for the
6060 * complete() function.
6061 * Sets the global variables: compl_col, compl_length and compl_pattern.
6062 */
6063 static int
6064get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6065{
6066 compl_col = (colnr_T)getwhitecols(line);
6067 compl_length = (int)curs_col - (int)compl_col;
6068 if (compl_length < 0) // cursor in indent: empty pattern
6069 compl_length = 0;
6070 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006071 {
John Marriott5e6ea922024-11-23 14:01:57 +01006072 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6073 NULL, 0);
6074 if (compl_pattern.string == NULL)
6075 {
6076 compl_pattern.length = 0;
6077 return FAIL;
6078 }
6079 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006080 }
John Marriott5e6ea922024-11-23 14:01:57 +01006081 else
6082 {
6083 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6084 if (compl_pattern.string == NULL)
6085 {
6086 compl_pattern.length = 0;
6087 return FAIL;
6088 }
6089 compl_pattern.length = (size_t)compl_length;
6090 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006091
6092 return OK;
6093}
6094
6095/*
6096 * Get the pattern, column and length for filename completion.
6097 * Sets the global variables: compl_col, compl_length and compl_pattern.
6098 */
6099 static int
6100get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6101{
6102 // Go back to just before the first filename character.
6103 if (startcol > 0)
6104 {
6105 char_u *p = line + startcol;
6106
6107 MB_PTR_BACK(line, p);
6108 while (p > line && vim_isfilec(PTR2CHAR(p)))
6109 MB_PTR_BACK(line, p);
6110 if (p == line && vim_isfilec(PTR2CHAR(p)))
6111 startcol = 0;
6112 else
6113 startcol = (int)(p - line) + 1;
6114 }
6115
6116 compl_col += startcol;
6117 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006118 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6119 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006120 {
John Marriott5e6ea922024-11-23 14:01:57 +01006121 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006122 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006123 }
6124
John Marriott5e6ea922024-11-23 14:01:57 +01006125 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006126
6127 return OK;
6128}
6129
6130/*
6131 * Get the pattern, column and length for command-line completion.
6132 * Sets the global variables: compl_col, compl_length and compl_pattern.
6133 */
6134 static int
6135get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6136{
John Marriott5e6ea922024-11-23 14:01:57 +01006137 compl_pattern.string = vim_strnsave(line, curs_col);
6138 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006139 {
John Marriott5e6ea922024-11-23 14:01:57 +01006140 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006141 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006142 }
John Marriott5e6ea922024-11-23 14:01:57 +01006143 compl_pattern.length = curs_col;
6144 set_cmd_context(&compl_xp, compl_pattern.string,
6145 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006146 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6147 || compl_xp.xp_context == EXPAND_NOTHING)
6148 // No completion possible, use an empty pattern to get a
6149 // "pattern not found" message.
6150 compl_col = curs_col;
6151 else
John Marriott5e6ea922024-11-23 14:01:57 +01006152 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006153 compl_length = curs_col - compl_col;
6154
6155 return OK;
6156}
6157
Girish Palya98c29db2025-06-01 19:40:00 +02006158#ifdef FEAT_COMPL_FUNC
6159/*
6160 * Set global variables related to completion:
6161 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6162 */
6163 static int
6164set_compl_globals(
6165 int startcol UNUSED,
6166 colnr_T curs_col UNUSED,
6167 int is_cpt_compl UNUSED)
6168{
6169 char_u *line = NULL;
6170 string_T *pattern = NULL;
6171 int len;
6172
6173 if (startcol < 0 || startcol > curs_col)
6174 startcol = curs_col;
6175 len = curs_col - startcol;
6176
6177 // Re-obtain line in case it has changed
6178 line = ml_get(curwin->w_cursor.lnum);
6179
6180 pattern = is_cpt_compl ? &cpt_compl_pattern : &compl_pattern;
6181 pattern->string = vim_strnsave(line + startcol, (size_t)len);
6182 if (pattern->string == NULL)
6183 {
6184 pattern->length = 0;
6185 return FAIL;
6186 }
6187 pattern->length = (size_t)len;
6188 if (!is_cpt_compl)
6189 {
6190 compl_col = startcol;
6191 compl_length = len;
6192 }
6193 return OK;
6194}
6195#endif
6196
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006197/*
6198 * Get the pattern, column and length for user defined completion ('omnifunc',
6199 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006200 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006201 * Callback function "cb" is set if triggered by a function in the 'cpt'
6202 * option; otherwise, it is NULL.
6203 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006204 */
6205 static int
glepnir19e1dd62025-05-08 22:50:38 +02006206get_userdefined_compl_info(
6207 colnr_T curs_col UNUSED,
6208 callback_T *cb UNUSED,
6209 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006210{
6211 int ret = FAIL;
6212
6213#ifdef FEAT_COMPL_FUNC
6214 // Call user defined function 'completefunc' with "a:findstart"
6215 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006216 typval_T args[3];
6217 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006218 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006219 pos_T pos;
6220 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006221 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006222
Girish Palyacbe53192025-04-14 22:13:15 +02006223 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006224 {
Girish Palyacbe53192025-04-14 22:13:15 +02006225 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6226 // length as a string
6227 funcname = get_complete_funcname(ctrl_x_mode);
6228 if (*funcname == NUL)
6229 {
6230 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6231 ? "completefunc" : "omnifunc");
6232 return FAIL;
6233 }
6234 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006235 }
6236
6237 args[0].v_type = VAR_NUMBER;
6238 args[0].vval.v_number = 1;
6239 args[1].v_type = VAR_STRING;
6240 args[1].vval.v_string = (char_u *)"";
6241 args[2].v_type = VAR_UNKNOWN;
6242 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006243 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006244 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006245 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006246
6247 State = save_State;
6248 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006249 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006250 validate_cursor();
6251 if (!EQUAL_POS(curwin->w_cursor, pos))
6252 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006253 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006254 return FAIL;
6255 }
6256
Girish Palyacbe53192025-04-14 22:13:15 +02006257 if (startcol != NULL)
6258 *startcol = col;
6259
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006260 // Return value -2 means the user complete function wants to cancel the
6261 // complete without an error, do the same if the function did not execute
6262 // successfully.
6263 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006264 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006265
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006266 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006267 if (col == -3)
6268 {
Girish Palyacbe53192025-04-14 22:13:15 +02006269 if (is_cpt_function)
6270 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006271 ctrl_x_mode = CTRL_X_NORMAL;
6272 edit_submode = NULL;
6273 if (!shortmess(SHM_COMPLETIONMENU))
6274 msg_clr_cmdline();
6275 return FAIL;
6276 }
6277
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006278 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006279 // completion.
6280 compl_opt_refresh_always = FALSE;
6281 compl_opt_suppress_empty = FALSE;
6282
Girish Palya98c29db2025-06-01 19:40:00 +02006283 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006284#endif
6285
6286 return ret;
6287}
6288
6289/*
6290 * Get the pattern, column and length for spell completion.
6291 * Sets the global variables: compl_col, compl_length and compl_pattern.
6292 * Uses the global variable: spell_bad_len
6293 */
6294 static int
6295get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6296{
6297 int ret = FAIL;
6298#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006299 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006300
6301 if (spell_bad_len > 0)
6302 compl_col = curs_col - spell_bad_len;
6303 else
6304 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006305
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006306 if (compl_col >= (colnr_T)startcol)
6307 {
6308 compl_length = 0;
6309 compl_col = curs_col;
6310 }
6311 else
6312 {
6313 spell_expand_check_cap(compl_col);
6314 compl_length = (int)curs_col - compl_col;
6315 }
6316 // Need to obtain "line" again, it may have become invalid.
6317 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006318 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6319 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006320 {
John Marriott5e6ea922024-11-23 14:01:57 +01006321 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006322 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006323 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006324
John Marriott5e6ea922024-11-23 14:01:57 +01006325 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006326 ret = OK;
6327#endif
6328
6329 return ret;
6330}
6331
6332/*
6333 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006334 * "startcol" - start column number of the completion pattern/text
6335 * "cur_col" - current cursor column
6336 * On return, "line_invalid" is set to TRUE, if the current line may have
6337 * become invalid and needs to be fetched again.
6338 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006339 */
6340 static int
6341compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6342{
glepnird5fdfa52025-06-02 19:45:41 +02006343 if (ctrl_x_mode_normal() || ctrl_x_mode_register()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006344 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6345 && !thesaurus_func_complete(ctrl_x_mode)))
6346 {
6347 return get_normal_compl_info(line, startcol, curs_col);
6348 }
6349 else if (ctrl_x_mode_line_or_eval())
6350 {
6351 return get_wholeline_compl_info(line, curs_col);
6352 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006353 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006354 {
6355 return get_filename_compl_info(line, startcol, curs_col);
6356 }
6357 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6358 {
6359 return get_cmdline_compl_info(line, curs_col);
6360 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006361 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006362 || thesaurus_func_complete(ctrl_x_mode))
6363 {
Girish Palyacbe53192025-04-14 22:13:15 +02006364 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006365 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006366 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006367 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006368 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006369 {
6370 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6371 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006372 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006373 }
6374 else
6375 {
6376 internal_error("ins_complete()");
6377 return FAIL;
6378 }
6379
6380 return OK;
6381}
6382
6383/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006384 * Continue an interrupted completion mode search in "line".
6385 *
6386 * If this same ctrl_x_mode has been interrupted use the text from
6387 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6388 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6389 * the same line as the cursor then fix it (the line has been split because it
6390 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6391 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006392 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006393 static void
6394ins_compl_continue_search(char_u *line)
6395{
6396 // it is a continued search
6397 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006398 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6399 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006400 {
6401 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6402 {
6403 // line (probably) wrapped, set compl_startpos to the
6404 // first non_blank in the line, if it is not a wordchar
6405 // include it to get a better pattern, but then we don't
6406 // want the "\\<" prefix, check it below
6407 compl_col = (colnr_T)getwhitecols(line);
6408 compl_startpos.col = compl_col;
6409 compl_startpos.lnum = curwin->w_cursor.lnum;
6410 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6411 }
6412 else
6413 {
6414 // S_IPOS was set when we inserted a word that was at the
6415 // beginning of the line, which means that we'll go to SOL
6416 // mode but first we need to redefine compl_startpos
6417 if (compl_cont_status & CONT_S_IPOS)
6418 {
6419 compl_cont_status |= CONT_SOL;
6420 compl_startpos.col = (colnr_T)(skipwhite(
6421 line + compl_length
6422 + compl_startpos.col) - line);
6423 }
6424 compl_col = compl_startpos.col;
6425 }
6426 compl_length = curwin->w_cursor.col - (int)compl_col;
6427 // IObuff is used to add a "word from the next line" would we
6428 // have enough space? just being paranoid
6429#define MIN_SPACE 75
6430 if (compl_length > (IOSIZE - MIN_SPACE))
6431 {
6432 compl_cont_status &= ~CONT_SOL;
6433 compl_length = (IOSIZE - MIN_SPACE);
6434 compl_col = curwin->w_cursor.col - compl_length;
6435 }
6436 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6437 if (compl_length < 1)
6438 compl_cont_status &= CONT_LOCAL;
6439 }
glepnird5fdfa52025-06-02 19:45:41 +02006440 else if (ctrl_x_mode_line_or_eval() || ctrl_x_mode_register())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006441 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6442 else
6443 compl_cont_status = 0;
6444}
6445
6446/*
6447 * start insert mode completion
6448 */
6449 static int
6450ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006451{
glepnir19e1dd62025-05-08 22:50:38 +02006452 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006453 int startcol = 0; // column where searched text starts
6454 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006455 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006456 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006457 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006458
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006459 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006460 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006461 did_si = FALSE;
6462 can_si = FALSE;
6463 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006464 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006465 return FAIL;
6466
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006467 line = ml_get(curwin->w_cursor.lnum);
6468 curs_col = curwin->w_cursor.col;
6469 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006470 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006471
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006472 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6473 && compl_cont_mode == ctrl_x_mode)
6474 // this same ctrl-x_mode was interrupted previously. Continue the
6475 // completion.
6476 ins_compl_continue_search(line);
6477 else
6478 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006479
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006480 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006481 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006482 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006483 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006484 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6485 compl_cont_status = 0;
6486 compl_cont_status |= CONT_N_ADDS;
6487 compl_startpos = curwin->w_cursor;
6488 startcol = (int)curs_col;
6489 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006490 }
6491
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006492 // Work out completion pattern and original text -- webb
6493 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6494 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006495 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6496 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006497 // restore did_ai, so that adding comment leader works
6498 did_ai = save_did_ai;
6499 return FAIL;
6500 }
6501 // If "line" was changed while getting completion info get it again.
6502 if (line_invalid)
6503 line = ml_get(curwin->w_cursor.lnum);
6504
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006505 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006506 {
6507 edit_submode_pre = (char_u *)_(" Adding");
6508 if (ctrl_x_mode_line_or_eval())
6509 {
6510 // Insert a new line, keep indentation but ignore 'comments'.
6511 char_u *old = curbuf->b_p_com;
6512
6513 curbuf->b_p_com = (char_u *)"";
6514 compl_startpos.lnum = curwin->w_cursor.lnum;
6515 compl_startpos.col = compl_col;
6516 ins_eol('\r');
6517 curbuf->b_p_com = old;
6518 compl_length = 0;
6519 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006520 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006521 }
glepnircfe502c2025-04-17 20:17:53 +02006522 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006523 {
6524 compl_startpos = curwin->w_cursor;
6525 compl_cont_status &= CONT_S_IPOS;
6526 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006527 }
6528 else
6529 {
6530 edit_submode_pre = NULL;
6531 compl_startpos.col = compl_col;
6532 }
6533
6534 if (compl_cont_status & CONT_LOCAL)
6535 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6536 else
6537 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6538
6539 // If any of the original typed text has been changed we need to fix
6540 // the redo buffer.
6541 ins_compl_fixRedoBufForLeader(NULL);
6542
6543 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006544 VIM_CLEAR_STRING(compl_orig_text);
6545 compl_orig_text.length = (size_t)compl_length;
6546 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006547 if (p_ic)
6548 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006549 if (compl_orig_text.string == NULL
6550 || ins_compl_add(compl_orig_text.string,
6551 (int)compl_orig_text.length,
6552 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006553 {
John Marriott5e6ea922024-11-23 14:01:57 +01006554 VIM_CLEAR_STRING(compl_pattern);
6555 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006556 return FAIL;
6557 }
6558
6559 // showmode might reset the internal line pointers, so it must
6560 // be called before line = ml_get(), or when this address is no
6561 // longer needed. -- Acevedo.
6562 edit_submode_extra = (char_u *)_("-- Searching...");
6563 edit_submode_highl = HLF_COUNT;
6564 showmode();
6565 edit_submode_extra = NULL;
6566 out_flush();
6567
6568 return OK;
6569}
6570
6571/*
6572 * display the completion status message
6573 */
6574 static void
6575ins_compl_show_statusmsg(void)
6576{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006577 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006578 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006579 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006580 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006581 ? (char_u *)_("Hit end of paragraph")
6582 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006583 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006584 }
6585
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006586 if (edit_submode_extra == NULL)
6587 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006588 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006589 {
6590 edit_submode_extra = (char_u *)_("Back at original");
6591 edit_submode_highl = HLF_W;
6592 }
6593 else if (compl_cont_status & CONT_S_IPOS)
6594 {
6595 edit_submode_extra = (char_u *)_("Word from other line");
6596 edit_submode_highl = HLF_COUNT;
6597 }
6598 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6599 {
6600 edit_submode_extra = (char_u *)_("The only match");
6601 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006602 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006603 }
6604 else
6605 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006606#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006607 // Update completion sequence number when needed.
6608 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006609 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006610#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006611 // The match should always have a sequence number now, this is
6612 // just a safety check.
6613 if (compl_curr_match->cp_number != -1)
6614 {
6615 // Space for 10 text chars. + 2x10-digit no.s = 31.
6616 // Translations may need more than twice that.
6617 static char_u match_ref[81];
6618
6619 if (compl_matches > 0)
6620 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006621 _("match %d of %d"),
6622 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006623 else
6624 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006625 _("match %d"),
6626 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006627 edit_submode_extra = match_ref;
6628 edit_submode_highl = HLF_R;
6629 if (dollar_vcol >= 0)
6630 curs_columns(FALSE);
6631 }
6632 }
6633 }
6634
6635 // Show a message about what (completion) mode we're in.
6636 if (!compl_opt_suppress_empty)
6637 {
6638 showmode();
6639 if (!shortmess(SHM_COMPLETIONMENU))
6640 {
6641 if (edit_submode_extra != NULL)
6642 {
6643 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006644 {
6645 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006646 msg_attr((char *)edit_submode_extra,
6647 edit_submode_highl < HLF_COUNT
6648 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006649 msg_hist_off = FALSE;
6650 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006651 }
6652 else
6653 msg_clr_cmdline(); // necessary for "noshowmode"
6654 }
6655 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006656}
6657
6658/*
6659 * Do Insert mode completion.
6660 * Called when character "c" was typed, which has a meaning for completion.
6661 * Returns OK if completion was done, FAIL if something failed (out of mem).
6662 */
6663 int
6664ins_complete(int c, int enable_pum)
6665{
6666 int n;
6667 int save_w_wrow;
6668 int save_w_leftcol;
6669 int insert_match;
6670
6671 compl_direction = ins_compl_key2dir(c);
6672 insert_match = ins_compl_use_match(c);
6673
6674 if (!compl_started)
6675 {
6676 if (ins_compl_start() == FAIL)
6677 return FAIL;
6678 }
6679 else if (insert_match && stop_arrow() == FAIL)
6680 return FAIL;
6681
glepnircf7f0122025-04-15 19:02:00 +02006682 compl_curr_win = curwin;
6683 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006684 compl_shown_match = compl_curr_match;
6685 compl_shows_dir = compl_direction;
6686
6687 // Find next match (and following matches).
6688 save_w_wrow = curwin->w_wrow;
6689 save_w_leftcol = curwin->w_leftcol;
6690 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6691
6692 // may undisplay the popup menu
6693 ins_compl_upd_pum();
6694
6695 if (n > 1) // all matches have been found
6696 compl_matches = n;
6697 compl_curr_match = compl_shown_match;
6698 compl_direction = compl_shows_dir;
6699
6700 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6701 // mode.
6702 if (got_int && !global_busy)
6703 {
6704 (void)vgetc();
6705 got_int = FALSE;
6706 }
6707
6708 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006709 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006710 {
6711 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6712 // because we couldn't expand anything at first place, but if we used
6713 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6714 // (such as M in M'exico) if not tried already. -- Acevedo
6715 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006716 || compl_status_adding()
6717 || (ctrl_x_mode_not_default()
6718 && !ctrl_x_mode_path_patterns()
6719 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006720 compl_cont_status &= ~CONT_N_ADDS;
6721 }
6722
6723 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6724 compl_cont_status |= CONT_S_IPOS;
6725 else
6726 compl_cont_status &= ~CONT_S_IPOS;
6727
6728 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006729
6730 // Show the popup menu, unless we got interrupted.
6731 if (enable_pum && !compl_interrupted)
6732 show_pum(save_w_wrow, save_w_leftcol);
6733
6734 compl_was_interrupted = compl_interrupted;
6735 compl_interrupted = FALSE;
6736
6737 return OK;
6738}
6739
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006740/*
6741 * Remove (if needed) and show the popup menu
6742 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006743 static void
6744show_pum(int prev_w_wrow, int prev_w_leftcol)
6745{
6746 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006747 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006748 RedrawingDisabled = 0;
6749
6750 // If the cursor moved or the display scrolled we need to remove the pum
6751 // first.
6752 setcursor();
6753 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6754 ins_compl_del_pum();
6755
6756 ins_compl_show_pum();
6757 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006758
6759 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006760}
6761
6762/*
6763 * Looks in the first "len" chars. of "src" for search-metachars.
6764 * If dest is not NULL the chars. are copied there quoting (with
6765 * a backslash) the metachars, and dest would be NUL terminated.
6766 * Returns the length (needed) of dest
6767 */
6768 static unsigned
6769quote_meta(char_u *dest, char_u *src, int len)
6770{
6771 unsigned m = (unsigned)len + 1; // one extra for the NUL
6772
6773 for ( ; --len >= 0; src++)
6774 {
6775 switch (*src)
6776 {
6777 case '.':
6778 case '*':
6779 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006780 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006781 break;
6782 // FALLTHROUGH
6783 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006784 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006785 break;
6786 // FALLTHROUGH
6787 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006788 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006789 break;
6790 // FALLTHROUGH
6791 case '^': // currently it's not needed.
6792 case '$':
6793 m++;
6794 if (dest != NULL)
6795 *dest++ = '\\';
6796 break;
6797 }
6798 if (dest != NULL)
6799 *dest++ = *src;
6800 // Copy remaining bytes of a multibyte character.
6801 if (has_mbyte)
6802 {
glepnir19e1dd62025-05-08 22:50:38 +02006803 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006804 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006805 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006806 {
6807 --len;
6808 ++src;
6809 if (dest != NULL)
6810 *dest++ = *src;
6811 }
6812 }
6813 }
6814 if (dest != NULL)
6815 *dest = NUL;
6816
6817 return m;
6818}
6819
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006820#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006821 void
6822free_insexpand_stuff(void)
6823{
John Marriott5e6ea922024-11-23 14:01:57 +01006824 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006825# ifdef FEAT_EVAL
6826 free_callback(&cfu_cb);
6827 free_callback(&ofu_cb);
6828 free_callback(&tsrfu_cb);
6829# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006830}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006831#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006832
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006833#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006834/*
6835 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6836 * spelled word, if there is one.
6837 */
6838 static void
6839spell_back_to_badword(void)
6840{
6841 pos_T tpos = curwin->w_cursor;
6842
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006843 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006844 if (curwin->w_cursor.col != tpos.col)
6845 start_arrow(&tpos);
6846}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006847#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006848
6849/*
6850 * Reset the info associated with completion sources.
6851 */
6852 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006853cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006854{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006855 VIM_CLEAR(cpt_sources_array);
6856 cpt_sources_index = -1;
6857 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006858}
6859
6860/*
Girish Palya98c29db2025-06-01 19:40:00 +02006861 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006862 */
6863 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006864setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006865{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006866 char_u buf[LSIZE];
6867 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006868 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006869 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006870
Girish Palya0ac1eb32025-04-16 20:18:33 +02006871 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006872 {
6873 while (*p == ',' || *p == ' ') // Skip delimiters
6874 p++;
6875 if (*p) // If not end of string, count this segment
6876 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006877 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006878 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006879 }
6880 }
Girish Palya98c29db2025-06-01 19:40:00 +02006881 if (count == 0)
6882 return OK;
6883
Girish Palya0ac1eb32025-04-16 20:18:33 +02006884 cpt_sources_clear();
6885 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006886 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6887 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006888 {
Girish Palya98c29db2025-06-01 19:40:00 +02006889 cpt_sources_count = 0;
6890 return FAIL;
6891 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006892
Girish Palya98c29db2025-06-01 19:40:00 +02006893 for (p = curbuf->b_p_cpt; *p;)
6894 {
6895 while (*p == ',' || *p == ' ') // Skip delimiters
6896 p++;
6897 if (*p) // If not end of string, count this segment
6898 {
6899 char_u *t;
6900
6901 vim_memset(buf, 0, LSIZE);
6902 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6903 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6904 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
6905 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006906 }
Girish Palyacbe53192025-04-14 22:13:15 +02006907 }
6908 return OK;
6909}
6910
6911/*
6912 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6913 */
6914 static int
6915is_cpt_func_refresh_always(void)
6916{
6917#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006918 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02006919 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006920 return TRUE;
6921#endif
6922 return FALSE;
6923}
6924
6925/*
6926 * Make the completion list non-cyclic.
6927 */
Girish Palyacbe53192025-04-14 22:13:15 +02006928 static void
6929ins_compl_make_linear(void)
6930{
6931 compl_T *m;
6932
6933 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6934 return;
6935 m = compl_first_match->cp_prev;
6936 m->cp_next = NULL;
6937 compl_first_match->cp_prev = NULL;
6938}
Girish Palyacbe53192025-04-14 22:13:15 +02006939
6940/*
6941 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006942 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006943 */
6944#ifdef FEAT_COMPL_FUNC
6945 static compl_T *
6946remove_old_matches(void)
6947{
6948 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6949 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006950 int compl_shown_removed = FALSE;
6951 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6952
6953 compl_direction = forward ? FORWARD : BACKWARD;
6954 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02006955
6956 // Identify the sublist of old matches that needs removal
6957 for (current = compl_first_match; current != NULL; current = current->cp_next)
6958 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006959 if (current->cp_cpt_source_idx < cpt_sources_index &&
6960 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02006961 insert_at = current;
6962
Girish Palya0ac1eb32025-04-16 20:18:33 +02006963 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02006964 {
6965 if (!sublist_start)
6966 sublist_start = current;
6967 sublist_end = current;
6968 if (!compl_shown_removed && compl_shown_match == current)
6969 compl_shown_removed = TRUE;
6970 }
6971
Girish Palya0ac1eb32025-04-16 20:18:33 +02006972 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
6973 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02006974 break;
6975 }
6976
6977 // Re-assign compl_shown_match if necessary
6978 if (compl_shown_removed)
6979 {
6980 if (forward)
6981 compl_shown_match = compl_first_match;
6982 else
6983 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02006984 for (current = compl_first_match; current->cp_next != NULL;
6985 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02006986 ;
6987 compl_shown_match = current;
6988 }
6989 }
6990
6991 if (!sublist_start) // No nodes to remove
6992 return insert_at;
6993
6994 // Update links to remove sublist
6995 if (sublist_start->cp_prev)
6996 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6997 else
6998 compl_first_match = sublist_end->cp_next;
6999
7000 if (sublist_end->cp_next)
7001 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
7002
7003 // Free all nodes in the sublist
7004 sublist_end->cp_next = NULL;
7005 for (current = sublist_start; current != NULL; current = next)
7006 {
7007 next = current->cp_next;
7008 ins_compl_item_free(current);
7009 }
7010
7011 return insert_at;
7012}
7013#endif
7014
7015/*
7016 * Retrieve completion matches using the callback function "cb" and store the
7017 * 'refresh:always' flag.
7018 */
7019#ifdef FEAT_COMPL_FUNC
7020 static void
7021get_cpt_func_completion_matches(callback_T *cb UNUSED)
7022{
Girish Palya98c29db2025-06-01 19:40:00 +02007023 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02007024
7025 VIM_CLEAR_STRING(cpt_compl_pattern);
Girish Palya98c29db2025-06-01 19:40:00 +02007026
7027 if (startcol == -2 || startcol == -3)
7028 return;
7029
7030 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02007031 {
7032 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02007033 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02007034 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02007035 compl_opt_refresh_always = FALSE;
7036 }
7037}
7038#endif
7039
7040/*
7041 * Retrieve completion matches from functions in the 'cpt' option where the
7042 * 'refresh:always' flag is set.
7043 */
7044 static void
7045cpt_compl_refresh(void)
7046{
7047#ifdef FEAT_COMPL_FUNC
7048 char_u *cpt;
7049 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007050 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007051 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007052
7053 // Make the completion list linear (non-cyclic)
7054 ins_compl_make_linear();
7055 // Make a copy of 'cpt' in case the buffer gets wiped out
7056 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007057 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007058
Girish Palya0ac1eb32025-04-16 20:18:33 +02007059 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007060 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007061 {
7062 while (*p == ',' || *p == ' ') // Skip delimiters
7063 p++;
7064
Girish Palya98c29db2025-06-01 19:40:00 +02007065 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007066 {
Girish Palya98c29db2025-06-01 19:40:00 +02007067 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007068 if (cb)
7069 {
7070 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007071 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7072 &startcol);
7073 if (ret == FAIL)
7074 {
7075 if (startcol == -3)
7076 cpt_sources_array[cpt_sources_index].cs_refresh_always
7077 = FALSE;
7078 else
7079 startcol = -2;
7080 }
7081 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7082 if (ret == OK)
7083 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007084 }
7085 }
7086
Girish Palya7c621052025-05-26 19:41:59 +02007087 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7088 if (may_advance_cpt_index(p))
7089 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007090 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007091 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007092
7093 vim_free(cpt);
7094 // Make the list cyclic
7095 compl_matches = ins_compl_make_cyclic();
7096#endif
7097}