blob: 51dd675b1379f7e28477afc4dfece18fe9c4dce0 [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
glepnir05460682025-05-26 18:23:27 +020041# define CTRL_X_REGISTER 18 // complete words from registers
Bram Moolenaar7591bb32019-03-30 13:53:47 +010042
43# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
44
45// Message for CTRL-X mode, index is ctrl_x_mode.
46static char *ctrl_x_msgs[] =
47{
48 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
glepnir05460682025-05-26 18:23:27 +020049 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010050 NULL, // CTRL_X_SCROLL: depends on state
51 N_(" Whole line completion (^L^N^P)"),
52 N_(" File name completion (^F^N^P)"),
53 N_(" Tag completion (^]^N^P)"),
54 N_(" Path pattern completion (^N^P)"),
55 N_(" Definition completion (^D^N^P)"),
56 NULL, // CTRL_X_FINISHED
57 N_(" Dictionary completion (^K^N^P)"),
58 N_(" Thesaurus completion (^T^N^P)"),
59 N_(" Command-line completion (^V^N^P)"),
60 N_(" User defined completion (^U^N^P)"),
61 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020062 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010063 N_(" Keyword Local completion (^N^P)"),
64 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020065 N_(" Command-line completion (^V^N^P)"),
glepnir05460682025-05-26 18:23:27 +020066 N_(" Register completion (^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010067};
68
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020069#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010070static char *ctrl_x_mode_names[] = {
Hirohito Higashi355db992025-04-28 18:07:02 +020071 "keyword",
72 "ctrl_x",
73 "scroll",
74 "whole_line",
75 "files",
76 "tags",
77 "path_patterns",
78 "path_defines",
79 "unknown", // CTRL_X_FINISHED
80 "dictionary",
81 "thesaurus",
82 "cmdline",
83 "function",
84 "omni",
85 "spell",
86 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
87 "eval",
88 "cmdline",
glepnir05460682025-05-26 18:23:27 +020089 "register",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010090};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020091#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010092
93/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010094 * Structure used to store one match for insert completion.
95 */
96typedef struct compl_S compl_T;
97struct compl_S
98{
99 compl_T *cp_next;
100 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +0100101 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +0100102 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200103 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100104#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100105 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100106#endif
glepnir0fe17f82024-10-08 22:26:44 +0200107 char_u *cp_fname; // file containing the match, allocated when
108 // cp_flags has CP_FREE_FNAME
109 int cp_flags; // CP_ values
110 int cp_number; // sequence number
Girish Palyab1565882025-04-15 20:16:00 +0200111 int cp_score; // fuzzy match score or proximity score
glepnird4088ed2024-12-31 10:55:22 +0100112 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200113 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200114 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palya0ac1eb32025-04-16 20:18:33 +0200115 int cp_cpt_source_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100116};
117
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200118// values for cp_flags
119# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
120# define CP_FREE_FNAME 2 // cp_fname is allocated
121# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
122# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
123# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200124# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100125
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126/*
127 * All the current matches are stored in a list.
128 * "compl_first_match" points to the start of the list.
129 * "compl_curr_match" points to the currently selected entry.
130 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200131 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000132 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100133 */
134static compl_T *compl_first_match = NULL;
135static compl_T *compl_curr_match = NULL;
136static compl_T *compl_shown_match = NULL;
137static compl_T *compl_old_match = NULL;
138
glepnirf31cfa22025-03-06 21:59:13 +0100139// list used to store the compl_T which have the max score
140// used for completefuzzycollect
141static compl_T **compl_best_matches = NULL;
142static int compl_num_bests = 0;
143// inserted a longest when completefuzzycollect enabled
144static int compl_cfc_longest_ins = FALSE;
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// After using a cursor key <Enter> selects a match in the popup menu,
147// otherwise it inserts a line break.
148static int compl_enter_selects = FALSE;
149
150// When "compl_leader" is not NULL only matches that start with this string
151// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100152static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100153
154static int compl_get_longest = FALSE; // put longest common string
155 // in compl_leader
156
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100157// Selected one of the matches. When FALSE the match was edited or using the
158// longest common string.
159static int compl_used_match;
160
161// didn't finish finding completions.
162static int compl_was_interrupted = FALSE;
163
164// Set when character typed while looking for matches and it means we should
165// stop looking for matches.
166static int compl_interrupted = FALSE;
167
168static int compl_restarting = FALSE; // don't insert match
169
170// When the first completion is done "compl_started" is set. When it's
171// FALSE the word to be completed must be located.
172static int compl_started = FALSE;
173
174// Which Ctrl-X mode are we in?
175static int ctrl_x_mode = CTRL_X_NORMAL;
176
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000177static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200178static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
179#ifdef FEAT_COMPL_FUNC
180static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
181#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100182static int compl_direction = FORWARD;
183static int compl_shows_dir = FORWARD;
184static int compl_pending = 0; // > 1 for postponed CTRL-N
185static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000186// Length in bytes of the text being completed (this is deleted to be replaced
187// by the match.)
188static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100189static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100190static colnr_T compl_col = 0; // column where the text starts
191 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100192static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100193static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100194 // completion started
195static int compl_cont_mode = 0;
196static expand_T compl_xp;
197
glepnircf7f0122025-04-15 19:02:00 +0200198static win_T *compl_curr_win = NULL; // win where completion is active
199static buf_T *compl_curr_buf = NULL; // buf where completion is active
200
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000201// List of flags for method of completion.
202static int compl_cont_status = 0;
203# define CONT_ADDING 1 // "normal" or "adding" expansion
204# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
205 // it's set only iff N_ADDS is set
206# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
207# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
208 // if so, word-wise-expansion will set SOL
209# define CONT_SOL 16 // pattern includes start of line, just for
210 // word-wise expansion, not set for ^X^L
211# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
212 // expansion, (eg use complete=.)
213
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100214static int compl_opt_refresh_always = FALSE;
215static int compl_opt_suppress_empty = FALSE;
216
glepnira218cc62024-06-03 19:32:39 +0200217static int compl_selected_item = -1;
218
glepnir8159fb12024-07-17 20:32:54 +0200219static int *compl_fuzzy_scores;
220
Girish Palya0ac1eb32025-04-16 20:18:33 +0200221// Define the structure for completion source (in 'cpt' option) information
222typedef struct cpt_source_T
223{
Girish Palya98c29db2025-06-01 19:40:00 +0200224 int cs_refresh_always; // Whether 'refresh:always' is set for func
225 int cs_startcol; // Start column returned by func
226 int cs_max_matches; // Max items to display from this source
Girish Palya0ac1eb32025-04-16 20:18:33 +0200227} cpt_source_T;
228
229static cpt_source_T *cpt_sources_array; // Pointer to the array of completion sources
230static int cpt_sources_count; // Total number of completion sources specified in the 'cpt' option
Girish Palya7c621052025-05-26 19:41:59 +0200231static int cpt_sources_index = -1; // Index of the current completion source being expanded
Girish Palyacbe53192025-04-14 22:13:15 +0200232
glepnir6a38aff2024-12-16 21:56:16 +0100233// "compl_match_array" points the currently displayed list of entries in the
234// popup menu. It is NULL when there is no popup menu.
235static pumitem_T *compl_match_array = NULL;
236static int compl_match_arraysize;
237
glepnirf31cfa22025-03-06 21:59:13 +0100238static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup, int *user_hl, int score);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100239static void ins_compl_longest_match(compl_T *match);
240static void ins_compl_del_pum(void);
241static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100243static int ins_compl_need_restart(void);
244static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000245static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100246static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100247static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100248static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
249# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
250static void ins_compl_add_list(list_T *list);
251static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200252static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
Girish Palyacbe53192025-04-14 22:13:15 +0200253static void get_cpt_func_completion_matches(callback_T *cb);
Girish Palya98c29db2025-06-01 19:40:00 +0200254static callback_T *get_callback_if_cpt_func(char_u *p);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100255# endif
Girish Palya98c29db2025-06-01 19:40:00 +0200256static int setup_cpt_sources(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200257static int is_cpt_func_refresh_always(void);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200258static void cpt_sources_clear(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200259static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100260static int ins_compl_key2dir(int c);
261static int ins_compl_pum_key(int c);
262static int ins_compl_key2count(int c);
263static void show_pum(int prev_w_wrow, int prev_w_leftcol);
264static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100265static int ins_compl_has_multiple(void);
266static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100267static void ins_compl_longest_insert(char_u *prefix);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100268
269#ifdef FEAT_SPELL
270static void spell_back_to_badword(void);
271static int spell_bad_len = 0; // length of located bad word
272#endif
273
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100274/*
275 * CTRL-X pressed in Insert mode.
276 */
277 void
278ins_ctrl_x(void)
279{
zeertzjqdca29d92021-08-31 19:12:51 +0200280 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100281 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000282 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100283 if (compl_cont_status & CONT_N_ADDS)
284 compl_cont_status |= CONT_INTRPT;
285 else
286 compl_cont_status = 0;
287 // We're not sure which CTRL-X mode it will be yet
288 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
289 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
290 edit_submode_pre = NULL;
291 showmode();
292 }
zeertzjqdca29d92021-08-31 19:12:51 +0200293 else
294 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
295 // CTRL-V look like CTRL-N
296 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100297
LemonBoy2bf52dd2022-04-09 18:17:34 +0100298 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100299}
300
301/*
302 * Functions to check the current CTRL-X mode.
303 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000304int ctrl_x_mode_none(void)
305 { return ctrl_x_mode == 0; }
306int ctrl_x_mode_normal(void)
307 { return ctrl_x_mode == CTRL_X_NORMAL; }
308int ctrl_x_mode_scroll(void)
309 { return ctrl_x_mode == CTRL_X_SCROLL; }
310int ctrl_x_mode_whole_line(void)
311 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
312int ctrl_x_mode_files(void)
313 { return ctrl_x_mode == CTRL_X_FILES; }
314int ctrl_x_mode_tags(void)
315 { return ctrl_x_mode == CTRL_X_TAGS; }
316int ctrl_x_mode_path_patterns(void)
317 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
318int ctrl_x_mode_path_defines(void)
319 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
320int ctrl_x_mode_dictionary(void)
321 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
322int ctrl_x_mode_thesaurus(void)
323 { return ctrl_x_mode == CTRL_X_THESAURUS; }
324int ctrl_x_mode_cmdline(void)
325 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200326 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000327int ctrl_x_mode_function(void)
328 { return ctrl_x_mode == CTRL_X_FUNCTION; }
329int ctrl_x_mode_omni(void)
330 { return ctrl_x_mode == CTRL_X_OMNI; }
331int ctrl_x_mode_spell(void)
332 { return ctrl_x_mode == CTRL_X_SPELL; }
333static int ctrl_x_mode_eval(void)
334 { return ctrl_x_mode == CTRL_X_EVAL; }
335int ctrl_x_mode_line_or_eval(void)
336 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
glepnir05460682025-05-26 18:23:27 +0200337int ctrl_x_mode_register(void)
338 { return ctrl_x_mode == CTRL_X_REGISTER; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100339
340/*
341 * Whether other than default completion has been selected.
342 */
343 int
344ctrl_x_mode_not_default(void)
345{
346 return ctrl_x_mode != CTRL_X_NORMAL;
347}
348
349/*
zeertzjqdca29d92021-08-31 19:12:51 +0200350 * Whether CTRL-X was typed without a following character,
351 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100352 */
353 int
354ctrl_x_mode_not_defined_yet(void)
355{
356 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
357}
358
359/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000360 * Return TRUE if currently in "normal" or "adding" insert completion matches
361 * state
362 */
363 int
364compl_status_adding(void)
365{
366 return compl_cont_status & CONT_ADDING;
367}
368
369/*
370 * Return TRUE if the completion pattern includes start of line, just for
371 * word-wise expansion.
372 */
373 int
374compl_status_sol(void)
375{
376 return compl_cont_status & CONT_SOL;
377}
378
379/*
380 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
381 */
382 int
383compl_status_local(void)
384{
385 return compl_cont_status & CONT_LOCAL;
386}
387
388/*
389 * Clear the completion status flags
390 */
391 void
392compl_status_clear(void)
393{
394 compl_cont_status = 0;
395}
396
397/*
398 * Return TRUE if completion is using the forward direction matches
399 */
400 static int
401compl_dir_forward(void)
402{
403 return compl_direction == FORWARD;
404}
405
406/*
407 * Return TRUE if currently showing forward completion matches
408 */
409 static int
410compl_shows_dir_forward(void)
411{
412 return compl_shows_dir == FORWARD;
413}
414
415/*
416 * Return TRUE if currently showing backward completion matches
417 */
418 static int
419compl_shows_dir_backward(void)
420{
421 return compl_shows_dir == BACKWARD;
422}
423
424/*
425 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100426 */
427 int
428has_compl_option(int dict_opt)
429{
430 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200431#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100432 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200433#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100435 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
436#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100437 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100438#endif
439 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100440 {
441 ctrl_x_mode = CTRL_X_NORMAL;
442 edit_submode = NULL;
443 msg_attr(dict_opt ? _("'dictionary' option is empty")
444 : _("'thesaurus' option is empty"),
445 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100446 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100447 {
448 vim_beep(BO_COMPL);
449 setcursor();
450 out_flush();
451#ifdef FEAT_EVAL
452 if (!get_vim_var_nr(VV_TESTING))
453#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100454 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100455 }
456 return FALSE;
457 }
458 return TRUE;
459}
460
461/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000462 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100463 * This depends on the current mode.
464 */
465 int
466vim_is_ctrl_x_key(int c)
467{
468 // Always allow ^R - let its results then be checked
glepnir05460682025-05-26 18:23:27 +0200469 if (c == Ctrl_R && ctrl_x_mode != CTRL_X_REGISTER)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100470 return TRUE;
471
472 // Accept <PageUp> and <PageDown> if the popup menu is visible.
473 if (ins_compl_pum_key(c))
474 return TRUE;
475
476 switch (ctrl_x_mode)
477 {
478 case 0: // Not in any CTRL-X mode
479 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
480 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200481 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100482 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
483 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
484 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
485 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
486 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200487 || c == Ctrl_S || c == Ctrl_K || c == 's'
glepnir05460682025-05-26 18:23:27 +0200488 || c == Ctrl_Z || c == Ctrl_R);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100489 case CTRL_X_SCROLL:
490 return (c == Ctrl_Y || c == Ctrl_E);
491 case CTRL_X_WHOLE_LINE:
492 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
493 case CTRL_X_FILES:
494 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
495 case CTRL_X_DICTIONARY:
496 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
497 case CTRL_X_THESAURUS:
498 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
499 case CTRL_X_TAGS:
500 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
501#ifdef FEAT_FIND_ID
502 case CTRL_X_PATH_PATTERNS:
503 return (c == Ctrl_P || c == Ctrl_N);
504 case CTRL_X_PATH_DEFINES:
505 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
506#endif
507 case CTRL_X_CMDLINE:
508 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
509 || c == Ctrl_X);
510#ifdef FEAT_COMPL_FUNC
511 case CTRL_X_FUNCTION:
512 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
513 case CTRL_X_OMNI:
514 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
515#endif
516 case CTRL_X_SPELL:
517 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
518 case CTRL_X_EVAL:
519 return (c == Ctrl_P || c == Ctrl_N);
glepnir05460682025-05-26 18:23:27 +0200520 case CTRL_X_REGISTER:
521 return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100522 }
523 internal_error("vim_is_ctrl_x_key()");
524 return FALSE;
525}
526
527/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000528 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000529 */
530 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000531match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000532{
533 return match->cp_flags & CP_ORIGINAL_TEXT;
534}
535
536/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000537 * Returns TRUE if "match" is the first match in the completion list.
538 */
539 static int
540is_first_match(compl_T *match)
541{
542 return match == compl_first_match;
543}
544
545/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100546 * Return TRUE when character "c" is part of the item currently being
547 * completed. Used to decide whether to abandon complete mode when the menu
548 * is visible.
549 */
550 int
551ins_compl_accept_char(int c)
552{
553 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
554 // When expanding an identifier only accept identifier chars.
555 return vim_isIDc(c);
556
557 switch (ctrl_x_mode)
558 {
559 case CTRL_X_FILES:
560 // When expanding file name only accept file name chars. But not
561 // path separators, so that "proto/<Tab>" expands files in
562 // "proto", not "proto/" as a whole
563 return vim_isfilec(c) && !vim_ispathsep(c);
564
565 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200566 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100567 case CTRL_X_OMNI:
568 // Command line and Omni completion can work with just about any
569 // printable character, but do stop at white space.
570 return vim_isprintc(c) && !VIM_ISWHITE(c);
571
572 case CTRL_X_WHOLE_LINE:
573 // For while line completion a space can be part of the line.
574 return vim_isprintc(c);
575 }
576 return vim_iswordc(c);
577}
578
579/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000580 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100581 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 */
583 static char_u *
584ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200585 char_u *str,
586 int char_len,
587 int compl_char_len,
588 int min_len,
589 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000590{
591 int *wca; // Wide character array.
592 char_u *p;
593 int i, c;
594 int has_lower = FALSE;
595 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100596 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000597
598 IObuff[0] = NUL;
599
600 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100601 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000602 if (wca == NULL)
603 return IObuff;
604
605 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100606 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100607 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000608 if (has_mbyte)
609 wca[i] = mb_ptr2char_adv(&p);
610 else
611 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100612 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000613
614 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100615 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000616 for (i = 0; i < min_len; ++i)
617 {
glepnir6e199932024-12-14 21:13:27 +0100618 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000619 if (MB_ISLOWER(c))
620 {
621 has_lower = TRUE;
622 if (MB_ISUPPER(wca[i]))
623 {
624 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100625 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000626 wca[i] = MB_TOLOWER(wca[i]);
627 break;
628 }
629 }
630 }
631
632 // Rule 2: No lower case, 2nd consecutive letter converted to
633 // upper case.
634 if (!has_lower)
635 {
John Marriott5e6ea922024-11-23 14:01:57 +0100636 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000637 for (i = 0; i < min_len; ++i)
638 {
glepnir6e199932024-12-14 21:13:27 +0100639 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000640 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
641 {
642 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100643 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000644 wca[i] = MB_TOUPPER(wca[i]);
645 break;
646 }
647 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
648 }
649 }
650
651 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100652 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000653 for (i = 0; i < min_len; ++i)
654 {
glepnir6e199932024-12-14 21:13:27 +0100655 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000656 if (MB_ISLOWER(c))
657 wca[i] = MB_TOLOWER(wca[i]);
658 else if (MB_ISUPPER(c))
659 wca[i] = MB_TOUPPER(wca[i]);
660 }
661
662 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000663 p = IObuff;
664 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100665 ga_init2(&gap, 1, 500);
666 while (i < char_len)
667 {
668 if (gap.ga_data != NULL)
669 {
670 if (ga_grow(&gap, 10) == FAIL)
671 {
672 ga_clear(&gap);
673 return (char_u *)"[failed]";
674 }
675 p = (char_u *)gap.ga_data + gap.ga_len;
676 if (has_mbyte)
677 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
678 else
679 {
680 *p = wca[i++];
681 ++gap.ga_len;
682 }
683 }
684 else if ((p - IObuff) + 6 >= IOSIZE)
685 {
686 // Multi-byte characters can occupy up to five bytes more than
687 // ASCII characters, and we also need one byte for NUL, so when
688 // getting to six bytes from the edge of IObuff switch to using a
689 // growarray. Add the character in the next round.
690 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100691 {
692 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100693 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100694 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100695 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100696 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100697 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 }
699 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000700 p += (*mb_char2bytes)(wca[i++], p);
701 else
702 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100703 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000704 vim_free(wca);
705
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100706 if (gap.ga_data != NULL)
707 {
708 *tofree = gap.ga_data;
709 return gap.ga_data;
710 }
711
712 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000713 return IObuff;
714}
715
716/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100717 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
718 * case of the originally typed text is used, and the case of the completed
719 * text is inferred, ie this tries to work out what case you probably wanted
720 * the rest of the word to be in -- webb
721 */
722 int
723ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200724 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 int len,
726 int icase,
727 char_u *fname,
728 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100729 int cont_s_ipos, // next ^X<> will set initial_pos
730 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100731{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200732 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100734 int char_len; // count multi-byte characters
735 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100736 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200737 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 int res;
739 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100740
741 if (p_ic && curbuf->b_p_inf && len > 0)
742 {
743 // Infer case of completed part.
744
745 // Find actual length of completion.
746 if (has_mbyte)
747 {
748 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100749 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100750 while (*p != NUL)
751 {
752 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100753 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100754 }
755 }
756 else
glepnir6e199932024-12-14 21:13:27 +0100757 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100758 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100759 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100760
761 // Find actual length of original text.
762 if (has_mbyte)
763 {
John Marriott5e6ea922024-11-23 14:01:57 +0100764 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100765 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 while (*p != NUL)
767 {
768 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100769 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100770 }
771 }
772 else
glepnir6e199932024-12-14 21:13:27 +0100773 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100774 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100775 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100776
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100777 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100778 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100779 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100781 str = ins_compl_infercase_gettext(str, char_len,
782 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100783 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200784 if (cont_s_ipos)
785 flags |= CP_CONT_S_IPOS;
786 if (icase)
787 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200788
glepnirf31cfa22025-03-06 21:59:13 +0100789 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100790 vim_free(tofree);
791 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100792}
793
794/*
glepnirf31cfa22025-03-06 21:59:13 +0100795 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
796 */
797 static int
798cfc_has_mode(void)
799{
glepnir58760162025-03-13 21:39:51 +0100800 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
801 return (cfc_flags & CFC_KEYWORD) != 0;
802 else if (ctrl_x_mode_files())
803 return (cfc_flags & CFC_FILES) != 0;
804 else if (ctrl_x_mode_whole_line())
805 return (cfc_flags & CFC_WHOLELINE) != 0;
806 else
807 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100808}
809
810/*
Girish Palyab1565882025-04-15 20:16:00 +0200811 * Returns TRUE if matches should be sorted based on proximity to the cursor.
812 */
813 static int
814is_nearest_active(void)
815{
glepnirc3fbaa02025-05-08 23:05:10 +0200816 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200817}
818
819/*
820 * Repositions a match in the completion list based on its proximity score.
821 * If the match is at the head and has a higher score than the next node,
822 * or if it's in the middle/tail and has a lower score than the previous node,
823 * it is moved to the correct position while maintaining ascending order.
824 */
825 static void
826reposition_match(compl_T *match)
827{
828 compl_T *insert_before = NULL;
829 compl_T *insert_after = NULL;
830
831 // Node is at head and score is too big
832 if (!match->cp_prev)
833 {
834 if (match->cp_next && match->cp_next->cp_score > 0 &&
835 match->cp_next->cp_score < match->cp_score)
836 {
837 // <c-p>: compl_first_match is at head and newly inserted node
838 compl_first_match = compl_curr_match = match->cp_next;
839 // Find the correct position in ascending order
840 insert_before = match->cp_next;
841 do
842 {
843 insert_after = insert_before;
844 insert_before = insert_before->cp_next;
845 } while (insert_before && insert_before->cp_score > 0 &&
846 insert_before->cp_score < match->cp_score);
847 }
848 else
849 return;
850 }
851 // Node is at tail or in the middle but score is too small
852 else
853 {
854 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
855 {
856 // <c-n>: compl_curr_match (and newly inserted match) is at tail
857 if (!match->cp_next)
858 compl_curr_match = compl_curr_match->cp_prev;
859 // Find the correct position in ascending order
860 insert_after = match->cp_prev;
861 do
862 {
863 insert_before = insert_after;
864 insert_after = insert_after->cp_prev;
865 } while (insert_after && insert_after->cp_score > 0 &&
866 insert_after->cp_score > match->cp_score);
867 }
868 else
869 return;
870 }
871
872 if (insert_after)
873 {
874 // Remove the match from its current position
875 if (match->cp_prev)
876 match->cp_prev->cp_next = match->cp_next;
877 else
878 compl_first_match = match->cp_next;
879 if (match->cp_next)
880 match->cp_next->cp_prev = match->cp_prev;
881
882 // Insert the match at the correct position
883 match->cp_next = insert_before;
884 match->cp_prev = insert_after;
885 insert_after->cp_next = match;
886 insert_before->cp_prev = match;
887 }
888}
889
890/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000891 * Add a match to the list of matches. The arguments are:
892 * str - text of the match to add
893 * len - length of "str". If -1, then the length of "str" is
894 * computed.
895 * fname - file name to associate with this match.
896 * cptext - list of strings to use with this match (for abbr, menu, info
897 * and kind)
898 * user_data - user supplied data (any vim type) for this match
899 * cdir - match direction. If 0, use "compl_direction".
900 * flags_arg - match flags (cp_flags)
901 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100902 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000903 * If "cdir" is FORWARD, then the match is added after the current match.
904 * Otherwise, it is added before the current match.
905 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100906 * If the given string is already in the list of completions, then return
907 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
908 * maybe because alloc() returns NULL, then FAIL is returned.
909 */
910 static int
911ins_compl_add(
912 char_u *str,
913 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100914 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100915 char_u **cptext, // extra text for popup menu or NULL
916 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100917 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200918 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200919 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100920 int *user_hl, // user abbr/kind hlattr
921 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100922{
glepnirf31cfa22025-03-06 21:59:13 +0100923 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100924 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200925 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100926 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100927
Bram Moolenaarceb06192021-04-04 15:05:22 +0200928 if (flags & CP_FAST)
929 fast_breakcheck();
930 else
931 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100932 if (got_int)
933 return FAIL;
934 if (len < 0)
935 len = (int)STRLEN(str);
936
937 // If the same match is already present, don't add it.
938 if (compl_first_match != NULL && !adup)
939 {
940 match = compl_first_match;
941 do
942 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000943 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100944 && STRNCMP(match->cp_str.string, str, len) == 0
945 && ((int)match->cp_str.length <= len
946 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200947 {
948 if (is_nearest_active() && score > 0 && score < match->cp_score)
949 {
950 match->cp_score = score;
951 reposition_match(match);
952 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100953 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200954 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100955 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000956 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100957 }
958
959 // Remove any popup menu before changing the list of matches.
960 ins_compl_del_pum();
961
962 // Allocate a new match structure.
963 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200964 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100965 if (match == NULL)
966 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100967 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100968 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100969 {
970 vim_free(match);
971 return FAIL;
972 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100973
John Marriott5e6ea922024-11-23 14:01:57 +0100974 match->cp_str.length = len;
975
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100976 // match-fname is:
977 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200978 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100979 // - NULL otherwise. --Acevedo
980 if (fname != NULL
981 && compl_curr_match != NULL
982 && compl_curr_match->cp_fname != NULL
983 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
984 match->cp_fname = compl_curr_match->cp_fname;
985 else if (fname != NULL)
986 {
987 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200988 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100989 }
990 else
991 match->cp_fname = NULL;
992 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100993 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
994 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100995 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200996 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100997
998 if (cptext != NULL)
999 {
glepnir19e1dd62025-05-08 22:50:38 +02001000 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +01001001 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002 if (cptext[i] != NULL && *cptext[i] != NUL)
1003 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +01001004 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001005 }
Bram Moolenaarab782c52020-01-04 19:00:11 +01001006#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001007 if (user_data != NULL)
1008 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +01001009#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001010
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001011 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1012 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001013 if (compl_first_match == NULL)
1014 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001015 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1016 {
1017 current = compl_first_match->cp_next;
1018 prev = compl_first_match;
1019 inserted = FALSE;
1020 // The direction is ignored when using longest and
1021 // completefuzzycollect, because matches are inserted
1022 // and sorted by score.
1023 while (current != NULL && current != compl_first_match)
1024 {
1025 if (current->cp_score < score)
1026 {
Hirohito Higashi355db992025-04-28 18:07:02 +02001027 match->cp_next = current;
1028 match->cp_prev = current->cp_prev;
1029 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +01001030 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +02001031 current->cp_prev = match;
1032 inserted = TRUE;
1033 break;
glepnirf31cfa22025-03-06 21:59:13 +01001034 }
1035 prev = current;
1036 current = current->cp_next;
1037 }
1038 if (!inserted)
1039 {
1040 prev->cp_next = match;
1041 match->cp_prev = prev;
1042 match->cp_next = compl_first_match;
1043 compl_first_match->cp_prev = match;
1044 }
1045 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001046 else if (dir == FORWARD)
1047 {
1048 match->cp_next = compl_curr_match->cp_next;
1049 match->cp_prev = compl_curr_match;
1050 }
1051 else // BACKWARD
1052 {
1053 match->cp_next = compl_curr_match;
1054 match->cp_prev = compl_curr_match->cp_prev;
1055 }
1056 if (match->cp_next)
1057 match->cp_next->cp_prev = match;
1058 if (match->cp_prev)
1059 match->cp_prev->cp_next = match;
1060 else // if there's nothing before, it is the first match
1061 compl_first_match = match;
1062 compl_curr_match = match;
1063
Girish Palyab1565882025-04-15 20:16:00 +02001064 if (is_nearest_active() && score > 0)
1065 reposition_match(match);
1066
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001067 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001068 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001069 ins_compl_longest_match(match);
1070
1071 return OK;
1072}
1073
1074/*
1075 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001076 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001077 */
1078 static int
1079ins_compl_equal(compl_T *match, char_u *str, int len)
1080{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001081 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001082 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001083 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001084 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1085 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001086}
1087
1088/*
glepnir6a38aff2024-12-16 21:56:16 +01001089 * when len is -1 mean use whole length of p otherwise part of p
1090 */
1091 static void
1092ins_compl_insert_bytes(char_u *p, int len)
1093{
1094 if (len == -1)
1095 len = (int)STRLEN(p);
1096 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001097 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001098}
1099
1100/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001101 * Checks if the column is within the currently inserted completion text
1102 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001103 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001104 */
1105 int
glepnir76bdb822025-02-08 19:04:51 +01001106ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001107{
glepnir76bdb822025-02-08 19:04:51 +01001108 int start_col;
1109 int attr;
1110
1111 if ((get_cot_flags() & COT_FUZZY)
1112 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001113 return -1;
1114
glepnir76bdb822025-02-08 19:04:51 +01001115 start_col = compl_col + (int)ins_compl_leader_len();
1116 if (!ins_compl_has_multiple())
1117 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1118
1119 // Multiple lines
1120 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1121 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1122 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1123 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001124
1125 return -1;
1126}
1127
1128/*
glepnir76bdb822025-02-08 19:04:51 +01001129 * Returns TRUE if the current completion string contains newline characters,
1130 * indicating it's a multi-line completion.
1131 */
1132 static int
1133ins_compl_has_multiple(void)
1134{
1135 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1136}
1137
1138/*
1139 * Returns TRUE if the given line number falls within the range of a multi-line
1140 * completion, i.e. between the starting line (compl_lnum) and current cursor
1141 * line. Always returns FALSE for single-line completions.
1142 */
1143 int
1144ins_compl_lnum_in_range(linenr_T lnum)
1145{
1146 if (!ins_compl_has_multiple())
1147 return FALSE;
1148 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1149}
1150
1151/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001152 * Reduce the longest common string for match "match".
1153 */
1154 static void
1155ins_compl_longest_match(compl_T *match)
1156{
1157 char_u *p, *s;
1158 int c1, c2;
1159 int had_match;
1160
John Marriott5e6ea922024-11-23 14:01:57 +01001161 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001162 {
1163 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001164 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1165 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001166 return;
1167
John Marriott5e6ea922024-11-23 14:01:57 +01001168 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001169 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001170 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001171
1172 // When the match isn't there (to avoid matching itself) remove it
1173 // again after redrawing.
1174 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001176 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001177
1178 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001179 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001180
1181 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001182 p = compl_leader.string;
1183 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001184 while (*p != NUL)
1185 {
1186 if (has_mbyte)
1187 {
1188 c1 = mb_ptr2char(p);
1189 c2 = mb_ptr2char(s);
1190 }
1191 else
1192 {
1193 c1 = *p;
1194 c2 = *s;
1195 }
1196 if ((match->cp_flags & CP_ICASE)
1197 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1198 break;
1199 if (has_mbyte)
1200 {
1201 MB_PTR_ADV(p);
1202 MB_PTR_ADV(s);
1203 }
1204 else
1205 {
1206 ++p;
1207 ++s;
1208 }
1209 }
1210
1211 if (*p != NUL)
1212 {
1213 // Leader was shortened, need to change the inserted text.
1214 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001215 compl_leader.length = (size_t)(p - compl_leader.string);
1216
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001217 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001218 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001219
1220 // When the match isn't there (to avoid matching itself) remove it
1221 // again after redrawing.
1222 if (!had_match)
1223 ins_compl_delete();
1224 }
1225
1226 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227}
1228
1229/*
1230 * Add an array of matches to the list of matches.
1231 * Frees matches[].
1232 */
1233 static void
1234ins_compl_add_matches(
1235 int num_matches,
1236 char_u **matches,
1237 int icase)
1238{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001239 int add_r = OK;
1240 int dir = compl_direction;
1241
glepnir19e1dd62025-05-08 22:50:38 +02001242 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001243 {
1244 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001245 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001246 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001247 // if dir was BACKWARD then honor it just once
1248 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001249 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001250 FreeWild(num_matches, matches);
1251}
1252
1253/*
1254 * Make the completion list cyclic.
1255 * Return the number of matches (excluding the original).
1256 */
1257 static int
1258ins_compl_make_cyclic(void)
1259{
1260 compl_T *match;
1261 int count = 0;
1262
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001263 if (compl_first_match == NULL)
1264 return 0;
1265
1266 // Find the end of the list.
1267 match = compl_first_match;
1268 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001269 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001270 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001271 match = match->cp_next;
1272 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001273 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001274 match->cp_next = compl_first_match;
1275 compl_first_match->cp_prev = match;
1276
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001277 return count;
1278}
1279
1280/*
1281 * Return whether there currently is a shown match.
1282 */
1283 int
1284ins_compl_has_shown_match(void)
1285{
1286 return compl_shown_match == NULL
1287 || compl_shown_match != compl_shown_match->cp_next;
1288}
1289
1290/*
1291 * Return whether the shown match is long enough.
1292 */
1293 int
1294ins_compl_long_shown_match(void)
1295{
John Marriott5e6ea922024-11-23 14:01:57 +01001296 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001297 > curwin->w_cursor.col - compl_col;
1298}
1299
1300/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001301 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001302 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 unsigned int
1304get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001305{
zeertzjq529b9ad2024-06-05 20:27:06 +02001306 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001307}
1308
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001309/*
1310 * Update the screen and when there is any scrolling remove the popup menu.
1311 */
1312 static void
1313ins_compl_upd_pum(void)
1314{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001315 if (compl_match_array == NULL)
1316 return;
1317
glepnir19e1dd62025-05-08 22:50:38 +02001318 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001319 // Update the screen later, before drawing the popup menu over it.
1320 pum_call_update_screen();
1321 if (h != curwin->w_cline_height)
1322 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001323}
1324
1325/*
1326 * Remove any popup menu.
1327 */
1328 static void
1329ins_compl_del_pum(void)
1330{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001331 if (compl_match_array == NULL)
1332 return;
1333
1334 pum_undisplay();
1335 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001336}
1337
1338/*
1339 * Return TRUE if the popup menu should be displayed.
1340 */
1341 int
1342pum_wanted(void)
1343{
1344 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001345 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001346 return FALSE;
1347
1348 // The display looks bad on a B&W display.
1349 if (t_colors < 8
1350#ifdef FEAT_GUI
1351 && !gui.in_use
1352#endif
1353 )
1354 return FALSE;
1355 return TRUE;
1356}
1357
1358/*
1359 * Return TRUE if there are two or more matches to be shown in the popup menu.
1360 * One if 'completopt' contains "menuone".
1361 */
1362 static int
1363pum_enough_matches(void)
1364{
1365 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001366 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001367
1368 // Don't display the popup menu if there are no matches or there is only
1369 // one (ignoring the original text).
1370 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001371 do
1372 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001373 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001374 break;
1375 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001376 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001377
zeertzjq529b9ad2024-06-05 20:27:06 +02001378 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001379 return (i >= 1);
1380 return (i >= 2);
1381}
1382
Bram Moolenaar3075a452021-11-17 15:51:52 +00001383#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001384/*
1385 * Allocate Dict for the completed item.
1386 * { word, abbr, menu, kind, info }
1387 */
1388 static dict_T *
1389ins_compl_dict_alloc(compl_T *match)
1390{
1391 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1392
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001393 if (dict == NULL)
1394 return NULL;
1395
John Marriott5e6ea922024-11-23 14:01:57 +01001396 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001397 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1398 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1399 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1400 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1401 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1402 dict_add_string(dict, "user_data", (char_u *)"");
1403 else
1404 dict_add_tv(dict, "user_data", &match->cp_user_data);
1405
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001406 return dict;
1407}
1408
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001409/*
1410 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1411 * completion menu is changed.
1412 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001413 static void
1414trigger_complete_changed_event(int cur)
1415{
1416 dict_T *v_event;
1417 dict_T *item;
1418 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001419 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001420
1421 if (recursive)
1422 return;
1423
glepnir40891ba2025-02-10 22:18:00 +01001424 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001425 if (item == NULL)
1426 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001427 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001428 dict_add_dict(v_event, "completed_item", item);
1429 pum_set_event_info(v_event);
1430 dict_set_items_ro(v_event);
1431
1432 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001433 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001434 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001435 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001436 recursive = FALSE;
1437
Bram Moolenaar3075a452021-11-17 15:51:52 +00001438 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001439}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001440#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001441
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001442/*
Girish Palya19ef6b02025-05-28 20:28:21 +02001443 * Trim compl_match_array to enforce max_matches per completion source.
1444 *
1445 * Note: This special-case trimming is a workaround because compl_match_array
1446 * becomes inconsistent with compl_first_match (list) after former is sorted by
1447 * fuzzy score. The two structures end up in different orders.
1448 * Ideally, compl_first_match list should have been sorted instead.
Girish Palya6c40df02025-06-01 20:11:59 +02001449 *
1450 * Returns recalculated index of shown match.
Girish Palya19ef6b02025-05-28 20:28:21 +02001451 */
Girish Palya6c40df02025-06-01 20:11:59 +02001452 static int
1453trim_compl_match_array(int shown_match_idx)
Girish Palya19ef6b02025-05-28 20:28:21 +02001454{
1455 int i, src_idx, limit, new_size = 0, *match_counts = NULL;
1456 pumitem_T *trimmed = NULL;
Girish Palya6c40df02025-06-01 20:11:59 +02001457 int trimmed_idx = 0, remove_count = 0;
Girish Palya19ef6b02025-05-28 20:28:21 +02001458
1459 // Count current matches per source.
1460 match_counts = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1461 if (match_counts == NULL)
Girish Palya6c40df02025-06-01 20:11:59 +02001462 return shown_match_idx;
Girish Palya19ef6b02025-05-28 20:28:21 +02001463 for (i = 0; i < compl_match_arraysize; i++)
1464 {
1465 src_idx = compl_match_array[i].pum_cpt_source_idx;
1466 if (src_idx != -1)
1467 match_counts[src_idx]++;
1468 }
1469
1470 // Calculate size of trimmed array, respecting max_matches per source.
1471 for (i = 0; i < cpt_sources_count; i++)
1472 {
Girish Palya98c29db2025-06-01 19:40:00 +02001473 limit = cpt_sources_array[i].cs_max_matches;
Girish Palya19ef6b02025-05-28 20:28:21 +02001474 new_size += (limit > 0 && match_counts[i] > limit)
1475 ? limit : match_counts[i];
1476 }
1477
1478 if (new_size == compl_match_arraysize)
1479 goto theend;
1480
1481 // Create trimmed array while enforcing per-source limits
1482 trimmed = ALLOC_CLEAR_MULT(pumitem_T, new_size);
1483 if (trimmed == NULL)
1484 goto theend;
1485 vim_memset(match_counts, 0, sizeof(int) * cpt_sources_count);
1486 for (i = 0; i < compl_match_arraysize; i++)
1487 {
1488 src_idx = compl_match_array[i].pum_cpt_source_idx;
1489 if (src_idx != -1)
1490 {
Girish Palya98c29db2025-06-01 19:40:00 +02001491 limit = cpt_sources_array[src_idx].cs_max_matches;
Girish Palya19ef6b02025-05-28 20:28:21 +02001492 if (limit <= 0 || match_counts[src_idx] < limit)
1493 {
1494 trimmed[trimmed_idx++] = compl_match_array[i];
1495 match_counts[src_idx]++;
1496 }
Girish Palya6c40df02025-06-01 20:11:59 +02001497 else if (i < shown_match_idx)
1498 remove_count++;
Girish Palya19ef6b02025-05-28 20:28:21 +02001499 }
1500 else
1501 trimmed[trimmed_idx++] = compl_match_array[i];
1502 }
1503 vim_free(compl_match_array);
1504 compl_match_array = trimmed;
1505 compl_match_arraysize = new_size;
1506
1507theend:
1508 vim_free(match_counts);
Girish Palya6c40df02025-06-01 20:11:59 +02001509 return shown_match_idx - remove_count;
Girish Palya19ef6b02025-05-28 20:28:21 +02001510}
1511
1512/*
glepnira218cc62024-06-03 19:32:39 +02001513 * pumitem qsort compare func
1514 */
1515 static int
zeertzjq8e567472024-06-14 20:04:42 +02001516ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001517{
1518 const int sa = (*(pumitem_T *)a).pum_score;
1519 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001520 const int ia = (*(pumitem_T *)a).pum_idx;
1521 const int ib = (*(pumitem_T *)b).pum_idx;
1522 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001523}
1524
1525/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001526 * Build a popup menu to show the completion matches.
1527 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1528 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001529 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001530 static int
1531ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001532{
1533 compl_T *compl;
1534 compl_T *shown_compl = NULL;
1535 int did_find_shown_match = FALSE;
1536 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001537 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001538 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001539 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001540 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001541 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001542 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1543 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001544 compl_T *match_head = NULL;
1545 compl_T *match_tail = NULL;
1546 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001547 int update_shown_match = fuzzy_filter;
Christian Brabandtb53d4fb2025-04-16 21:12:30 +02001548 int match_count = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001549 int cur_source = -1;
1550 int max_matches_found = FALSE;
Girish Palya19ef6b02025-05-28 20:28:21 +02001551 int is_forward = compl_shows_dir_forward();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001552
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001553 // Need to build the popup menu list.
1554 compl_match_arraysize = 0;
1555 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001556
glepnira49c0772024-11-30 10:56:30 +01001557 // If the current match is the original text don't find the first
1558 // match after it, don't highlight anything.
1559 if (match_at_original_text(compl_shown_match))
1560 shown_match_ok = TRUE;
1561
glepnire4e4d1c2025-04-02 20:18:25 +02001562 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1563 && compl_shown_match->cp_score > 0)
1564 update_shown_match = FALSE;
1565
glepnira49c0772024-11-30 10:56:30 +01001566 if (compl_leader.string != NULL
1567 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1568 && shown_match_ok == FALSE)
1569 compl_shown_match = compl_no_select ? compl_first_match
1570 : compl_first_match->cp_next;
1571
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001572 do
1573 {
glepnird4088ed2024-12-31 10:55:22 +01001574 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001575 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1576 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001577 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001578 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001579
Girish Palya19ef6b02025-05-28 20:28:21 +02001580 if (is_forward && !fuzzy_sort && compl->cp_cpt_source_idx != -1)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001581 {
1582 if (cur_source != compl->cp_cpt_source_idx)
1583 {
1584 cur_source = compl->cp_cpt_source_idx;
1585 match_count = 1;
1586 max_matches_found = FALSE;
1587 }
Girish Palyadc314052025-05-08 23:28:52 +02001588 else if (cpt_sources_array != NULL && !max_matches_found)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001589 {
Girish Palya98c29db2025-06-01 19:40:00 +02001590 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001591 if (max_matches > 0 && match_count > max_matches)
1592 max_matches_found = TRUE;
1593 }
1594 }
1595
Girish Palyadc314052025-05-08 23:28:52 +02001596 // Apply 'smartcase' behavior during normal mode
1597 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1598 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1599 compl->cp_flags &= ~CP_ICASE;
1600
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001601 if (!match_at_original_text(compl)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001602 && !max_matches_found
John Marriott5e6ea922024-11-23 14:01:57 +01001603 && (compl_leader.string == NULL
Girish Palyadc314052025-05-08 23:28:52 +02001604 || ins_compl_equal(compl, compl_leader.string,
1605 (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001606 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001607 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001608 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001609 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001610 if (match_head == NULL)
1611 match_head = compl;
1612 else
glepnira49c0772024-11-30 10:56:30 +01001613 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001614 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001615
glepnirf400a0c2025-01-23 19:55:14 +01001616 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001617 {
1618 if (compl == compl_shown_match || did_find_shown_match)
1619 {
1620 // This item is the shown match or this is the
1621 // first displayed item after the shown match.
1622 compl_shown_match = compl;
1623 did_find_shown_match = TRUE;
1624 shown_match_ok = TRUE;
1625 }
1626 else
1627 // Remember this displayed match for when the
1628 // shown match is just below it.
1629 shown_compl = compl;
1630 cur = i;
1631 }
glepnirf400a0c2025-01-23 19:55:14 +01001632 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001633 {
1634 if (i == 0)
1635 shown_compl = compl;
1636 // Update the maximum fuzzy score and the shown match
1637 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001638 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1639 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001640 {
1641 did_find_shown_match = TRUE;
1642 max_fuzzy_score = compl->cp_score;
1643 if (!compl_no_select)
1644 compl_shown_match = compl;
1645 }
1646
glepnir3af0a8d2025-02-20 22:06:16 +01001647 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001648 {
1649 cur = i;
1650 shown_match_ok = TRUE;
1651 }
1652 }
Girish Palya19ef6b02025-05-28 20:28:21 +02001653 if (is_forward && !fuzzy_sort && compl->cp_cpt_source_idx != -1)
Girish Palya0ac1eb32025-04-16 20:18:33 +02001654 match_count++;
glepnira49c0772024-11-30 10:56:30 +01001655 i++;
glepnir80b66202024-11-27 21:53:53 +01001656 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001657
glepnirf400a0c2025-01-23 19:55:14 +01001658 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001659 {
1660 did_find_shown_match = TRUE;
1661
1662 // When the original text is the shown match don't set
1663 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001664 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001665 shown_match_ok = TRUE;
1666
1667 if (!shown_match_ok && shown_compl != NULL)
1668 {
1669 // The shown match isn't displayed, set it to the
1670 // previously displayed match.
1671 compl_shown_match = shown_compl;
1672 shown_match_ok = TRUE;
1673 }
1674 }
glepnira49c0772024-11-30 10:56:30 +01001675 compl = compl->cp_next;
1676 } while (compl != NULL && !is_first_match(compl));
1677
1678 if (compl_match_arraysize == 0)
1679 return -1;
1680
glepnirc0b7ca42025-02-13 20:27:44 +01001681 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1682 {
1683 compl_shown_match = shown_compl;
1684 shown_match_ok = TRUE;
1685 cur = 0;
1686 }
1687
glepnira49c0772024-11-30 10:56:30 +01001688 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1689 if (compl_match_array == NULL)
1690 return -1;
1691
1692 compl = match_head;
1693 i = 0;
1694 while (compl != NULL)
1695 {
glepnir6e199932024-12-14 21:13:27 +01001696 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1697 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001698 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1699 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1700 compl_match_array[i].pum_score = compl->cp_score;
Girish Palya19ef6b02025-05-28 20:28:21 +02001701 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001702 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1703 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001704 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1705 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001706 match_next = compl->cp_match_next;
1707 compl->cp_match_next = NULL;
1708 compl = match_next;
1709 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001710
zeertzjqd65aa1b2025-01-25 15:29:03 +01001711 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001712 {
1713 for (i = 0; i < compl_match_arraysize; i++)
1714 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001715 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001716 qsort(compl_match_array, (size_t)compl_match_arraysize,
1717 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001718 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001719 }
glepnira218cc62024-06-03 19:32:39 +02001720
Girish Palya6c40df02025-06-01 20:11:59 +02001721 if (fuzzy_sort && cpt_sources_array != NULL)
1722 cur = trim_compl_match_array(cur); // Truncate by max_matches in 'cpt'
Girish Palya19ef6b02025-05-28 20:28:21 +02001723
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001724 if (!shown_match_ok) // no displayed match at all
1725 cur = -1;
1726
1727 return cur;
1728}
1729
1730/*
1731 * Show the popup menu for the list of matches.
1732 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1733 */
1734 void
1735ins_compl_show_pum(void)
1736{
1737 int i;
1738 int cur = -1;
1739 colnr_T col;
1740
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001741 if (!pum_wanted() || !pum_enough_matches())
1742 return;
1743
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001744 // Update the screen later, before drawing the popup menu over it.
1745 pum_call_update_screen();
1746
1747 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001748 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001749 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001750 else
1751 {
1752 // popup menu already exists, only need to find the current item.
1753 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001754 {
John Marriott5e6ea922024-11-23 14:01:57 +01001755 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001756 || compl_match_array[i].pum_text
1757 == compl_shown_match->cp_text[CPT_ABBR])
1758 {
1759 cur = i;
1760 break;
1761 }
glepnir19e1dd62025-05-08 22:50:38 +02001762 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001763 }
1764
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001765 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001766 {
1767#ifdef FEAT_EVAL
1768 if (compl_started && has_completechanged())
1769 trigger_complete_changed_event(cur);
1770#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001771 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001772 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001773
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001774 // In Replace mode when a $ is displayed at the end of the line only
1775 // part of the screen would be updated. We do need to redraw here.
1776 dollar_vcol = -1;
1777
1778 // Compute the screen column of the start of the completed text.
1779 // Use the cursor to get all wrapping and other settings right.
1780 col = curwin->w_cursor.col;
1781 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001782 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001783 pum_display(compl_match_array, compl_match_arraysize, cur);
1784 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001785
glepnircbb46b42024-02-03 18:11:13 +01001786 // After adding leader, set the current match to shown match.
1787 if (compl_started && compl_curr_match != compl_shown_match)
1788 compl_curr_match = compl_shown_match;
1789
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001790#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001791 if (has_completechanged())
1792 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001793#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001794}
1795
1796#define DICT_FIRST (1) // use just first element in "dict"
1797#define DICT_EXACT (2) // "dict" is the exact name of a file
1798
1799/*
glepnir40c1c332024-06-11 19:37:04 +02001800 * Get current completion leader
1801 */
1802 char_u *
1803ins_compl_leader(void)
1804{
John Marriott5e6ea922024-11-23 14:01:57 +01001805 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1806}
1807
1808/*
1809 * Get current completion leader length
1810 */
1811 size_t
1812ins_compl_leader_len(void)
1813{
1814 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001815}
1816
1817/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001818 * Add any identifiers that match the given pattern "pat" in the list of
1819 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001820 */
1821 static void
1822ins_compl_dictionaries(
1823 char_u *dict_start,
1824 char_u *pat,
1825 int flags, // DICT_FIRST and/or DICT_EXACT
1826 int thesaurus) // Thesaurus completion
1827{
1828 char_u *dict = dict_start;
1829 char_u *ptr;
1830 char_u *buf;
1831 regmatch_T regmatch;
1832 char_u **files;
1833 int count;
1834 int save_p_scs;
1835 int dir = compl_direction;
1836
1837 if (*dict == NUL)
1838 {
1839#ifdef FEAT_SPELL
1840 // When 'dictionary' is empty and spell checking is enabled use
1841 // "spell".
1842 if (!thesaurus && curwin->w_p_spell)
1843 dict = (char_u *)"spell";
1844 else
1845#endif
1846 return;
1847 }
1848
1849 buf = alloc(LSIZE);
1850 if (buf == NULL)
1851 return;
1852 regmatch.regprog = NULL; // so that we can goto theend
1853
1854 // If 'infercase' is set, don't use 'smartcase' here
1855 save_p_scs = p_scs;
1856 if (curbuf->b_p_inf)
1857 p_scs = FALSE;
1858
1859 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1860 // to only match at the start of a line. Otherwise just match the
1861 // pattern. Also need to double backslashes.
1862 if (ctrl_x_mode_line_or_eval())
1863 {
1864 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001865
1866 if (pat_esc == NULL)
1867 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001868 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001869 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001870 if (ptr == NULL)
1871 {
1872 vim_free(pat_esc);
1873 goto theend;
1874 }
1875 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1876 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1877 vim_free(pat_esc);
1878 vim_free(ptr);
1879 }
1880 else
1881 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001882 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001883 if (regmatch.regprog == NULL)
1884 goto theend;
1885 }
1886
1887 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1888 regmatch.rm_ic = ignorecase(pat);
1889 while (*dict != NUL && !got_int && !compl_interrupted)
1890 {
1891 // copy one dictionary file name into buf
1892 if (flags == DICT_EXACT)
1893 {
1894 count = 1;
1895 files = &dict;
1896 }
1897 else
1898 {
1899 // Expand wildcards in the dictionary name, but do not allow
1900 // backticks (for security, the 'dict' option may have been set in
1901 // a modeline).
1902 copy_option_part(&dict, buf, LSIZE, ",");
1903# ifdef FEAT_SPELL
1904 if (!thesaurus && STRCMP(buf, "spell") == 0)
1905 count = -1;
1906 else
1907# endif
1908 if (vim_strchr(buf, '`') != NULL
1909 || expand_wildcards(1, &buf, &count, &files,
1910 EW_FILE|EW_SILENT) != OK)
1911 count = 0;
1912 }
1913
1914# ifdef FEAT_SPELL
1915 if (count == -1)
1916 {
1917 // Complete from active spelling. Skip "\<" in the pattern, we
1918 // don't use it as a RE.
1919 if (pat[0] == '\\' && pat[1] == '<')
1920 ptr = pat + 2;
1921 else
1922 ptr = pat;
1923 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1924 }
1925 else
1926# endif
1927 if (count > 0) // avoid warning for using "files" uninit
1928 {
1929 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001930 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001931 if (flags != DICT_EXACT)
1932 FreeWild(count, files);
1933 }
1934 if (flags != 0)
1935 break;
1936 }
1937
1938theend:
1939 p_scs = save_p_scs;
1940 vim_regfree(regmatch.regprog);
1941 vim_free(buf);
1942}
1943
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001944/*
1945 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1946 * skipping the word at 'skip_word'. Returns OK on success.
1947 */
1948 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001949thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001950 char_u *fname,
1951 char_u **buf_arg,
1952 int dir,
1953 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001954{
1955 int status = OK;
1956 char_u *ptr;
1957 char_u *wstart;
1958
1959 // Add the other matches on the line
1960 ptr = *buf_arg;
1961 while (!got_int)
1962 {
1963 // Find start of the next word. Skip white
1964 // space and punctuation.
1965 ptr = find_word_start(ptr);
1966 if (*ptr == NUL || *ptr == NL)
1967 break;
1968 wstart = ptr;
1969
1970 // Find end of the word.
1971 if (has_mbyte)
1972 // Japanese words may have characters in
1973 // different classes, only separate words
1974 // with single-byte non-word characters.
1975 while (*ptr != NUL)
1976 {
1977 int l = (*mb_ptr2len)(ptr);
1978
1979 if (l < 2 && !vim_iswordc(*ptr))
1980 break;
1981 ptr += l;
1982 }
1983 else
1984 ptr = find_word_end(ptr);
1985
1986 // Add the word. Skip the regexp match.
1987 if (wstart != skip_word)
1988 {
1989 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001990 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001991 if (status == FAIL)
1992 break;
1993 }
1994 }
1995
1996 *buf_arg = ptr;
1997 return status;
1998}
1999
2000/*
2001 * Process "count" dictionary/thesaurus "files" and add the text matching
2002 * "regmatch".
2003 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002004 static void
2005ins_compl_files(
2006 int count,
2007 char_u **files,
2008 int thesaurus,
2009 int flags,
2010 regmatch_T *regmatch,
2011 char_u *buf,
2012 int *dir)
2013{
2014 char_u *ptr;
2015 int i;
2016 FILE *fp;
2017 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01002018 char_u *leader = NULL;
2019 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01002020 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01002021 int score = 0;
2022 int len = 0;
2023 char_u *line_end = NULL;
2024
2025 if (in_fuzzy_collect)
2026 {
2027 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02002028 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01002029 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002030
2031 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
2032 {
2033 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01002034 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002035 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01002036 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002037 vim_snprintf((char *)IObuff, IOSIZE,
2038 _("Scanning dictionary: %s"), (char *)files[i]);
2039 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2040 }
2041
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002042 if (fp == NULL)
2043 continue;
2044
2045 // Read dictionary file line by line.
2046 // Check each line for a match.
2047 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002048 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002049 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01002050 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002051 {
glepnirf31cfa22025-03-06 21:59:13 +01002052 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002053 {
glepnirf31cfa22025-03-06 21:59:13 +01002054 ptr = regmatch->startp[0];
2055 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
2056 : find_word_end(ptr);
2057 add_r = ins_compl_add_infercase(regmatch->startp[0],
2058 (int)(ptr - regmatch->startp[0]),
2059 p_ic, files[i], *dir, FALSE, 0);
2060 if (thesaurus)
2061 {
2062 // For a thesaurus, add all the words in the line
2063 ptr = buf;
2064 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
2065 regmatch->startp[0]);
2066 }
2067 if (add_r == OK)
2068 // if dir was BACKWARD then honor it just once
2069 *dir = FORWARD;
2070 else if (add_r == FAIL)
2071 break;
2072 // avoid expensive call to vim_regexec() when at end
2073 // of line
2074 if (*ptr == '\n' || got_int)
2075 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002076 }
glepnirf31cfa22025-03-06 21:59:13 +01002077 }
2078 else if (in_fuzzy_collect && leader_len > 0)
2079 {
2080 line_end = find_line_end(ptr);
2081 while (ptr < line_end)
2082 {
2083 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
2084 {
2085 char_u *end_ptr = ctrl_x_mode_line_or_eval()
2086 ? find_line_end(ptr) : find_word_end(ptr);
2087 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2088 p_ic, files[i], *dir, FALSE, score);
2089 if (add_r == FAIL)
2090 break;
2091 ptr = end_ptr; // start from next word
2092 if (compl_get_longest && ctrl_x_mode_normal()
2093 && compl_first_match->cp_next
2094 && score == compl_first_match->cp_next->cp_score)
2095 compl_num_bests++;
2096 }
glepnirf31cfa22025-03-06 21:59:13 +01002097 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002099 line_breakcheck();
2100 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002101 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002102 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002103 }
2104}
2105
2106/*
2107 * Find the start of the next word.
2108 * Returns a pointer to the first char of the word. Also stops at a NUL.
2109 */
2110 char_u *
2111find_word_start(char_u *ptr)
2112{
2113 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002114 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002115 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2116 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002117 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002118 else
glepnir19e1dd62025-05-08 22:50:38 +02002119 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002120 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2121 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002122 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002123 return ptr;
2124}
2125
2126/*
2127 * Find the end of the word. Assumes it starts inside a word.
2128 * Returns a pointer to just after the word.
2129 */
2130 char_u *
2131find_word_end(char_u *ptr)
2132{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133 if (has_mbyte)
2134 {
glepnir19e1dd62025-05-08 22:50:38 +02002135 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002136 if (start_class > 1)
2137 while (*ptr != NUL)
2138 {
2139 ptr += (*mb_ptr2len)(ptr);
2140 if (mb_get_class(ptr) != start_class)
2141 break;
2142 }
2143 }
2144 else
2145 while (vim_iswordc(*ptr))
2146 ++ptr;
2147 return ptr;
2148}
2149
2150/*
2151 * Find the end of the line, omitting CR and NL at the end.
2152 * Returns a pointer to just after the line.
2153 */
glepnirdd42b052025-03-08 16:52:55 +01002154 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002155find_line_end(char_u *ptr)
2156{
glepnir19e1dd62025-05-08 22:50:38 +02002157 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002158 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2159 --s;
2160 return s;
2161}
2162
2163/*
Girish Palyacbe53192025-04-14 22:13:15 +02002164 * Free a completion item in the list
2165 */
2166 static void
2167ins_compl_item_free(compl_T *match)
2168{
Girish Palyacbe53192025-04-14 22:13:15 +02002169 VIM_CLEAR_STRING(match->cp_str);
2170 // several entries may use the same fname, free it just once.
2171 if (match->cp_flags & CP_FREE_FNAME)
2172 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002173 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002174 vim_free(match->cp_text[i]);
2175#ifdef FEAT_EVAL
2176 clear_tv(&match->cp_user_data);
2177#endif
2178 vim_free(match);
2179}
2180
2181/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002182 * Free the list of completions
2183 */
2184 static void
2185ins_compl_free(void)
2186{
2187 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002188
John Marriott5e6ea922024-11-23 14:01:57 +01002189 VIM_CLEAR_STRING(compl_pattern);
2190 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002191
2192 if (compl_first_match == NULL)
2193 return;
2194
2195 ins_compl_del_pum();
2196 pum_clear();
2197
2198 compl_curr_match = compl_first_match;
2199 do
2200 {
2201 match = compl_curr_match;
2202 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002203 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002204 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002205 compl_first_match = compl_curr_match = NULL;
2206 compl_shown_match = NULL;
2207 compl_old_match = NULL;
2208}
2209
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002210/*
2211 * Reset/clear the completion state.
2212 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002213 void
2214ins_compl_clear(void)
2215{
2216 compl_cont_status = 0;
2217 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002218 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002219 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002220 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002221 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002222 compl_curr_win = NULL;
2223 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002224 VIM_CLEAR_STRING(compl_pattern);
2225 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002226 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002227 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002228 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002229 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002230#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002231 // clear v:completed_item
2232 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002233#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002234}
2235
2236/*
2237 * Return TRUE when Insert completion is active.
2238 */
2239 int
2240ins_compl_active(void)
2241{
2242 return compl_started;
2243}
2244
2245/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002246 * Return True when wp is the actual completion window
2247 */
2248 int
glepnircf7f0122025-04-15 19:02:00 +02002249ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002250{
glepnircf7f0122025-04-15 19:02:00 +02002251 return ins_compl_active() && wp == compl_curr_win
2252 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002253}
2254
2255/*
Girish Palyacbe53192025-04-14 22:13:15 +02002256 * Selected one of the matches. When FALSE, the match was either edited or
2257 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002258 */
2259 int
2260ins_compl_used_match(void)
2261{
2262 return compl_used_match;
2263}
2264
2265/*
2266 * Initialize get longest common string.
2267 */
2268 void
2269ins_compl_init_get_longest(void)
2270{
2271 compl_get_longest = FALSE;
2272}
2273
2274/*
2275 * Returns TRUE when insert completion is interrupted.
2276 */
2277 int
2278ins_compl_interrupted(void)
2279{
2280 return compl_interrupted;
2281}
2282
2283/*
2284 * Returns TRUE if the <Enter> key selects a match in the completion popup
2285 * menu.
2286 */
2287 int
2288ins_compl_enter_selects(void)
2289{
2290 return compl_enter_selects;
2291}
2292
2293/*
2294 * Return the column where the text starts that is being completed
2295 */
2296 colnr_T
2297ins_compl_col(void)
2298{
2299 return compl_col;
2300}
2301
2302/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002303 * Return the length in bytes of the text being completed
2304 */
2305 int
2306ins_compl_len(void)
2307{
2308 return compl_length;
2309}
2310
2311/*
glepnir94a045e2025-03-01 16:12:23 +01002312 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2313 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002314 */
2315 static int
2316ins_compl_has_preinsert(void)
2317{
glepnira2c55592025-02-28 17:43:42 +01002318 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002319 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2320 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002321}
2322
2323/*
2324 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2325 * the `compl_ins_end_col` range.
2326 */
2327 int
2328ins_compl_preinsert_effect(void)
2329{
2330 if (!ins_compl_has_preinsert())
2331 return FALSE;
2332
2333 return curwin->w_cursor.col < compl_ins_end_col;
2334}
2335
2336/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002337 * Delete one character before the cursor and show the subset of the matches
2338 * that match the word that is now before the cursor.
2339 * Returns the character to be used, NUL if the work is done and another char
2340 * to be got from the user.
2341 */
2342 int
2343ins_compl_bs(void)
2344{
2345 char_u *line;
2346 char_u *p;
2347
glepniredd4ac32025-01-29 18:53:51 +01002348 if (ins_compl_preinsert_effect())
2349 ins_compl_delete();
2350
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002351 line = ml_get_curline();
2352 p = line + curwin->w_cursor.col;
2353 MB_PTR_BACK(line, p);
2354
2355 // Stop completion when the whole word was deleted. For Omni completion
2356 // allow the word to be deleted, we won't match everything.
2357 // Respect the 'backspace' option.
2358 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002359 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2360 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002361 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2362 - compl_length < 0))
2363 return K_BS;
2364
2365 // Deleted more than what was used to find matches or didn't finish
2366 // finding all matches: need to look for matches all over again.
2367 if (curwin->w_cursor.col <= compl_col + compl_length
2368 || ins_compl_need_restart())
2369 ins_compl_restart();
2370
John Marriott5e6ea922024-11-23 14:01:57 +01002371 VIM_CLEAR_STRING(compl_leader);
2372 compl_leader.length = (size_t)((p - line) - compl_col);
2373 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2374 if (compl_leader.string == NULL)
2375 {
2376 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002377 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002378 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002379
2380 ins_compl_new_leader();
2381 if (compl_shown_match != NULL)
2382 // Make sure current match is not a hidden item.
2383 compl_curr_match = compl_shown_match;
2384 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002385}
2386
2387/*
2388 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2389 * be called.
2390 */
2391 static int
2392ins_compl_need_restart(void)
2393{
2394 // Return TRUE if we didn't complete finding matches or when the
2395 // 'completefunc' returned "always" in the "refresh" dictionary item.
2396 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002397 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002398 && compl_opt_refresh_always);
2399}
2400
2401/*
2402 * Called after changing "compl_leader".
2403 * Show the popup menu with a different set of matches.
2404 * May also search for matches again if the previous search was interrupted.
2405 */
2406 static void
2407ins_compl_new_leader(void)
2408{
2409 ins_compl_del_pum();
2410 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002411 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002412 compl_used_match = FALSE;
2413
2414 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002415 {
John Marriott5e6ea922024-11-23 14:01:57 +01002416 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002417 if (is_cpt_func_refresh_always())
2418 cpt_compl_refresh();
2419 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002420 else
2421 {
2422#ifdef FEAT_SPELL
2423 spell_bad_len = 0; // need to redetect bad word
2424#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002425 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002426 // the popup menu display the changed text before the cursor. Set
2427 // "compl_restarting" to avoid that the first match is inserted.
2428 pum_call_update_screen();
2429#ifdef FEAT_GUI
2430 if (gui.in_use)
2431 {
2432 // Show the cursor after the match, not after the redrawn text.
2433 setcursor();
2434 out_flush_cursor(FALSE, FALSE);
2435 }
2436#endif
2437 compl_restarting = TRUE;
2438 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2439 compl_cont_status = 0;
2440 compl_restarting = FALSE;
2441 }
2442
glepnir44180412025-02-20 22:09:48 +01002443 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002444
2445 // Show the popup menu with a different set of matches.
2446 ins_compl_show_pum();
2447
2448 // Don't let Enter select the original text when there is no popup menu.
2449 if (compl_match_array == NULL)
2450 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002451 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2452 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002453}
2454
2455/*
2456 * Return the length of the completion, from the completion start column to
2457 * the cursor column. Making sure it never goes below zero.
2458 */
2459 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002460get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002461{
2462 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002463 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002464}
2465
2466/*
2467 * Append one character to the match leader. May reduce the number of
2468 * matches.
2469 */
2470 void
2471ins_compl_addleader(int c)
2472{
glepnir19e1dd62025-05-08 22:50:38 +02002473 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002474
glepniredd4ac32025-01-29 18:53:51 +01002475 if (ins_compl_preinsert_effect())
2476 ins_compl_delete();
2477
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002478 if (stop_arrow() == FAIL)
2479 return;
2480 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2481 {
2482 char_u buf[MB_MAXBYTES + 1];
2483
2484 (*mb_char2bytes)(c, buf);
2485 buf[cc] = NUL;
2486 ins_char_bytes(buf, cc);
2487 if (compl_opt_refresh_always)
2488 AppendToRedobuff(buf);
2489 }
2490 else
2491 {
2492 ins_char(c);
2493 if (compl_opt_refresh_always)
2494 AppendCharToRedobuff(c);
2495 }
2496
2497 // If we didn't complete finding matches we must search again.
2498 if (ins_compl_need_restart())
2499 ins_compl_restart();
2500
2501 // When 'always' is set, don't reset compl_leader. While completing,
2502 // cursor doesn't point original position, changing compl_leader would
2503 // break redo.
2504 if (!compl_opt_refresh_always)
2505 {
John Marriott5e6ea922024-11-23 14:01:57 +01002506 VIM_CLEAR_STRING(compl_leader);
2507 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2508 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2509 compl_leader.length);
2510 if (compl_leader.string == NULL)
2511 {
2512 compl_leader.length = 0;
2513 return;
2514 }
2515
2516 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002517 }
2518}
2519
2520/*
2521 * Setup for finding completions again without leaving CTRL-X mode. Used when
2522 * BS or a key was typed while still searching for matches.
2523 */
2524 static void
2525ins_compl_restart(void)
2526{
2527 ins_compl_free();
2528 compl_started = FALSE;
2529 compl_matches = 0;
2530 compl_cont_status = 0;
2531 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002532 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002533}
2534
2535/*
2536 * Set the first match, the original text.
2537 */
2538 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002539ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002540{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002541 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002542 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2543 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002544 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002545 {
John Marriott5e6ea922024-11-23 14:01:57 +01002546 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002547 if (p != NULL)
2548 {
John Marriott5e6ea922024-11-23 14:01:57 +01002549 VIM_CLEAR_STRING(compl_first_match->cp_str);
2550 compl_first_match->cp_str.string = p;
2551 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002552 }
2553 }
2554 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002555 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002556 {
John Marriott5e6ea922024-11-23 14:01:57 +01002557 char_u *p = vim_strnsave(str, len);
2558 if (p != NULL)
2559 {
2560 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2561 compl_first_match->cp_prev->cp_str.string = p;
2562 compl_first_match->cp_prev->cp_str.length = len;
2563 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002564 }
2565}
2566
2567/*
2568 * Append one character to the match leader. May reduce the number of
2569 * matches.
2570 */
2571 void
2572ins_compl_addfrommatch(void)
2573{
2574 char_u *p;
2575 int len = (int)curwin->w_cursor.col - (int)compl_col;
2576 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002577
John Marriott5e6ea922024-11-23 14:01:57 +01002578 p = compl_shown_match->cp_str.string;
2579 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002580 {
John Marriott5e6ea922024-11-23 14:01:57 +01002581 size_t plen;
2582 compl_T *cp;
2583
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002584 // When still at the original match use the first entry that matches
2585 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002586 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002587 return;
2588
2589 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002590 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002591 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002592 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002593 {
John Marriott5e6ea922024-11-23 14:01:57 +01002594 if (compl_leader.string == NULL
2595 || ins_compl_equal(cp, compl_leader.string,
2596 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002597 {
John Marriott5e6ea922024-11-23 14:01:57 +01002598 p = cp->cp_str.string;
2599 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002600 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002601 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002602 }
John Marriott5e6ea922024-11-23 14:01:57 +01002603 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002604 return;
2605 }
2606 p += len;
2607 c = PTR2CHAR(p);
2608 ins_compl_addleader(c);
2609}
2610
2611/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002612 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002613 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2614 * compl_cont_mode and compl_cont_status.
2615 * Returns TRUE when the character is not to be inserted.
2616 */
2617 static int
2618set_ctrl_x_mode(int c)
2619{
glepnir05460682025-05-26 18:23:27 +02002620 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002621
2622 switch (c)
2623 {
2624 case Ctrl_E:
2625 case Ctrl_Y:
2626 // scroll the window one line up or down
2627 ctrl_x_mode = CTRL_X_SCROLL;
2628 if (!(State & REPLACE_FLAG))
2629 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2630 else
2631 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2632 edit_submode_pre = NULL;
2633 showmode();
2634 break;
2635 case Ctrl_L:
2636 // complete whole line
2637 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2638 break;
2639 case Ctrl_F:
2640 // complete filenames
2641 ctrl_x_mode = CTRL_X_FILES;
2642 break;
2643 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002644 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002645 ctrl_x_mode = CTRL_X_DICTIONARY;
2646 break;
2647 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002648 // When CTRL-R is followed by '=', don't trigger register completion
2649 // This allows expressions like <C-R>=func()<CR> to work normally
2650 if (vpeekc() == '=')
2651 break;
2652 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002653 break;
2654 case Ctrl_T:
2655 // complete words from a thesaurus
2656 ctrl_x_mode = CTRL_X_THESAURUS;
2657 break;
2658#ifdef FEAT_COMPL_FUNC
2659 case Ctrl_U:
2660 // user defined completion
2661 ctrl_x_mode = CTRL_X_FUNCTION;
2662 break;
2663 case Ctrl_O:
2664 // omni completion
2665 ctrl_x_mode = CTRL_X_OMNI;
2666 break;
2667#endif
2668 case 's':
2669 case Ctrl_S:
2670 // complete spelling suggestions
2671 ctrl_x_mode = CTRL_X_SPELL;
2672#ifdef FEAT_SPELL
2673 ++emsg_off; // Avoid getting the E756 error twice.
2674 spell_back_to_badword();
2675 --emsg_off;
2676#endif
2677 break;
2678 case Ctrl_RSB:
2679 // complete tag names
2680 ctrl_x_mode = CTRL_X_TAGS;
2681 break;
2682#ifdef FEAT_FIND_ID
2683 case Ctrl_I:
2684 case K_S_TAB:
2685 // complete keywords from included files
2686 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2687 break;
2688 case Ctrl_D:
2689 // complete definitions from included files
2690 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2691 break;
2692#endif
2693 case Ctrl_V:
2694 case Ctrl_Q:
2695 // complete vim commands
2696 ctrl_x_mode = CTRL_X_CMDLINE;
2697 break;
2698 case Ctrl_Z:
2699 // stop completion
2700 ctrl_x_mode = CTRL_X_NORMAL;
2701 edit_submode = NULL;
2702 showmode();
2703 retval = TRUE;
2704 break;
2705 case Ctrl_P:
2706 case Ctrl_N:
2707 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2708 // just started ^X mode, or there were enough ^X's to cancel
2709 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2710 // do normal expansion when interrupting a different mode (say
2711 // ^X^F^X^P or ^P^X^X^P, see below)
2712 // nothing changes if interrupting mode 0, (eg, the flag
2713 // doesn't change when going to ADDING mode -- Acevedo
2714 if (!(compl_cont_status & CONT_INTRPT))
2715 compl_cont_status |= CONT_LOCAL;
2716 else if (compl_cont_mode != 0)
2717 compl_cont_status &= ~CONT_LOCAL;
2718 // FALLTHROUGH
2719 default:
2720 // If we have typed at least 2 ^X's... for modes != 0, we set
2721 // compl_cont_status = 0 (eg, as if we had just started ^X
2722 // mode).
2723 // For mode 0, we set "compl_cont_mode" to an impossible
2724 // value, in both cases ^X^X can be used to restart the same
2725 // mode (avoiding ADDING mode).
2726 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2727 // 'complete' and local ^P expansions respectively.
2728 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2729 // mode -- Acevedo
2730 if (c == Ctrl_X)
2731 {
2732 if (compl_cont_mode != 0)
2733 compl_cont_status = 0;
2734 else
2735 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2736 }
2737 ctrl_x_mode = CTRL_X_NORMAL;
2738 edit_submode = NULL;
2739 showmode();
2740 break;
2741 }
2742
2743 return retval;
2744}
2745
2746/*
glepnir1c5a1202024-12-04 20:27:34 +01002747 * Trigger CompleteDone event and adds relevant information to v:event
2748 */
2749 static void
2750trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2751{
2752#if defined(FEAT_EVAL)
2753 save_v_event_T save_v_event;
2754 dict_T *v_event = get_v_event(&save_v_event);
2755 char_u *mode_str = NULL;
2756
2757 mode = mode & ~CTRL_X_WANT_IDENT;
2758 if (ctrl_x_mode_names[mode])
2759 mode_str = (char_u *)ctrl_x_mode_names[mode];
2760
2761 (void)dict_add_string(v_event, "complete_word",
2762 word == NULL ? (char_u *)"" : word);
2763 (void)dict_add_string(v_event, "complete_type",
2764 mode_str != NULL ? mode_str : (char_u *)"");
2765
2766 dict_set_items_ro(v_event);
2767#endif
2768 ins_apply_autocmds(EVENT_COMPLETEDONE);
2769
2770#if defined(FEAT_EVAL)
2771 restore_v_event(v_event, &save_v_event);
2772#endif
2773}
2774
2775/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002776 * Stop insert completion mode
2777 */
2778 static int
2779ins_compl_stop(int c, int prev_mode, int retval)
2780{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002781 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002782 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002783
glepnir84a75032025-03-15 09:59:22 +01002784 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002785 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002786 ins_compl_delete();
2787
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002788 // Get here when we have finished typing a sequence of ^N and
2789 // ^P or other completion characters in CTRL-X mode. Free up
2790 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002791 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002792 {
glepnir40891ba2025-02-10 22:18:00 +01002793 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002794
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002795 // If any of the original typed text has been changed, eg when
2796 // ignorecase is set, we must add back-spaces to the redo
2797 // buffer. We add as few as necessary to delete just the part
2798 // of the original text that has changed.
2799 // When using the longest match, edited the match or used
2800 // CTRL-E then don't use the current match.
2801 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002802 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002803 ins_compl_fixRedoBufForLeader(ptr);
2804 }
2805
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002806 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002807
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002808 // When completing whole lines: fix indent for 'cindent'.
2809 // Otherwise, break line if it's too long.
2810 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2811 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002812 // re-indent the current line
2813 if (want_cindent)
2814 {
2815 do_c_expr_indent();
2816 want_cindent = FALSE; // don't do it again
2817 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002818 }
2819 else
2820 {
2821 int prev_col = curwin->w_cursor.col;
2822
2823 // put the cursor on the last char, for 'tw' formatting
2824 if (prev_col > 0)
2825 dec_cursor();
2826 // only format when something was inserted
2827 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2828 insertchar(NUL, 0, -1);
2829 if (prev_col > 0
2830 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2831 inc_cursor();
2832 }
2833
2834 // If the popup menu is displayed pressing CTRL-Y means accepting
2835 // the selection without inserting anything. When
2836 // compl_enter_selects is set the Enter key does the same.
2837 if ((c == Ctrl_Y || (compl_enter_selects
2838 && (c == CAR || c == K_KENTER || c == NL)))
2839 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002840 {
2841 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002842 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002843 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002844
2845 // CTRL-E means completion is Ended, go back to the typed text.
2846 // but only do this, if the Popup is still visible
2847 if (c == Ctrl_E)
2848 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002849 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002850 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002851
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002852 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002853 if (compl_leader.string != NULL)
2854 {
2855 p = compl_leader.string;
2856 plen = compl_leader.length;
2857 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002858 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002859 {
2860 p = compl_orig_text.string;
2861 plen = compl_orig_text.length;
2862 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002863 if (p != NULL)
2864 {
2865 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002866
John Marriott5e6ea922024-11-23 14:01:57 +01002867 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002868 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002869 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002870 retval = TRUE;
2871 }
2872
2873 auto_format(FALSE, TRUE);
2874
2875 // Trigger the CompleteDonePre event to give scripts a chance to
2876 // act upon the completion before clearing the info, and restore
2877 // ctrl_x_mode, so that complete_info() can be used.
2878 ctrl_x_mode = prev_mode;
2879 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2880
2881 ins_compl_free();
2882 compl_started = FALSE;
2883 compl_matches = 0;
2884 if (!shortmess(SHM_COMPLETIONMENU))
2885 msg_clr_cmdline(); // necessary for "noshowmode"
2886 ctrl_x_mode = CTRL_X_NORMAL;
2887 compl_enter_selects = FALSE;
2888 if (edit_submode != NULL)
2889 {
2890 edit_submode = NULL;
2891 showmode();
2892 }
2893
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002894 if (c == Ctrl_C && cmdwin_type != 0)
2895 // Avoid the popup menu remains displayed when leaving the
2896 // command line window.
2897 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002898 // Indent now if a key was typed that is in 'cinkeys'.
2899 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2900 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002901 // Trigger the CompleteDone event to give scripts a chance to act
2902 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002903 trigger_complete_done_event(prev_mode, word);
2904 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002905
2906 return retval;
2907}
2908
2909/*
glepnircf7f0122025-04-15 19:02:00 +02002910 * Cancel completion.
2911 */
2912 int
2913ins_compl_cancel(void)
2914{
2915 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2916}
2917
2918/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002919 * Prepare for Insert mode completion, or stop it.
2920 * Called just after typing a character in Insert mode.
2921 * Returns TRUE when the character is not to be inserted;
2922 */
2923 int
2924ins_compl_prep(int c)
2925{
glepnir19e1dd62025-05-08 22:50:38 +02002926 int retval = FALSE;
2927 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002928
2929 // Forget any previous 'special' messages if this is actually
2930 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2931 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2932 edit_submode_extra = NULL;
2933
zeertzjq440d4cb2023-03-02 17:51:32 +00002934 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002935 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002936 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002937 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002938 return retval;
2939
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002940#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002941 // Ignore mouse events in a popup window
2942 if (is_mouse_key(c))
2943 {
2944 // Ignore drag and release events, the position does not need to be in
2945 // the popup and it may have just closed.
2946 if (c == K_LEFTRELEASE
2947 || c == K_LEFTRELEASE_NM
2948 || c == K_MIDDLERELEASE
2949 || c == K_RIGHTRELEASE
2950 || c == K_X1RELEASE
2951 || c == K_X2RELEASE
2952 || c == K_LEFTDRAG
2953 || c == K_MIDDLEDRAG
2954 || c == K_RIGHTDRAG
2955 || c == K_X1DRAG
2956 || c == K_X2DRAG)
2957 return retval;
2958 if (popup_visible)
2959 {
2960 int row = mouse_row;
2961 int col = mouse_col;
2962 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2963
2964 if (wp != NULL && WIN_IS_POPUP(wp))
2965 return retval;
2966 }
2967 }
2968#endif
2969
zeertzjqdca29d92021-08-31 19:12:51 +02002970 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2971 {
2972 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2973 || !vim_is_ctrl_x_key(c))
2974 {
2975 // Not starting another completion mode.
2976 ctrl_x_mode = CTRL_X_CMDLINE;
2977
2978 // CTRL-X CTRL-Z should stop completion without inserting anything
2979 if (c == Ctrl_Z)
2980 retval = TRUE;
2981 }
2982 else
2983 {
2984 ctrl_x_mode = CTRL_X_CMDLINE;
2985
2986 // Other CTRL-X keys first stop completion, then start another
2987 // completion mode.
2988 ins_compl_prep(' ');
2989 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2990 }
2991 }
2992
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002993 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002994 if (ctrl_x_mode_not_defined_yet()
2995 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002996 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002997 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002998 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002999 }
3000
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003001 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003002 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3003 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003004 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003005 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003006 {
3007 // We're already in CTRL-X mode, do we stay in it?
3008 if (!vim_is_ctrl_x_key(c))
3009 {
glepnir40891ba2025-02-10 22:18:00 +01003010 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003011 edit_submode = NULL;
3012 }
3013 showmode();
3014 }
3015
3016 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3017 {
3018 // Show error message from attempted keyword completion (probably
3019 // 'Pattern not found') until another key is hit, then go back to
3020 // showing what mode we are in.
3021 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003022 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003023 && c != Ctrl_R && !ins_compl_pum_key(c))
3024 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003025 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003026 }
3027 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
3028 // Trigger the CompleteDone event to give scripts a chance to act
3029 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01003030 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003031
LemonBoy2bf52dd2022-04-09 18:17:34 +01003032 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003033
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003034 // reset continue_* if we left expansion-mode, if we stay they'll be
3035 // (re)set properly in ins_complete()
3036 if (!vim_is_ctrl_x_key(c))
3037 {
3038 compl_cont_status = 0;
3039 compl_cont_mode = 0;
3040 }
3041
3042 return retval;
3043}
3044
3045/*
3046 * Fix the redo buffer for the completion leader replacing some of the typed
3047 * text. This inserts backspaces and appends the changed text.
3048 * "ptr" is the known leader text or NUL.
3049 */
3050 static void
3051ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
3052{
John Marriott5e6ea922024-11-23 14:01:57 +01003053 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003054 char_u *p;
3055 char_u *ptr = ptr_arg;
3056
3057 if (ptr == NULL)
3058 {
John Marriott5e6ea922024-11-23 14:01:57 +01003059 if (compl_leader.string != NULL)
3060 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003061 else
3062 return; // nothing to do
3063 }
John Marriott5e6ea922024-11-23 14:01:57 +01003064 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003065 {
John Marriott5e6ea922024-11-23 14:01:57 +01003066 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01003067 // Find length of common prefix between original text and new completion
3068 while (p[len] != NUL && p[len] == ptr[len])
3069 len++;
3070 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003071 if (len > 0)
3072 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01003073 // Add backspace characters for each remaining character in
3074 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003075 for (p += len; *p != NUL; MB_PTR_ADV(p))
3076 AppendCharToRedobuff(K_BS);
3077 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003078 if (ptr != NULL)
3079 AppendToRedobuffLit(ptr + len, -1);
3080}
3081
3082/*
3083 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3084 * (depending on flag) starting from buf and looking for a non-scanned
3085 * buffer (other than curbuf). curbuf is special, if it is called with
3086 * buf=curbuf then it has to be the first call for a given flag/expansion.
3087 *
3088 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3089 */
3090 static buf_T *
3091ins_compl_next_buf(buf_T *buf, int flag)
3092{
glepnir19e1dd62025-05-08 22:50:38 +02003093 static win_T *wp = NULL;
3094 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003095
3096 if (flag == 'w') // just windows
3097 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003098 if (buf == curbuf || !win_valid(wp))
3099 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003100 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003101
3102 while (TRUE)
3103 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003104 // Move to next window (wrap to first window if at the end)
3105 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3106 // Break if we're back at start or found an unscanned buffer
3107 if (wp == curwin || !wp->w_buffer->b_scanned)
3108 break;
glepnir40891ba2025-02-10 22:18:00 +01003109 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003110 buf = wp->w_buffer;
3111 }
3112 else
glepnir40891ba2025-02-10 22:18:00 +01003113 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003114 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3115 // (unlisted buffers)
3116 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003117 while (TRUE)
3118 {
3119 // Move to next buffer (wrap to first buffer if at the end)
3120 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3121 // Break if we're back at start buffer
3122 if (buf == curbuf)
3123 break;
3124
3125 // Check buffer conditions based on flag
3126 if (flag == 'U')
3127 skip_buffer = buf->b_p_bl;
3128 else
3129 skip_buffer = !buf->b_p_bl ||
3130 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3131
3132 // Break if we found a buffer that matches our criteria
3133 if (!skip_buffer && !buf->b_scanned)
3134 break;
3135 }
3136 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003137 return buf;
3138}
3139
3140#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003141
3142# ifdef FEAT_EVAL
3143static callback_T cfu_cb; // 'completefunc' callback function
3144static callback_T ofu_cb; // 'omnifunc' callback function
3145static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3146# endif
3147
3148/*
3149 * Copy a global callback function to a buffer local callback.
3150 */
3151 static void
3152copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3153{
3154 free_callback(bufcb);
3155 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3156 copy_callback(bufcb, globcb);
3157}
3158
3159/*
3160 * Parse the 'completefunc' option value and set the callback function.
3161 * Invoked when the 'completefunc' option is set. The option value can be a
3162 * name of a function (string), or function(<name>) or funcref(<name>) or a
3163 * lambda expression.
3164 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003165 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003166did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003167{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003168 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3169 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003170
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003171 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003172
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003173 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003174}
3175
3176/*
3177 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003178 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003179 */
3180 void
3181set_buflocal_cfu_callback(buf_T *buf UNUSED)
3182{
3183# ifdef FEAT_EVAL
3184 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3185# endif
3186}
3187
3188/*
3189 * Parse the 'omnifunc' option value and set the callback function.
3190 * Invoked when the 'omnifunc' option is set. The option value can be a
3191 * name of a function (string), or function(<name>) or funcref(<name>) or a
3192 * lambda expression.
3193 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003194 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003195did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003196{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003197 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3198 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003199
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003200 set_buflocal_ofu_callback(curbuf);
3201 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003202}
3203
3204/*
3205 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003206 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003207 */
3208 void
3209set_buflocal_ofu_callback(buf_T *buf UNUSED)
3210{
3211# ifdef FEAT_EVAL
3212 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3213# endif
3214}
3215
3216/*
3217 * Parse the 'thesaurusfunc' option value and set the callback function.
3218 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3219 * name of a function (string), or function(<name>) or funcref(<name>) or a
3220 * lambda expression.
3221 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003222 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003223did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003224{
3225 int retval;
3226
zeertzjq6eda2692024-11-03 09:23:33 +01003227 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003228 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003229 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3230 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003231 else
3232 {
3233 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003234 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003235 // when using :set, free the local callback
3236 if (!(args->os_flags & OPT_GLOBAL))
3237 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003238 }
3239
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003240 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003241}
3242
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003243/*
3244 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003245 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003246 */
3247 int
3248set_ref_in_insexpand_funcs(int copyID)
3249{
glepnir19e1dd62025-05-08 22:50:38 +02003250 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003251 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3252 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3253
3254 return abort;
3255}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003256
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003257/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003258 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003259 */
3260 static char_u *
3261get_complete_funcname(int type)
3262{
3263 switch (type)
3264 {
3265 case CTRL_X_FUNCTION:
3266 return curbuf->b_p_cfu;
3267 case CTRL_X_OMNI:
3268 return curbuf->b_p_ofu;
3269 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003270 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003271 default:
3272 return (char_u *)"";
3273 }
3274}
3275
3276/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003277 * Get the callback to use for insert mode completion.
3278 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003279 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003280get_insert_callback(int type)
3281{
3282 if (type == CTRL_X_FUNCTION)
3283 return &curbuf->b_cfu_cb;
3284 if (type == CTRL_X_OMNI)
3285 return &curbuf->b_ofu_cb;
3286 // CTRL_X_THESAURUS
3287 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3288}
3289
3290/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003291 * Execute user defined complete function 'completefunc', 'omnifunc' or
3292 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003293 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3294 * Callback function "cb" is set if triggered by a function in the 'cpt'
3295 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003296 */
3297 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003298expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003299{
3300 list_T *matchlist = NULL;
3301 dict_T *matchdict = NULL;
3302 typval_T args[3];
3303 char_u *funcname;
3304 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003305 typval_T rettv;
3306 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003307 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003308 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003309
Girish Palyacbe53192025-04-14 22:13:15 +02003310 if (!is_cpt_function)
3311 {
3312 funcname = get_complete_funcname(type);
3313 if (*funcname == NUL)
3314 return;
3315 cb = get_insert_callback(type);
3316 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003317
3318 // Call 'completefunc' to obtain the list of matches.
3319 args[0].v_type = VAR_NUMBER;
3320 args[0].vval.v_number = 0;
3321 args[1].v_type = VAR_STRING;
3322 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3323 args[2].v_type = VAR_UNKNOWN;
3324
3325 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003326 // Lock the text to avoid weird things from happening. Also disallow
3327 // switching to another window, it should not be needed and may end up in
3328 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003329 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003330
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003331 retval = call_callback(cb, 0, &rettv, 2, args);
3332
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003333 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003334 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003335 {
3336 switch (rettv.v_type)
3337 {
3338 case VAR_LIST:
3339 matchlist = rettv.vval.v_list;
3340 break;
3341 case VAR_DICT:
3342 matchdict = rettv.vval.v_dict;
3343 break;
3344 case VAR_SPECIAL:
3345 if (rettv.vval.v_number == VVAL_NONE)
3346 compl_opt_suppress_empty = TRUE;
3347 // FALLTHROUGH
3348 default:
3349 // TODO: Give error message?
3350 clear_tv(&rettv);
3351 break;
3352 }
3353 }
zeertzjqcfe45652022-05-27 17:26:55 +01003354 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003355
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003356 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003357 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003358 validate_cursor();
3359 if (!EQUAL_POS(curwin->w_cursor, pos))
3360 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003361 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003362 goto theend;
3363 }
3364
3365 if (matchlist != NULL)
3366 ins_compl_add_list(matchlist);
3367 else if (matchdict != NULL)
3368 ins_compl_add_dict(matchdict);
3369
3370theend:
3371 // Restore State, it might have been changed.
3372 State = save_State;
3373
3374 if (matchdict != NULL)
3375 dict_unref(matchdict);
3376 if (matchlist != NULL)
3377 list_unref(matchlist);
3378}
3379#endif // FEAT_COMPL_FUNC
3380
3381#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003382
3383 static inline int
3384get_user_highlight_attr(char_u *hlname)
3385{
3386 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003387 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003388 return -1;
3389}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003390/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003391 * Add a match to the list of matches from a typeval_T.
3392 * If the given string is already in the list of completions, then return
3393 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3394 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003395 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003396 */
3397 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003398ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003399{
3400 char_u *word;
3401 int dup = FALSE;
3402 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003403 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003404 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003405 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003406 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003407 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003408 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003409 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003410
Bram Moolenaar08928322020-01-04 14:32:48 +01003411 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003412 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3413 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003414 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3415 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3416 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3417 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3418 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003419
glepnir0fe17f82024-10-08 22:26:44 +02003420 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003421 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003422
3423 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003424 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003425
Bram Moolenaard61efa52022-07-23 09:52:04 +01003426 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3427 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3428 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003429 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003430 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3431 dup = dict_get_number(tv->vval.v_dict, "dup");
3432 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3433 empty = dict_get_number(tv->vval.v_dict, "empty");
3434 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3435 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003436 flags |= CP_EQUAL;
3437 }
3438 else
3439 {
3440 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003441 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003442 }
3443 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003444 {
3445 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003446 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003447 }
glepnir508e7852024-07-25 21:39:08 +02003448 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003449 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003450 if (status != OK)
3451 clear_tv(&user_data);
3452 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003453}
3454
3455/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003456 * Add completions from a list.
3457 */
3458 static void
3459ins_compl_add_list(list_T *list)
3460{
3461 listitem_T *li;
3462 int dir = compl_direction;
3463
3464 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003465 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003466 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003467 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003468 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003469 // if dir was BACKWARD then honor it just once
3470 dir = FORWARD;
3471 else if (did_emsg)
3472 break;
3473 }
3474}
3475
3476/*
3477 * Add completions from a dict.
3478 */
3479 static void
3480ins_compl_add_dict(dict_T *dict)
3481{
3482 dictitem_T *di_refresh;
3483 dictitem_T *di_words;
3484
3485 // Check for optional "refresh" item.
3486 compl_opt_refresh_always = FALSE;
3487 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3488 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3489 {
3490 char_u *v = di_refresh->di_tv.vval.v_string;
3491
3492 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3493 compl_opt_refresh_always = TRUE;
3494 }
3495
3496 // Add completions from a "words" list.
3497 di_words = dict_find(dict, (char_u *)"words", 5);
3498 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3499 ins_compl_add_list(di_words->di_tv.vval.v_list);
3500}
3501
3502/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003503 * Start completion for the complete() function.
3504 * "startcol" is where the matched text starts (1 is first column).
3505 * "list" is the list of matches.
3506 */
3507 static void
3508set_completion(colnr_T startcol, list_T *list)
3509{
3510 int save_w_wrow = curwin->w_wrow;
3511 int save_w_leftcol = curwin->w_leftcol;
3512 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003513 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003514 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3515 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3516 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003517
3518 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003519 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003520 ins_compl_prep(' ');
3521 ins_compl_clear();
3522 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003523 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003524
3525 compl_direction = FORWARD;
3526 if (startcol > curwin->w_cursor.col)
3527 startcol = curwin->w_cursor.col;
3528 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003529 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003530 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3531 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003532 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3533 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003534 if (p_ic)
3535 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003536 if (compl_orig_text.string == NULL)
3537 {
3538 compl_orig_text.length = 0;
3539 return;
3540 }
3541 compl_orig_text.length = (size_t)compl_length;
3542 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003543 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3544 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003545 return;
3546
3547 ctrl_x_mode = CTRL_X_EVAL;
3548
3549 ins_compl_add_list(list);
3550 compl_matches = ins_compl_make_cyclic();
3551 compl_started = TRUE;
3552 compl_used_match = TRUE;
3553 compl_cont_status = 0;
3554
3555 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003556 int no_select = compl_no_select || compl_longest;
3557 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003558 {
3559 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003560 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003561 // Down/Up has no real effect.
3562 ins_complete(K_UP, FALSE);
3563 }
3564 else
3565 ins_complete(Ctrl_N, FALSE);
3566 compl_enter_selects = compl_no_insert;
3567
3568 // Lazily show the popup menu, unless we got interrupted.
3569 if (!compl_interrupted)
3570 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003571 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003572 out_flush();
3573}
3574
3575/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003576 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003577 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003578 void
3579f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003580{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003581 if (in_vim9script()
3582 && (check_for_number_arg(argvars, 0) == FAIL
3583 || check_for_list_arg(argvars, 1) == FAIL))
3584 return;
3585
Bram Moolenaar24959102022-05-07 20:01:16 +01003586 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003587 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003588 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003589 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003590 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003591
3592 // Check for undo allowed here, because if something was already inserted
3593 // the line was already saved for undo and this check isn't done.
3594 if (!undo_allowed())
3595 return;
3596
Bram Moolenaard83392a2022-09-01 12:22:46 +01003597 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003598 {
glepnir19e1dd62025-05-08 22:50:38 +02003599 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003600 if (startcol > 0)
3601 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003602 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003603}
3604
3605/*
3606 * "complete_add()" function
3607 */
3608 void
3609f_complete_add(typval_T *argvars, typval_T *rettv)
3610{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003611 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003612 return;
3613
Bram Moolenaar440cf092021-04-03 20:13:30 +02003614 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003615}
3616
3617/*
3618 * "complete_check()" function
3619 */
3620 void
3621f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3622{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003623 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003624 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003625
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003626 ins_compl_check_keys(0, TRUE);
3627 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003628
3629 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003630}
3631
3632/*
glepnirbcd59952025-04-24 21:48:35 +02003633 * Add match item to the return list.
3634 * Returns FAIL if out of memory, OK otherwise.
3635 */
3636 static int
3637add_match_to_list(
3638 typval_T *rettv,
3639 char_u *str,
3640 int len,
3641 int pos)
3642{
3643 list_T *match;
3644 int ret;
3645
3646 match = list_alloc();
3647 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003648 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003649
3650 if ((ret = list_append_number(match, pos + 1)) == FAIL
3651 || (ret = list_append_string(match, str, len)) == FAIL
3652 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3653 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003654 vim_free(match);
3655 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003656 }
3657
3658 return OK;
3659}
3660
3661/*
3662 * "complete_match()" function
3663 */
3664 void
3665f_complete_match(typval_T *argvars, typval_T *rettv)
3666{
3667 linenr_T lnum;
3668 colnr_T col;
3669 char_u *line = NULL;
3670 char_u *ise = NULL;
3671 regmatch_T regmatch;
3672 char_u *before_cursor = NULL;
3673 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003674 int bytepos = 0;
3675 char_u part[MAXPATHL];
3676 int ret;
3677
3678 if (rettv_list_alloc(rettv) == FAIL)
3679 return;
3680
3681 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3682
3683 if (argvars[0].v_type == VAR_UNKNOWN)
3684 {
3685 lnum = curwin->w_cursor.lnum;
3686 col = curwin->w_cursor.col;
3687 }
3688 else if (argvars[1].v_type == VAR_UNKNOWN)
3689 {
3690 emsg(_(e_invalid_argument));
3691 return;
3692 }
3693 else
3694 {
3695 lnum = (linenr_T)tv_get_number(&argvars[0]);
3696 col = (colnr_T)tv_get_number(&argvars[1]);
3697 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3698 {
3699 semsg(_(e_invalid_line_number_nr), lnum);
3700 return;
3701 }
3702 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3703 {
3704 semsg(_(e_invalid_column_number_nr), col + 1);
3705 return;
3706 }
3707 }
3708
3709 line = ml_get_buf(curbuf, lnum, FALSE);
3710 if (line == NULL)
3711 return;
3712
3713 before_cursor = vim_strnsave(line, col);
3714 if (before_cursor == NULL)
3715 return;
3716
3717 if (ise == NULL || *ise == NUL)
3718 {
3719 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3720 if (regmatch.regprog != NULL)
3721 {
3722 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3723 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003724 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003725 regmatch.endp[0] - regmatch.startp[0]);
3726 if (trig == NULL)
3727 {
3728 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003729 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003730 return;
3731 }
3732
Christian Brabandt3accf042025-04-25 19:01:06 +02003733 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003734 ret = add_match_to_list(rettv, trig, -1, bytepos);
3735 vim_free(trig);
3736 if (ret == FAIL)
3737 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003738 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003739 vim_regfree(regmatch.regprog);
3740 return;
3741 }
3742 }
3743 vim_regfree(regmatch.regprog);
3744 }
3745 }
3746 else
3747 {
glepnir08db2f42025-05-14 20:26:19 +02003748 char_u *p = ise;
3749 char_u *p_space = NULL;
3750
glepnirbcd59952025-04-24 21:48:35 +02003751 cur_end = before_cursor + (int)STRLEN(before_cursor);
3752
3753 while (*p != NUL)
3754 {
glepnir8d0e42b2025-05-12 20:28:28 +02003755 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003756 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003757 {
glepnir08db2f42025-05-14 20:26:19 +02003758 len = p - p_space - 1;
3759 memcpy(part, p_space + 1, len);
3760 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003761 }
3762 else
glepnir08db2f42025-05-14 20:26:19 +02003763 {
3764 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3765 if (next_comma && *(next_comma + 1) == ' ')
3766 p_space = next_comma;
3767
glepnir8d0e42b2025-05-12 20:28:28 +02003768 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003769 }
glepnirbcd59952025-04-24 21:48:35 +02003770
3771 if (len > 0 && len <= col)
3772 {
3773 if (STRNCMP(cur_end - len, part, len) == 0)
3774 {
3775 bytepos = col - len;
3776 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3777 {
3778 vim_free(before_cursor);
3779 return;
3780 }
3781 }
3782 }
3783 }
3784 }
3785
3786 vim_free(before_cursor);
3787}
3788
3789/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003790 * Return Insert completion mode name string
3791 */
3792 static char_u *
3793ins_compl_mode(void)
3794{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003795 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003796 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3797
3798 return (char_u *)"";
3799}
3800
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003801/*
3802 * Assign the sequence number to all the completion matches which don't have
3803 * one assigned yet.
3804 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003805 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003806ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003807{
3808 int number = 0;
3809 compl_T *match;
3810
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003811 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003812 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003813 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003814 // This should normally succeed already at the first loop
3815 // cycle, so it's fast!
3816 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003817 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003818 if (match->cp_number != -1)
3819 {
3820 number = match->cp_number;
3821 break;
3822 }
3823 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003824 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003825 for (match = match->cp_next;
3826 match != NULL && match->cp_number == -1;
3827 match = match->cp_next)
3828 match->cp_number = ++number;
3829 }
3830 else // BACKWARD
3831 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003832 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003833 // number. This should normally succeed already at the
3834 // first loop cycle, so it's fast!
3835 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003836 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003837 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003838 if (match->cp_number != -1)
3839 {
3840 number = match->cp_number;
3841 break;
3842 }
glepnir40891ba2025-02-10 22:18:00 +01003843 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003844 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003845 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003846 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003847 for (match = match->cp_prev; match
3848 && match->cp_number == -1;
3849 match = match->cp_prev)
3850 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003851 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003852 }
3853}
3854
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003855/*
glepnir037b0282025-01-16 14:37:44 +01003856 * Fill the dict of complete_info
3857 */
3858 static void
3859fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3860{
3861 dict_add_string(di, "word", match->cp_str.string);
3862 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3863 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3864 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3865 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3866 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003867 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003868 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003869 // Add an empty string for backwards compatibility
3870 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003871 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003872 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003873}
3874
3875/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003876 * Get complete information
3877 */
3878 static void
3879get_complete_info(list_T *what_list, dict_T *retdict)
3880{
3881 int ret = OK;
3882 listitem_T *item;
3883#define CI_WHAT_MODE 0x01
3884#define CI_WHAT_PUM_VISIBLE 0x02
3885#define CI_WHAT_ITEMS 0x04
3886#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003887#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003888#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003889#define CI_WHAT_ALL 0xff
3890 int what_flag;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003891 int compl_fuzzy_match = (get_cot_flags() & COT_FUZZY) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003892
3893 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003894 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003895 else
3896 {
3897 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003898 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003899 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003900 {
3901 char_u *what = tv_get_string(&item->li_tv);
3902
3903 if (STRCMP(what, "mode") == 0)
3904 what_flag |= CI_WHAT_MODE;
3905 else if (STRCMP(what, "pum_visible") == 0)
3906 what_flag |= CI_WHAT_PUM_VISIBLE;
3907 else if (STRCMP(what, "items") == 0)
3908 what_flag |= CI_WHAT_ITEMS;
3909 else if (STRCMP(what, "selected") == 0)
3910 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003911 else if (STRCMP(what, "completed") == 0)
3912 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003913 else if (STRCMP(what, "matches") == 0)
3914 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003915 }
3916 }
3917
3918 if (ret == OK && (what_flag & CI_WHAT_MODE))
3919 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3920
3921 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3922 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3923
glepnir037b0282025-01-16 14:37:44 +01003924 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3925 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003926 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003927 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003928 dict_T *di;
3929 compl_T *match;
3930 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003931 int has_items = what_flag & CI_WHAT_ITEMS;
3932 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003933 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003934
glepnird4088ed2024-12-31 10:55:22 +01003935 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003936 {
3937 li = list_alloc();
3938 if (li == NULL)
3939 return;
glepnird4088ed2024-12-31 10:55:22 +01003940 ret = dict_add_list(retdict, (has_matches && !has_items)
3941 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003942 }
3943 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3944 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3945 ins_compl_update_sequence_numbers();
3946 if (ret == OK && compl_first_match != NULL)
3947 {
3948 int list_idx = 0;
3949 match = compl_first_match;
3950 do
3951 {
3952 if (!match_at_original_text(match))
3953 {
glepnird4088ed2024-12-31 10:55:22 +01003954 if (has_items
3955 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003956 {
3957 di = dict_alloc();
3958 if (di == NULL)
3959 return;
3960 ret = list_append_dict(li, di);
3961 if (ret != OK)
3962 return;
glepnir037b0282025-01-16 14:37:44 +01003963 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003964 }
glepnird4088ed2024-12-31 10:55:22 +01003965 if (compl_curr_match != NULL
3966 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003967 selected_idx = list_idx;
Girish Palya0ac1eb32025-04-16 20:18:33 +02003968 if (compl_fuzzy_match || match->cp_in_match_array)
3969 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003970 }
3971 match = match->cp_next;
3972 }
3973 while (match != NULL && !is_first_match(match));
3974 }
3975 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3976 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003977
glepnir037b0282025-01-16 14:37:44 +01003978 if (ret == OK && selected_idx != -1 && has_completed)
3979 {
3980 di = dict_alloc();
3981 if (di == NULL)
3982 return;
3983 fill_complete_info_dict(di, compl_curr_match, FALSE);
3984 ret = dict_add_dict(retdict, "completed", di);
3985 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003986 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003987}
3988
3989/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003990 * "complete_info()" function
3991 */
3992 void
3993f_complete_info(typval_T *argvars, typval_T *rettv)
3994{
3995 list_T *what_list = NULL;
3996
Bram Moolenaar93a10962022-06-16 11:42:09 +01003997 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003998 return;
3999
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02004000 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
4001 return;
4002
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004003 if (argvars[0].v_type != VAR_UNKNOWN)
4004 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01004005 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004006 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004007 what_list = argvars[0].vval.v_list;
4008 }
4009 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004010}
4011#endif
4012
4013/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01004014 * Returns TRUE when using a user-defined function for thesaurus completion.
4015 */
4016 static int
4017thesaurus_func_complete(int type UNUSED)
4018{
4019#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01004020 return type == CTRL_X_THESAURUS
4021 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01004022#else
4023 return FALSE;
4024#endif
4025}
4026
4027/*
Girish Palya7c621052025-05-26 19:41:59 +02004028 * Check if 'cpt' list index can be advanced to the next completion source.
4029 */
4030 static int
4031may_advance_cpt_index(char_u *cpt)
4032{
4033 char_u *p = cpt;
4034
Girish Palya98c29db2025-06-01 19:40:00 +02004035 if (cpt_sources_index == -1)
4036 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004037 while (*p == ',' || *p == ' ') // Skip delimiters
4038 p++;
4039 return (*p != NUL);
4040}
4041
4042/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004043 * Return value of process_next_cpt_value()
4044 */
4045enum
4046{
4047 INS_COMPL_CPT_OK = 1,
4048 INS_COMPL_CPT_CONT,
4049 INS_COMPL_CPT_END
4050};
4051
4052/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004053 * state information used for getting the next set of insert completion
4054 * matches.
4055 */
4056typedef struct
4057{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004058 char_u *e_cpt_copy; // copy of 'complete'
4059 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004060 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004061 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004062 pos_T prev_match_pos; // previous match position
4063 int set_match_pos; // save first_match_pos/last_match_pos
4064 pos_T first_match_pos; // first match position
4065 pos_T last_match_pos; // last match position
4066 int found_all; // found all matches of a certain type.
4067 char_u *dict; // dictionary file to search
4068 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02004069 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004070} ins_compl_next_state_T;
4071
4072/*
4073 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004074 *
4075 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004076 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004077 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004078 * st->found_all - all matches of this type are found
4079 * st->ins_buf - search for completions in this buffer
4080 * st->first_match_pos - position of the first completion match
4081 * st->last_match_pos - position of the last completion match
4082 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004083 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004084 * st->dict - name of the dictionary or thesaurus file to search
4085 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004086 *
4087 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004088 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4089 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004090 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004091 */
4092 static int
4093process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004094 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004095 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004096 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004097 int fuzzy_collect,
4098 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004099{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004100 int compl_type = -1;
4101 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004102
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004103 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004104 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004105
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004106 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4107 st->e_cpt++;
4108
4109 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004110 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004111 st->ins_buf = curbuf;
4112 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004113 // Move the cursor back one character so that ^N can match the
4114 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004115 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004116 {
4117 // Move the cursor to after the last character in the
4118 // buffer, so that word at start of buffer is found
4119 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004120 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004121 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004122 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004123 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124 compl_type = 0;
4125
4126 // Remember the first match so that the loop stops when we
4127 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004128 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004129 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004130 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004131 && (st->ins_buf = ins_compl_next_buf(
4132 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004133 {
4134 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004135 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004136 {
4137 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004138 st->first_match_pos.col = st->last_match_pos.col = 0;
4139 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4140 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004141 compl_type = 0;
4142 }
4143 else // unloaded buffer, scan like dictionary
4144 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004145 st->found_all = TRUE;
4146 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004147 {
4148 status = INS_COMPL_CPT_CONT;
4149 goto done;
4150 }
4151 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004152 st->dict = st->ins_buf->b_fname;
4153 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004154 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004155 if (!shortmess(SHM_COMPLETIONSCAN))
4156 {
4157 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4158 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4159 st->ins_buf->b_fname == NULL
4160 ? buf_spname(st->ins_buf)
4161 : st->ins_buf->b_sfname == NULL
4162 ? st->ins_buf->b_fname
4163 : st->ins_buf->b_sfname);
4164 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4165 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004166 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004167 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004168 status = INS_COMPL_CPT_END;
4169 else
4170 {
4171 if (ctrl_x_mode_line_or_eval())
4172 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004173 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004174 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004175 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004176 compl_type = CTRL_X_DICTIONARY;
4177 else
4178 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004179 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004180 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004181 st->dict = st->e_cpt;
4182 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004183 }
4184 }
Girish Palyacbe53192025-04-14 22:13:15 +02004185#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004186 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004187 {
4188 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004189 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004190 if (!st->func_cb)
4191 compl_type = -1;
4192 }
4193#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004194#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004195 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004196 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004197 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004198 compl_type = CTRL_X_PATH_DEFINES;
4199#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004200 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004201 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004202 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004203 if (!shortmess(SHM_COMPLETIONSCAN))
4204 {
4205 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4206 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4207 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4208 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004209 }
4210 else
4211 compl_type = -1;
4212
4213 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004214 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004215 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004216
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004217 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004218 if (compl_type == -1)
4219 status = INS_COMPL_CPT_CONT;
4220 }
4221
4222done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004223 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004224 return status;
4225}
4226
4227#ifdef FEAT_FIND_ID
4228/*
4229 * Get the next set of identifiers or defines matching "compl_pattern" in
4230 * included files.
4231 */
4232 static void
4233get_next_include_file_completion(int compl_type)
4234{
John Marriott5e6ea922024-11-23 14:01:57 +01004235 find_pattern_in_path(compl_pattern.string, compl_direction,
4236 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004237 (compl_type == CTRL_X_PATH_DEFINES
4238 && !(compl_cont_status & CONT_SOL))
4239 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004240 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004241}
4242#endif
4243
4244/*
4245 * Get the next set of words matching "compl_pattern" in dictionary or
4246 * thesaurus files.
4247 */
4248 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004249get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004250{
4251#ifdef FEAT_COMPL_FUNC
4252 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004253 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004254 else
4255#endif
4256 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004257 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004258 : (compl_type == CTRL_X_THESAURUS
4259 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4260 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004261 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004262 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004263 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004264}
4265
4266/*
4267 * Get the next set of tag names matching "compl_pattern".
4268 */
4269 static void
4270get_next_tag_completion(void)
4271{
4272 int save_p_ic;
4273 char_u **matches;
4274 int num_matches;
4275
4276 // set p_ic according to p_ic, p_scs and pat for find_tags().
4277 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004278 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004279
4280 // Find up to TAG_MANY matches. Avoids that an enormous number
4281 // of matches is found when compl_pattern is empty
4282 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004283 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004284 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004285 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004286 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4287 ins_compl_add_matches(num_matches, matches, p_ic);
4288 g_tag_at_cursor = FALSE;
4289 p_ic = save_p_ic;
4290}
4291
4292/*
glepnir8159fb12024-07-17 20:32:54 +02004293 * Compare function for qsort
4294 */
glepnirf31cfa22025-03-06 21:59:13 +01004295 static int
4296compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004297{
4298 int idx_a = *(const int *)a;
4299 int idx_b = *(const int *)b;
4300 int score_a = compl_fuzzy_scores[idx_a];
4301 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004302 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4303 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004304}
4305
4306/*
glepnirf31cfa22025-03-06 21:59:13 +01004307 * insert prefix with redraw
4308 */
4309 static void
4310ins_compl_longest_insert(char_u *prefix)
4311{
4312 ins_compl_delete();
4313 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4314 ins_redraw(FALSE);
4315}
4316
4317/*
4318 * Calculate the longest common prefix among the best fuzzy matches
4319 * stored in compl_best_matches, and insert it as the longest.
4320 */
4321 static void
4322fuzzy_longest_match(void)
4323{
4324 char_u *prefix = NULL;
4325 int prefix_len = 0;
4326 int i = 0;
4327 int j = 0;
4328 char_u *match_str = NULL;
4329 char_u *prefix_ptr = NULL;
4330 char_u *match_ptr = NULL;
4331 char_u *leader = NULL;
4332 size_t leader_len = 0;
4333 compl_T *compl = NULL;
4334 int more_candidates = FALSE;
4335 compl_T *nn_compl = NULL;
4336
4337 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004338 return;
glepnirf31cfa22025-03-06 21:59:13 +01004339
4340 nn_compl = compl_first_match->cp_next->cp_next;
4341 if (nn_compl && nn_compl != compl_first_match)
4342 more_candidates = TRUE;
4343
4344 compl = ctrl_x_mode_whole_line() ? compl_first_match
4345 : compl_first_match->cp_next;
4346 if (compl_num_bests == 1)
4347 {
4348 // no more candidates insert the match str
4349 if (!more_candidates)
4350 {
4351 ins_compl_longest_insert(compl->cp_str.string);
4352 compl_num_bests = 0;
4353 }
4354 compl_num_bests = 0;
4355 return;
4356 }
4357
4358 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4359 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004360 return;
glepnirf31cfa22025-03-06 21:59:13 +01004361 while (compl != NULL && i < compl_num_bests)
4362 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004363 compl_best_matches[i] = compl;
4364 compl = compl->cp_next;
4365 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004366 }
4367
4368 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004369 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004370
4371 for (i = 1; i < compl_num_bests; i++)
4372 {
4373 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004374 prefix_ptr = prefix;
4375 match_ptr = match_str;
4376 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004377
4378 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4379 {
4380 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4381 break;
4382
4383 MB_PTR_ADV(prefix_ptr);
4384 MB_PTR_ADV(match_ptr);
4385 j++;
4386 }
4387
4388 if (j > 0)
4389 prefix_len = j;
4390 }
4391
4392 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004393 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004394
4395 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004396 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004397 goto end;
4398
zeertzjq4422de62025-03-07 19:06:02 +01004399 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004400 if (prefix != NULL)
4401 {
4402 ins_compl_longest_insert(prefix);
4403 compl_cfc_longest_ins = TRUE;
4404 vim_free(prefix);
4405 }
4406
4407end:
4408 vim_free(compl_best_matches);
4409 compl_best_matches = NULL;
4410 compl_num_bests = 0;
4411}
4412
4413/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004414 * Get the next set of filename matching "compl_pattern".
4415 */
4416 static void
4417get_next_filename_completion(void)
4418{
4419 char_u **matches;
4420 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004421 char_u *ptr;
4422 garray_T fuzzy_indices;
4423 int i;
4424 int score;
4425 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004426 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004427 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004428 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004429 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004430 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4431 int max_score = 0;
4432 int current_score = 0;
4433 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004434
glepnirb9de1a02024-08-02 19:14:38 +02004435#ifdef BACKSLASH_IN_FILENAME
4436 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4437 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4438#else
4439 char pathsep = PATHSEP;
4440#endif
4441
glepnirf31cfa22025-03-06 21:59:13 +01004442 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004443 {
glepnirb9de1a02024-08-02 19:14:38 +02004444#ifdef BACKSLASH_IN_FILENAME
4445 if (curbuf->b_p_csl[0] == 's')
4446 {
John Marriott5e6ea922024-11-23 14:01:57 +01004447 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004448 {
4449 if (leader[i] == '\\')
4450 leader[i] = '/';
4451 }
4452 }
4453 else if (curbuf->b_p_csl[0] == 'b')
4454 {
John Marriott5e6ea922024-11-23 14:01:57 +01004455 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004456 {
4457 if (leader[i] == '/')
4458 leader[i] = '\\';
4459 }
4460 }
4461#endif
4462 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004463 if (last_sep == NULL)
4464 {
4465 // No path separator or separator is the last character,
4466 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004467 VIM_CLEAR_STRING(compl_pattern);
4468 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4469 if (compl_pattern.string == NULL)
4470 return;
4471 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004472 }
4473 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004474 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004475 else
4476 {
4477 // Split leader into path and file parts
4478 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004479 char_u *path_with_wildcard;
4480
4481 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004482 if (path_with_wildcard != NULL)
4483 {
John Marriott5e6ea922024-11-23 14:01:57 +01004484 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4485 VIM_CLEAR_STRING(compl_pattern);
4486 compl_pattern.string = path_with_wildcard;
4487 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004488
4489 // Move leader to the file part
4490 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004491 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004492 }
4493 }
glepnir8159fb12024-07-17 20:32:54 +02004494 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004495
John Marriott5e6ea922024-11-23 14:01:57 +01004496 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004497 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4498 return;
4499
4500 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004501 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004502#ifdef BACKSLASH_IN_FILENAME
4503 if (curbuf->b_p_csl[0] != NUL)
4504 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004505 for (i = 0; i < num_matches; ++i)
4506 {
glepnir8159fb12024-07-17 20:32:54 +02004507 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004508 while (*ptr != NUL)
4509 {
4510 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4511 *ptr = '/';
4512 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4513 *ptr = '\\';
4514 ptr += (*mb_ptr2len)(ptr);
4515 }
4516 }
4517 }
4518#endif
glepnir8159fb12024-07-17 20:32:54 +02004519
glepnirf31cfa22025-03-06 21:59:13 +01004520 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004521 {
4522 ga_init2(&fuzzy_indices, sizeof(int), 10);
4523 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4524
4525 for (i = 0; i < num_matches; i++)
4526 {
4527 ptr = matches[i];
4528 score = fuzzy_match_str(ptr, leader);
4529 if (score > 0)
4530 {
4531 if (ga_grow(&fuzzy_indices, 1) == OK)
4532 {
4533 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4534 compl_fuzzy_scores[i] = score;
4535 fuzzy_indices.ga_len++;
4536 }
4537 }
4538 }
4539
Christian Brabandt220474d2024-07-20 13:26:44 +02004540 // prevent qsort from deref NULL pointer
4541 if (fuzzy_indices.ga_len > 0)
4542 {
glepnirf31cfa22025-03-06 21:59:13 +01004543 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004544 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4545 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004546
Christian Brabandt220474d2024-07-20 13:26:44 +02004547 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004548 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004549 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004550 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4551 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004552 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4553 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004554 dir = FORWARD;
4555
4556 if (need_collect_bests)
4557 {
4558 if (i == 0 || current_score == max_score)
4559 {
4560 compl_num_bests++;
4561 max_score = current_score;
4562 }
4563 }
4564 }
glepnir8159fb12024-07-17 20:32:54 +02004565
Christian Brabandt220474d2024-07-20 13:26:44 +02004566 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004567 }
glepnir6b6280c2024-07-27 16:25:45 +02004568 else if (leader_len > 0)
4569 {
4570 FreeWild(num_matches, matches);
4571 num_matches = 0;
4572 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004573
glepnir8159fb12024-07-17 20:32:54 +02004574 vim_free(compl_fuzzy_scores);
4575 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004576
4577 if (compl_num_bests > 0 && compl_get_longest)
4578 fuzzy_longest_match();
4579 return;
glepnir8159fb12024-07-17 20:32:54 +02004580 }
4581
glepnir6b6280c2024-07-27 16:25:45 +02004582 if (num_matches > 0)
4583 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004584}
4585
4586/*
4587 * Get the next set of command-line completions matching "compl_pattern".
4588 */
4589 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004590get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004591{
4592 char_u **matches;
4593 int num_matches;
4594
John Marriott5e6ea922024-11-23 14:01:57 +01004595 if (expand_cmdline(&compl_xp, compl_pattern.string,
4596 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004597 ins_compl_add_matches(num_matches, matches, FALSE);
4598}
4599
4600/*
4601 * Get the next set of spell suggestions matching "compl_pattern".
4602 */
4603 static void
4604get_next_spell_completion(linenr_T lnum UNUSED)
4605{
4606#ifdef FEAT_SPELL
4607 char_u **matches;
4608 int num_matches;
4609
John Marriott5e6ea922024-11-23 14:01:57 +01004610 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004611 if (num_matches > 0)
4612 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004613 else
4614 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004615#endif
4616}
4617
4618/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004619 * Return the next word or line from buffer "ins_buf" at position
4620 * "cur_match_pos" for completion. The length of the match is set in "len".
4621 */
4622 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004623ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004624 buf_T *ins_buf, // buffer being scanned
4625 pos_T *cur_match_pos, // current match position
4626 int *match_len,
4627 int *cont_s_ipos) // next ^X<> will set initial_pos
4628{
4629 char_u *ptr;
4630 int len;
4631
4632 *match_len = 0;
4633 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4634 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004635 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004636 if (ctrl_x_mode_line_or_eval())
4637 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004638 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004639 {
4640 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4641 return NULL;
4642 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004643 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004644 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004645 {
4646 char_u *tmp_ptr = ptr;
4647
4648 ptr = skipwhite(tmp_ptr);
4649 len -= (int)(ptr - tmp_ptr);
4650 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004651 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004652 }
4653 else
4654 {
4655 char_u *tmp_ptr = ptr;
4656
John Marriott5e6ea922024-11-23 14:01:57 +01004657 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004658 {
4659 tmp_ptr += compl_length;
4660 // Skip if already inside a word.
4661 if (vim_iswordp(tmp_ptr))
4662 return NULL;
4663 // Find start of next word.
4664 tmp_ptr = find_word_start(tmp_ptr);
4665 }
4666 // Find end of this word.
4667 tmp_ptr = find_word_end(tmp_ptr);
4668 len = (int)(tmp_ptr - ptr);
4669
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004670 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004671 {
4672 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4673 {
4674 // Try next line, if any. the new word will be
4675 // "join" as if the normal command "J" was used.
4676 // IOSIZE is always greater than
4677 // compl_length, so the next STRNCPY always
4678 // works -- Acevedo
4679 STRNCPY(IObuff, ptr, len);
4680 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4681 tmp_ptr = ptr = skipwhite(ptr);
4682 // Find start of next word.
4683 tmp_ptr = find_word_start(tmp_ptr);
4684 // Find end of next word.
4685 tmp_ptr = find_word_end(tmp_ptr);
4686 if (tmp_ptr > ptr)
4687 {
4688 if (*ptr != ')' && IObuff[len - 1] != TAB)
4689 {
4690 if (IObuff[len - 1] != ' ')
4691 IObuff[len++] = ' ';
4692 // IObuf =~ "\k.* ", thus len >= 2
4693 if (p_js
4694 && (IObuff[len - 2] == '.'
4695 || (vim_strchr(p_cpo, CPO_JOINSP)
4696 == NULL
4697 && (IObuff[len - 2] == '?'
4698 || IObuff[len - 2] == '!'))))
4699 IObuff[len++] = ' ';
4700 }
4701 // copy as much as possible of the new word
4702 if (tmp_ptr - ptr >= IOSIZE - len)
4703 tmp_ptr = ptr + IOSIZE - len - 1;
4704 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4705 len += (int)(tmp_ptr - ptr);
4706 *cont_s_ipos = TRUE;
4707 }
4708 IObuff[len] = NUL;
4709 ptr = IObuff;
4710 }
4711 if (len == compl_length)
4712 return NULL;
4713 }
4714 }
4715
4716 *match_len = len;
4717 return ptr;
4718}
4719
4720/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004721 * Get the next set of words matching "compl_pattern" for default completion(s)
4722 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004723 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4724 * position "st->start_pos" in the "compl_direction" direction. If
4725 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4726 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004727 * Returns OK if a new next match is found, otherwise returns FAIL.
4728 */
4729 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004730get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004731{
4732 int found_new_match = FAIL;
4733 int save_p_scs;
4734 int save_p_ws;
4735 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004736 char_u *ptr = NULL;
4737 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004738 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004739 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004740 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004741 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004742
4743 // If 'infercase' is set, don't use 'smartcase' here
4744 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004745 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004746 p_scs = FALSE;
4747
4748 // Buffers other than curbuf are scanned from the beginning or the
4749 // end but never from the middle, thus setting nowrapscan in this
4750 // buffer is a good idea, on the other hand, we always set
4751 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4752 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004753 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004754 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004755 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004756 p_ws = TRUE;
4757 looped_around = FALSE;
4758 for (;;)
4759 {
4760 int cont_s_ipos = FALSE;
4761
4762 ++msg_silent; // Don't want messages for wrapscan.
4763
glepnirf31cfa22025-03-06 21:59:13 +01004764 if (in_collect)
4765 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004766 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004767 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004768 start_pos, &len, &ptr, &score);
4769 }
4770 // ctrl_x_mode_line_or_eval() || word-wise search that
4771 // has added a word that was at the beginning of the line
4772 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4773 found_new_match = search_for_exact_line(st->ins_buf,
4774 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004775 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004776 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004777 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004778 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004779 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004780 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004781 {
4782 // set "compl_started" even on fail
4783 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004784 st->first_match_pos = *st->cur_match_pos;
4785 st->last_match_pos = *st->cur_match_pos;
4786 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004787 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004788 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4789 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004790 {
4791 found_new_match = FAIL;
4792 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004793 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004794 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4795 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4796 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004797 {
4798 if (looped_around)
4799 found_new_match = FAIL;
4800 else
4801 looped_around = TRUE;
4802 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004803 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004804 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4805 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4806 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004807 {
4808 if (looped_around)
4809 found_new_match = FAIL;
4810 else
4811 looped_around = TRUE;
4812 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004813 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004814 if (found_new_match == FAIL)
4815 break;
4816
4817 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004818 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004819 && start_pos->lnum == st->cur_match_pos->lnum
4820 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004821 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004822
glepnirf31cfa22025-03-06 21:59:13 +01004823 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004824 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4825 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004826 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004827 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004828
Girish Palyab1565882025-04-15 20:16:00 +02004829 if (is_nearest_active() && in_curbuf)
4830 {
4831 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4832 if (score < 0)
4833 score = -score;
4834 score++;
4835 }
4836
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004837 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004838 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004839 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004840 {
glepnirf31cfa22025-03-06 21:59:13 +01004841 if (in_collect && score == compl_first_match->cp_next->cp_score)
4842 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004843 found_new_match = OK;
4844 break;
4845 }
4846 }
4847 p_scs = save_p_scs;
4848 p_ws = save_p_ws;
4849
4850 return found_new_match;
4851}
4852
Girish Palyacbe53192025-04-14 22:13:15 +02004853#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004854/*
4855 * Return the callback function associated with "p" if it points to a
4856 * userfunc.
4857 */
Girish Palyacbe53192025-04-14 22:13:15 +02004858 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004859get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004860{
4861 static callback_T cb;
4862 char_u buf[LSIZE];
4863 int slen;
4864
Girish Palya98c29db2025-06-01 19:40:00 +02004865 if (*p == 'o')
4866 return &curbuf->b_ofu_cb;
4867 if (*p == 'F')
4868 {
4869 if (*++p != ',' && *p != NUL)
4870 {
4871 free_callback(&cb);
4872 slen = copy_option_part(&p, buf, LSIZE, ",");
4873 if (slen > 0 && option_set_callback_func(buf, &cb))
4874 return &cb;
4875 return NULL;
4876 }
4877 else
4878 return &curbuf->b_cfu_cb;
4879 }
Girish Palyacbe53192025-04-14 22:13:15 +02004880 return NULL;
4881}
4882
4883/*
4884 * Retrieve new completion matches by invoking callback "cb".
4885 */
4886 static void
4887expand_cpt_function(callback_T *cb)
4888{
4889 // Re-insert the text removed by ins_compl_delete().
4890 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4891 // Get matches
4892 get_cpt_func_completion_matches(cb);
4893 // Undo insertion
4894 ins_compl_delete();
4895}
4896#endif
4897
4898/*
glepnir05460682025-05-26 18:23:27 +02004899 * Get completion matches from register contents.
4900 * Extracts words from all available registers and adds them to the completion list.
4901 */
4902 static void
4903get_register_completion(void)
4904{
4905 int dir = compl_direction;
4906 yankreg_T *reg = NULL;
4907 void *reg_ptr = NULL;
4908
4909 for (int i = 0; i < NUM_REGISTERS; i++)
4910 {
4911 int regname = 0;
4912
4913 if (i == 0)
4914 regname = '"'; // unnamed register
4915 else if (i < 10)
4916 regname = '0' + i;
4917 else if (i == DELETION_REGISTER)
4918 regname = '-';
4919#ifdef FEAT_CLIPBOARD
4920 else if (i == STAR_REGISTER)
4921 regname = '*';
4922 else if (i == PLUS_REGISTER)
4923 regname = '+';
4924#endif
4925 else
4926 regname = 'a' + i - 10;
4927
4928 // Skip invalid or black hole register
4929 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4930 continue;
4931
4932 reg_ptr = get_register(regname, FALSE);
4933 if (reg_ptr == NULL)
4934 continue;
4935
4936 reg = (yankreg_T *)reg_ptr;
4937
4938 for (int j = 0; j < reg->y_size; j++)
4939 {
4940 char_u *str = reg->y_array[j].string;
4941 if (str == NULL)
4942 continue;
4943
4944 char_u *p = str;
4945 while (*p != NUL)
4946 {
4947 p = find_word_start(p);
4948 if (*p == NUL)
4949 break;
4950
4951 char_u *word_end = find_word_end(p);
4952
4953 // Add the word to the completion list
4954 int len = (int)(word_end - p);
4955 if (len > 0 && (!compl_orig_text.string
4956 || (p_ic ? STRNICMP(p, compl_orig_text.string,
4957 compl_orig_text.length) == 0
4958 : STRNCMP(p, compl_orig_text.string,
4959 compl_orig_text.length) == 0)))
4960 {
4961 if (ins_compl_add_infercase(p, len, p_ic, NULL,
4962 dir, FALSE, 0) == OK)
4963 dir = FORWARD;
4964 }
4965
4966 p = word_end;
4967 }
4968 }
4969
4970 // Free the register copy
4971 put_register(regname, reg_ptr);
4972 }
4973}
4974
4975/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004976 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004977 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004978 */
4979 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004980get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004981{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004982 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004983
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004984 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004985 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004986 case -1:
4987 break;
4988#ifdef FEAT_FIND_ID
4989 case CTRL_X_PATH_PATTERNS:
4990 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004991 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004992 break;
4993#endif
4994
4995 case CTRL_X_DICTIONARY:
4996 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004997 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4998 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004999 break;
5000
5001 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005002 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005003 break;
5004
5005 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005006 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005007 break;
5008
5009 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02005010 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005011 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005012 break;
5013
5014#ifdef FEAT_COMPL_FUNC
5015 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02005016 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
5017 expand_cpt_function(st->func_cb);
5018 else
5019 expand_by_function(type, compl_pattern.string, NULL);
5020 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005021 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02005022 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005023 break;
5024#endif
5025
5026 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005027 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005028 break;
5029
glepnir05460682025-05-26 18:23:27 +02005030 case CTRL_X_REGISTER:
5031 get_register_completion();
5032 break;
5033
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005034 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005035 found_new_match = get_next_default_completion(st, ini);
5036 if (found_new_match == FAIL && st->ins_buf == curbuf)
5037 st->found_all = TRUE;
5038 }
5039
5040 // check if compl_curr_match has changed, (e.g. other type of
5041 // expansion added something)
5042 if (type != 0 && compl_curr_match != compl_old_match)
5043 found_new_match = OK;
5044
5045 return found_new_match;
5046}
5047
5048/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005049 * Strips carets followed by numbers. This suffix typically represents the
5050 * max_matches setting.
5051 */
5052 static void
5053strip_caret_numbers_in_place(char_u *str)
5054{
5055 char_u *read = str, *write = str, *p;
5056
5057 if (str == NULL)
5058 return;
5059
5060 while (*read)
5061 {
5062 if (*read == '^')
5063 {
5064 p = read + 1;
5065 while (vim_isdigit(*p))
5066 p++;
5067 if ((*p == ',' || *p == '\0') && p != read + 1)
5068 {
5069 read = p;
5070 continue;
5071 }
5072 else
5073 *write++ = *read++;
5074 }
5075 else
5076 *write++ = *read++;
5077 }
5078 *write = '\0';
5079}
5080
5081/*
Girish Palya98c29db2025-06-01 19:40:00 +02005082 * Call functions specified in the 'cpt' option with findstart=1,
5083 * and retrieve the startcol.
5084 */
5085 static void
5086prepare_cpt_compl_funcs(void)
5087{
5088#ifdef FEAT_COMPL_FUNC
5089 char_u *cpt;
5090 char_u *p;
5091 callback_T *cb = NULL;
5092 int idx = 0;
5093 int startcol;
5094
5095 // Make a copy of 'cpt' in case the buffer gets wiped out
5096 cpt = vim_strsave(curbuf->b_p_cpt);
5097 strip_caret_numbers_in_place(cpt);
5098
5099 // Re-insert the text removed by ins_compl_delete().
5100 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5101
5102 for (p = cpt; *p;)
5103 {
5104 while (*p == ',' || *p == ' ') // Skip delimiters
5105 p++;
5106 cb = get_callback_if_cpt_func(p);
5107 if (cb)
5108 {
5109 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5110 == FAIL)
5111 {
5112 if (startcol == -3)
5113 cpt_sources_array[idx].cs_refresh_always = FALSE;
5114 else
5115 startcol = -2;
5116 }
5117 cpt_sources_array[idx].cs_startcol = startcol;
5118 }
5119 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5120 idx++;
5121 }
5122
5123 // Undo insertion
5124 ins_compl_delete();
5125
5126 vim_free(cpt);
5127#endif
5128}
5129
5130/*
Girish Palya7c621052025-05-26 19:41:59 +02005131 * Safely advance the cpt_sources_index by one.
5132 */
5133 static int
5134advance_cpt_sources_index_safe(void)
5135{
5136 if (cpt_sources_index < cpt_sources_count - 1)
5137 {
5138 cpt_sources_index++;
5139 return OK;
5140 }
5141#ifdef FEAT_EVAL
5142 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5143#endif
5144 return FAIL;
5145}
5146
5147/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005148 * Get the next expansion(s), using "compl_pattern".
5149 * The search starts at position "ini" in curbuf and in the direction
5150 * compl_direction.
5151 * When "compl_started" is FALSE start at that position, otherwise continue
5152 * where we stopped searching before.
5153 * This may return before finding all the matches.
5154 * Return the total number of matches or -1 if still unknown -- Acevedo
5155 */
5156 static int
5157ins_compl_get_exp(pos_T *ini)
5158{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005159 static ins_compl_next_state_T st;
5160 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005161 int i;
5162 int found_new_match;
5163 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005164 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005165
5166 if (!compl_started)
5167 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005168 buf_T *buf;
5169
5170 FOR_ALL_BUFFERS(buf)
5171 buf->b_scanned = 0;
5172 if (!st_cleared)
5173 {
5174 CLEAR_FIELD(st);
5175 st_cleared = TRUE;
5176 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005177 st.found_all = FALSE;
5178 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005179 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005180 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005181 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5182 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005183 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005184 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005185 st.last_match_pos = st.first_match_pos = *ini;
5186 }
5187 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5188 st.ins_buf = curbuf; // In case the buffer was wiped out.
5189
5190 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005191 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005192 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005193
Girish Palya98c29db2025-06-01 19:40:00 +02005194 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5195 !(compl_cont_status & CONT_LOCAL))
5196 {
5197 // ^N completion, not ^X^L or complete() or ^X^N
5198 if (!compl_started) // Before showing menu the first time
5199 {
5200 if (setup_cpt_sources() == FAIL)
5201 return FAIL;
5202 }
5203 prepare_cpt_compl_funcs();
5204 cpt_sources_index = 0;
5205 }
5206
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005207 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005208 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005209 {
5210 found_new_match = FAIL;
5211 st.set_match_pos = FALSE;
5212
5213 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5214 // or if found_all says this entry is done. For ^X^L only use the
5215 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005216 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005217 && (!compl_started || st.found_all))
5218 {
Girish Palya7c621052025-05-26 19:41:59 +02005219 int status = process_next_cpt_value(&st, &type, ini,
5220 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005221
5222 if (status == INS_COMPL_CPT_END)
5223 break;
5224 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005225 {
Girish Palya7c621052025-05-26 19:41:59 +02005226 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5227 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005228 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005229 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005230 }
5231
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005232 // If complete() was called then compl_pattern has been reset. The
5233 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005234 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005235 break;
5236
5237 // get the next set of completion matches
5238 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005239
Girish Palya7c621052025-05-26 19:41:59 +02005240 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5241 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005242
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005243 // break the loop for specialized modes (use 'complete' just for the
5244 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5245 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005246 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5247 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005248 {
5249 if (got_int)
5250 break;
5251 // Fill the popup menu as soon as possible.
5252 if (type != -1)
5253 ins_compl_check_keys(0, FALSE);
5254
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005255 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005256 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5257 break;
5258 compl_started = TRUE;
5259 }
5260 else
5261 {
5262 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005263 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005264 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005265
5266 compl_started = FALSE;
5267 }
5268 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005269 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005270 compl_started = TRUE;
5271
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005272 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005273 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005274 found_new_match = FAIL;
5275
5276 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005277 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005278 && !ctrl_x_mode_line_or_eval()))
5279 i = ins_compl_make_cyclic();
5280
glepnirf31cfa22025-03-06 21:59:13 +01005281 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5282 fuzzy_longest_match();
5283
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005284 if (compl_old_match != NULL)
5285 {
5286 // If several matches were added (FORWARD) or the search failed and has
5287 // just been made cyclic then we have to move compl_curr_match to the
5288 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005289 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005290 : compl_old_match->cp_prev;
5291 if (compl_curr_match == NULL)
5292 compl_curr_match = compl_old_match;
5293 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005294 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005295
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005296 return i;
5297}
5298
5299/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005300 * Update "compl_shown_match" to the actually shown match, it may differ when
5301 * "compl_leader" is used to omit some of the matches.
5302 */
5303 static void
5304ins_compl_update_shown_match(void)
5305{
5306 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005307 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005308 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005309 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005310 compl_shown_match = compl_shown_match->cp_next;
5311
5312 // If we didn't find it searching forward, and compl_shows_dir is
5313 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005314 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005315 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005316 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005317 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005318 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005319 {
5320 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005321 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005322 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005323 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005324 compl_shown_match = compl_shown_match->cp_prev;
5325 }
5326}
5327
5328/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005329 * Delete the old text being completed.
5330 */
5331 void
5332ins_compl_delete(void)
5333{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005334 // In insert mode: Delete the typed part.
5335 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005336 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005337 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005338 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005339 int has_preinsert = ins_compl_preinsert_effect();
5340 if (has_preinsert)
5341 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005342 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005343 curwin->w_cursor.col = compl_ins_end_col;
5344 }
5345
glepnir76bdb822025-02-08 19:04:51 +01005346 if (curwin->w_cursor.lnum > compl_lnum)
5347 {
5348 if (curwin->w_cursor.col < ml_get_curline_len())
5349 {
John Marriottf4b36412025-02-23 09:09:59 +01005350 char_u *line = ml_get_cursor();
5351 remaining.length = ml_get_cursor_len();
5352 remaining.string = vim_strnsave(line, remaining.length);
5353 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005354 return;
5355 }
5356 while (curwin->w_cursor.lnum > compl_lnum)
5357 {
5358 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5359 {
John Marriottf4b36412025-02-23 09:09:59 +01005360 if (remaining.string)
5361 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005362 return;
5363 }
zeertzjq060e6552025-02-21 20:06:26 +01005364 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005365 curwin->w_cursor.lnum--;
5366 }
5367 // move cursor to end of line
5368 curwin->w_cursor.col = ml_get_curline_len();
5369 }
5370
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005371 if ((int)curwin->w_cursor.col > col)
5372 {
5373 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005374 {
John Marriottf4b36412025-02-23 09:09:59 +01005375 if (remaining.string)
5376 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005377 return;
glepnire3647c82025-02-10 21:16:32 +01005378 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005379 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005380 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005381 }
5382
John Marriottf4b36412025-02-23 09:09:59 +01005383 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005384 {
5385 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005386 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005387 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005388 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005389 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005390 // TODO: is this sufficient for redrawing? Redrawing everything causes
5391 // flicker, thus we can't do that.
5392 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005393#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005394 // clear v:completed_item
5395 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005396#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005397}
5398
5399/*
glepnir76bdb822025-02-08 19:04:51 +01005400 * Insert a completion string that contains newlines.
5401 * The string is split and inserted line by line.
5402 */
5403 static void
5404ins_compl_expand_multiple(char_u *str)
5405{
5406 char_u *start = str;
5407 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005408 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005409
5410 while (*curr != NUL)
5411 {
5412 if (*curr == '\n')
5413 {
5414 // Insert the text chunk before newline
5415 if (curr > start)
5416 ins_char_bytes(start, (int)(curr - start));
5417
5418 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005419 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005420 start = curr + 1;
5421 }
5422 curr++;
5423 }
5424
5425 // Handle remaining text after last newline (if any)
5426 if (curr > start)
5427 ins_char_bytes(start, (int)(curr - start));
5428
5429 compl_ins_end_col = curwin->w_cursor.col;
5430}
5431
5432/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005433 * Insert the new text being completed.
5434 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01005435 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5436 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005437 */
5438 void
glepniredd4ac32025-01-29 18:53:51 +01005439ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005440{
glepnir76bdb822025-02-08 19:04:51 +01005441 int compl_len = get_compl_len();
5442 int preinsert = ins_compl_has_preinsert();
5443 char_u *cp_str = compl_shown_match->cp_str.string;
5444 size_t cp_str_len = compl_shown_match->cp_str.length;
5445 size_t leader_len = ins_compl_leader_len();
5446 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005447
5448 // Make sure we don't go over the end of the string, this can happen with
5449 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005450 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005451 {
glepnir76bdb822025-02-08 19:04:51 +01005452 if (has_multiple)
5453 ins_compl_expand_multiple(cp_str + compl_len);
5454 else
5455 {
5456 ins_compl_insert_bytes(cp_str + compl_len, -1);
5457 if (preinsert && move_cursor)
5458 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5459 }
glepniredd4ac32025-01-29 18:53:51 +01005460 }
5461 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005462 compl_used_match = FALSE;
5463 else
5464 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005465#ifdef FEAT_EVAL
5466 {
5467 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5468
5469 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5470 }
5471#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005472 if (!in_compl_func)
5473 compl_curr_match = compl_shown_match;
5474}
5475
5476/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005477 * show the file name for the completion match (if any). Truncate the file
5478 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005479 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005480 static void
5481ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005482{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005483 char *lead = _("match in file");
5484 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5485 char_u *s;
5486 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005487
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005488 if (space <= 0)
5489 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005491 // We need the tail that fits. With double-byte encoding going
5492 // back from the end is very slow, thus go from the start and keep
5493 // the text that fits in "space" between "s" and "e".
5494 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005495 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005496 space -= ptr2cells(e);
5497 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005498 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005499 space += ptr2cells(s);
5500 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005501 }
5502 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005503 msg_hist_off = TRUE;
5504 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5505 s > compl_shown_match->cp_fname ? "<" : "", s);
5506 msg((char *)IObuff);
5507 msg_hist_off = FALSE;
5508 redraw_cmdline = FALSE; // don't overwrite!
5509}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005510
glepnirdca57fb2024-06-04 22:01:21 +02005511/*
zeertzjq551d8c32024-06-05 19:53:32 +02005512 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005513 */
glepnira218cc62024-06-03 19:32:39 +02005514 static compl_T *
5515find_comp_when_fuzzy(void)
5516{
5517 int score;
5518 char_u* str;
5519 int target_idx = -1;
5520 int is_forward = compl_shows_dir_forward();
5521 int is_backward = compl_shows_dir_backward();
5522 compl_T *comp = NULL;
5523
glepnir43eef882024-06-19 20:20:48 +02005524 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005525 || (is_backward && compl_selected_item == 0))
glepnir5a18ccf2025-05-11 13:48:33 +02005526 return match_at_original_text(compl_first_match)
5527 ? compl_first_match : compl_first_match->cp_prev;
glepnira218cc62024-06-03 19:32:39 +02005528
5529 if (is_forward)
5530 target_idx = compl_selected_item + 1;
5531 else if (is_backward)
Hirohito Higashi355db992025-04-28 18:07:02 +02005532 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005533 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005534
5535 score = compl_match_array[target_idx].pum_score;
5536 str = compl_match_array[target_idx].pum_text;
5537
5538 comp = compl_first_match;
Hirohito Higashia4a00a72025-05-08 22:58:31 +02005539 do
5540 {
Hirohito Higashi355db992025-04-28 18:07:02 +02005541 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
5542 return comp;
5543 comp = comp->cp_next;
glepnira218cc62024-06-03 19:32:39 +02005544 } while (comp != NULL && !is_first_match(comp));
5545
5546 return NULL;
5547}
5548
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005549/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005550 * Find the appropriate completion item when 'complete' ('cpt') includes
5551 * a 'max_matches' postfix. In this case, we search for a match where
5552 * 'cp_in_match_array' is set, indicating that the match is also present
5553 * in 'compl_match_array'.
5554 */
5555 static compl_T *
5556find_comp_when_cpt_sources(void)
5557{
5558 int is_forward = compl_shows_dir_forward();
5559 compl_T *match = compl_shown_match;
5560
5561 do
5562 match = is_forward ? match->cp_next : match->cp_prev;
5563 while (match->cp_next && !match->cp_in_match_array
5564 && !match_at_original_text(match));
5565 return match;
5566}
5567
5568/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005569 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005570 * times. The number of matches found is returned in 'num_matches'.
5571 *
5572 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5573 * get more completions. If it is FALSE, then do nothing when there are no more
5574 * completions in the given direction.
5575 *
5576 * If "advance" is TRUE, then completion will move to the first match.
5577 * Otherwise, the original text will be shown.
5578 *
5579 * Returns OK on success and -1 if the number of matches are unknown.
5580 */
5581 static int
5582find_next_completion_match(
5583 int allow_get_expansion,
5584 int todo, // repeat completion this many times
5585 int advance,
5586 int *num_matches)
5587{
5588 int found_end = FALSE;
5589 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005590 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005591 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5592 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02005593 int cpt_sources_active = compl_match_array && cpt_sources_array;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005594
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005595 while (--todo >= 0)
5596 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005597 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005598 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02005599 if (compl_match_array != NULL && compl_fuzzy_match)
5600 compl_shown_match = find_comp_when_fuzzy();
5601 else if (cpt_sources_active)
5602 compl_shown_match = find_comp_when_cpt_sources();
5603 else
5604 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005605 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005606 && (is_first_match(compl_shown_match->cp_next)
5607 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005608 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005609 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005610 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005611 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005612 found_end = is_first_match(compl_shown_match);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005613 if (compl_match_array != NULL && compl_fuzzy_match)
5614 compl_shown_match = find_comp_when_fuzzy();
5615 else if (cpt_sources_active)
5616 compl_shown_match = find_comp_when_cpt_sources();
5617 else
5618 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005619 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005620 }
5621 else
5622 {
5623 if (!allow_get_expansion)
5624 {
5625 if (advance)
5626 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005627 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005628 compl_pending -= todo + 1;
5629 else
5630 compl_pending += todo + 1;
5631 }
5632 return -1;
5633 }
5634
5635 if (!compl_no_select && advance)
5636 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005637 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005638 --compl_pending;
5639 else
5640 ++compl_pending;
5641 }
5642
5643 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005644 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005645
5646 // handle any pending completions
5647 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005648 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005649 {
5650 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5651 {
5652 compl_shown_match = compl_shown_match->cp_next;
5653 --compl_pending;
5654 }
5655 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5656 {
5657 compl_shown_match = compl_shown_match->cp_prev;
5658 ++compl_pending;
5659 }
5660 else
5661 break;
5662 }
5663 found_end = FALSE;
5664 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005665 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005666 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005667 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005668 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005669 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005670 ++todo;
5671 else
5672 // Remember a matching item.
5673 found_compl = compl_shown_match;
5674
5675 // Stop at the end of the list when we found a usable match.
5676 if (found_end)
5677 {
5678 if (found_compl != NULL)
5679 {
5680 compl_shown_match = found_compl;
5681 break;
5682 }
5683 todo = 1; // use first usable match after wrapping around
5684 }
5685 }
5686
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005687 return OK;
5688}
5689
5690/*
5691 * Fill in the next completion in the current direction.
5692 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5693 * get more completions. If it is FALSE, then we just do nothing when there
5694 * are no more completions in a given direction. The latter case is used when
5695 * we are still in the middle of finding completions, to allow browsing
5696 * through the ones found so far.
5697 * Return the total number of matches, or -1 if still unknown -- webb.
5698 *
5699 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5700 * compl_shown_match here.
5701 *
5702 * Note that this function may be called recursively once only. First with
5703 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5704 * calls this function with "allow_get_expansion" FALSE.
5705 */
5706 static int
5707ins_compl_next(
5708 int allow_get_expansion,
5709 int count, // repeat completion this many times; should
5710 // be at least 1
5711 int insert_match, // Insert the newly selected match
5712 int in_compl_func) // called from complete_check()
5713{
5714 int num_matches = -1;
5715 int todo = count;
5716 int advance;
5717 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005718 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005719 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005720 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5721 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005722 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005723
5724 // When user complete function return -1 for findstart which is next
5725 // time of 'always', compl_shown_match become NULL.
5726 if (compl_shown_match == NULL)
5727 return -1;
5728
John Marriott5e6ea922024-11-23 14:01:57 +01005729 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005730 && !match_at_original_text(compl_shown_match)
5731 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005732 // Update "compl_shown_match" to the actually shown match
5733 ins_compl_update_shown_match();
5734
5735 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005736 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005737 // Delete old text to be replaced
5738 ins_compl_delete();
5739
5740 // When finding the longest common text we stick at the original text,
5741 // don't let CTRL-N or CTRL-P move to the first match.
5742 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5743
5744 // When restarting the search don't insert the first match either.
5745 if (compl_restarting)
5746 {
5747 advance = FALSE;
5748 compl_restarting = FALSE;
5749 }
5750
5751 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5752 // around.
5753 if (find_next_completion_match(allow_get_expansion, todo, advance,
5754 &num_matches) == -1)
5755 return -1;
5756
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005757 if (curbuf != orig_curbuf)
5758 {
5759 // In case some completion function switched buffer, don't want to
5760 // insert the completion elsewhere.
5761 return -1;
5762 }
5763
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005764 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005765 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005766 {
glepnir6a38aff2024-12-16 21:56:16 +01005767 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005768 compl_used_match = FALSE;
5769 }
5770 else if (insert_match)
5771 {
5772 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005773 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005774 else
glepnir6a38aff2024-12-16 21:56:16 +01005775 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005776 }
5777 else
5778 compl_used_match = FALSE;
5779
5780 if (!allow_get_expansion)
5781 {
5782 // may undisplay the popup menu first
5783 ins_compl_upd_pum();
5784
5785 if (pum_enough_matches())
5786 // Will display the popup menu, don't redraw yet to avoid flicker.
5787 pum_call_update_screen();
5788 else
5789 // Not showing the popup menu yet, redraw to show the user what was
5790 // inserted.
5791 update_screen(0);
5792
5793 // display the updated popup menu
5794 ins_compl_show_pum();
5795#ifdef FEAT_GUI
5796 if (gui.in_use)
5797 {
5798 // Show the cursor after the match, not after the redrawn text.
5799 setcursor();
5800 out_flush_cursor(FALSE, FALSE);
5801 }
5802#endif
5803
5804 // Delete old text to be replaced, since we're still searching and
5805 // don't want to match ourselves!
5806 ins_compl_delete();
5807 }
5808
5809 // Enter will select a match when the match wasn't inserted and the popup
5810 // menu is visible.
5811 if (compl_no_insert && !started)
5812 compl_enter_selects = TRUE;
5813 else
5814 compl_enter_selects = !insert_match && compl_match_array != NULL;
5815
5816 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005817 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005818 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005819
5820 return num_matches;
5821}
5822
5823/*
5824 * Call this while finding completions, to check whether the user has hit a key
5825 * that should change the currently displayed completion, or exit completion
5826 * mode. Also, when compl_pending is not zero, show a completion as soon as
5827 * possible. -- webb
5828 * "frequency" specifies out of how many calls we actually check.
5829 * "in_compl_func" is TRUE when called from complete_check(), don't set
5830 * compl_curr_match.
5831 */
5832 void
5833ins_compl_check_keys(int frequency, int in_compl_func)
5834{
5835 static int count = 0;
5836 int c;
5837
5838 // Don't check when reading keys from a script, :normal or feedkeys().
5839 // That would break the test scripts. But do check for keys when called
5840 // from complete_check().
5841 if (!in_compl_func && (using_script() || ex_normal_busy))
5842 return;
5843
5844 // Only do this at regular intervals
5845 if (++count < frequency)
5846 return;
5847 count = 0;
5848
5849 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5850 // can't do its work correctly.
5851 c = vpeekc_any();
5852 if (c != NUL)
5853 {
5854 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5855 {
5856 c = safe_vgetc(); // Eat the character
5857 compl_shows_dir = ins_compl_key2dir(c);
5858 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5859 c != K_UP && c != K_DOWN, in_compl_func);
5860 }
5861 else
5862 {
5863 // Need to get the character to have KeyTyped set. We'll put it
5864 // back with vungetc() below. But skip K_IGNORE.
5865 c = safe_vgetc();
5866 if (c != K_IGNORE)
5867 {
5868 // Don't interrupt completion when the character wasn't typed,
5869 // e.g., when doing @q to replay keys.
5870 if (c != Ctrl_R && KeyTyped)
5871 compl_interrupted = TRUE;
5872
5873 vungetc(c);
5874 }
5875 }
5876 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005877 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005878 {
5879 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5880
5881 compl_pending = 0;
5882 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5883 }
5884}
5885
5886/*
5887 * Decide the direction of Insert mode complete from the key typed.
5888 * Returns BACKWARD or FORWARD.
5889 */
5890 static int
5891ins_compl_key2dir(int c)
5892{
5893 if (c == Ctrl_P || c == Ctrl_L
5894 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5895 return BACKWARD;
5896 return FORWARD;
5897}
5898
5899/*
5900 * Return TRUE for keys that are used for completion only when the popup menu
5901 * is visible.
5902 */
5903 static int
5904ins_compl_pum_key(int c)
5905{
5906 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5907 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5908 || c == K_UP || c == K_DOWN);
5909}
5910
5911/*
5912 * Decide the number of completions to move forward.
5913 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5914 */
5915 static int
5916ins_compl_key2count(int c)
5917{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005918 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5919 {
glepnir19e1dd62025-05-08 22:50:38 +02005920 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005921 if (h > 3)
5922 h -= 2; // keep some context
5923 return h;
5924 }
5925 return 1;
5926}
5927
5928/*
5929 * Return TRUE if completion with "c" should insert the match, FALSE if only
5930 * to change the currently selected completion.
5931 */
5932 static int
5933ins_compl_use_match(int c)
5934{
5935 switch (c)
5936 {
5937 case K_UP:
5938 case K_DOWN:
5939 case K_PAGEDOWN:
5940 case K_KPAGEDOWN:
5941 case K_S_DOWN:
5942 case K_PAGEUP:
5943 case K_KPAGEUP:
5944 case K_S_UP:
5945 return FALSE;
5946 }
5947 return TRUE;
5948}
5949
5950/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005951 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5952 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005953 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005954 * Uses the global variables: compl_cont_status and ctrl_x_mode
5955 */
5956 static int
5957get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5958{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005959 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005960 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005961 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005962 {
5963 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5964 ;
5965 compl_col += ++startcol;
5966 compl_length = curs_col - startcol;
5967 }
5968 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005969 {
John Marriott5e6ea922024-11-23 14:01:57 +01005970 compl_pattern.string = str_foldcase(line + compl_col,
5971 compl_length, NULL, 0);
5972 if (compl_pattern.string == NULL)
5973 {
5974 compl_pattern.length = 0;
5975 return FAIL;
5976 }
5977 compl_pattern.length = STRLEN(compl_pattern.string);
5978 }
5979 else
5980 {
5981 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5982 if (compl_pattern.string == NULL)
5983 {
5984 compl_pattern.length = 0;
5985 return FAIL;
5986 }
5987 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005988 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005989 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005990 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005991 {
5992 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005993 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005994 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005995
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005996 if (!vim_iswordp(line + compl_col)
5997 || (compl_col > 0
5998 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005999 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006000 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02006001 prefixlen = 0;
6002 }
John Marriott5e6ea922024-11-23 14:01:57 +01006003
6004 // we need up to 2 extra chars for the prefix
6005 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
6006 compl_pattern.string = alloc(n);
6007 if (compl_pattern.string == NULL)
6008 {
6009 compl_pattern.length = 0;
6010 return FAIL;
6011 }
6012 STRCPY((char *)compl_pattern.string, prefix);
6013 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006014 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006015 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006016 }
6017 else if (--startcol < 0
6018 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
6019 {
John Marriott5e6ea922024-11-23 14:01:57 +01006020 size_t len = STRLEN_LITERAL("\\<\\k\\k");
6021
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006022 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01006023 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
6024 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006025 {
John Marriott5e6ea922024-11-23 14:01:57 +01006026 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006027 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006028 }
John Marriott5e6ea922024-11-23 14:01:57 +01006029 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006030 compl_col += curs_col;
6031 compl_length = 0;
6032 }
6033 else
6034 {
6035 // Search the point of change class of multibyte character
6036 // or not a word single byte character backward.
6037 if (has_mbyte)
6038 {
6039 int base_class;
6040 int head_off;
6041
6042 startcol -= (*mb_head_off)(line, line + startcol);
6043 base_class = mb_get_class(line + startcol);
6044 while (--startcol >= 0)
6045 {
6046 head_off = (*mb_head_off)(line, line + startcol);
6047 if (base_class != mb_get_class(line + startcol
6048 - head_off))
6049 break;
6050 startcol -= head_off;
6051 }
6052 }
6053 else
glepnir19e1dd62025-05-08 22:50:38 +02006054 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006055 while (--startcol >= 0 && vim_iswordc(line[startcol]))
6056 ;
glepnir19e1dd62025-05-08 22:50:38 +02006057 }
6058
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006059 compl_col += ++startcol;
6060 compl_length = (int)curs_col - startcol;
6061 if (compl_length == 1)
6062 {
6063 // Only match word with at least two chars -- webb
6064 // there's no need to call quote_meta,
6065 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01006066 compl_pattern.string = alloc(7);
6067 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006068 {
John Marriott5e6ea922024-11-23 14:01:57 +01006069 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006070 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006071 }
John Marriott5e6ea922024-11-23 14:01:57 +01006072 STRCPY((char *)compl_pattern.string, "\\<");
6073 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
6074 STRCAT((char *)compl_pattern.string, "\\k");
6075 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006076 }
6077 else
6078 {
John Marriott5e6ea922024-11-23 14:01:57 +01006079 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6080
6081 compl_pattern.string = alloc(n);
6082 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006083 {
John Marriott5e6ea922024-11-23 14:01:57 +01006084 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006085 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006086 }
John Marriott5e6ea922024-11-23 14:01:57 +01006087 STRCPY((char *)compl_pattern.string, "\\<");
6088 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006089 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006090 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006091 }
6092 }
6093
6094 return OK;
6095}
6096
6097/*
6098 * Get the pattern, column and length for whole line completion or for the
6099 * complete() function.
6100 * Sets the global variables: compl_col, compl_length and compl_pattern.
6101 */
6102 static int
6103get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6104{
6105 compl_col = (colnr_T)getwhitecols(line);
6106 compl_length = (int)curs_col - (int)compl_col;
6107 if (compl_length < 0) // cursor in indent: empty pattern
6108 compl_length = 0;
6109 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006110 {
John Marriott5e6ea922024-11-23 14:01:57 +01006111 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6112 NULL, 0);
6113 if (compl_pattern.string == NULL)
6114 {
6115 compl_pattern.length = 0;
6116 return FAIL;
6117 }
6118 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006119 }
John Marriott5e6ea922024-11-23 14:01:57 +01006120 else
6121 {
6122 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6123 if (compl_pattern.string == NULL)
6124 {
6125 compl_pattern.length = 0;
6126 return FAIL;
6127 }
6128 compl_pattern.length = (size_t)compl_length;
6129 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006130
6131 return OK;
6132}
6133
6134/*
6135 * Get the pattern, column and length for filename completion.
6136 * Sets the global variables: compl_col, compl_length and compl_pattern.
6137 */
6138 static int
6139get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6140{
6141 // Go back to just before the first filename character.
6142 if (startcol > 0)
6143 {
6144 char_u *p = line + startcol;
6145
6146 MB_PTR_BACK(line, p);
6147 while (p > line && vim_isfilec(PTR2CHAR(p)))
6148 MB_PTR_BACK(line, p);
6149 if (p == line && vim_isfilec(PTR2CHAR(p)))
6150 startcol = 0;
6151 else
6152 startcol = (int)(p - line) + 1;
6153 }
6154
6155 compl_col += startcol;
6156 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006157 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6158 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006159 {
John Marriott5e6ea922024-11-23 14:01:57 +01006160 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006161 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006162 }
6163
John Marriott5e6ea922024-11-23 14:01:57 +01006164 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006165
6166 return OK;
6167}
6168
6169/*
6170 * Get the pattern, column and length for command-line completion.
6171 * Sets the global variables: compl_col, compl_length and compl_pattern.
6172 */
6173 static int
6174get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6175{
John Marriott5e6ea922024-11-23 14:01:57 +01006176 compl_pattern.string = vim_strnsave(line, curs_col);
6177 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006178 {
John Marriott5e6ea922024-11-23 14:01:57 +01006179 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006180 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006181 }
John Marriott5e6ea922024-11-23 14:01:57 +01006182 compl_pattern.length = curs_col;
6183 set_cmd_context(&compl_xp, compl_pattern.string,
6184 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006185 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6186 || compl_xp.xp_context == EXPAND_NOTHING)
6187 // No completion possible, use an empty pattern to get a
6188 // "pattern not found" message.
6189 compl_col = curs_col;
6190 else
John Marriott5e6ea922024-11-23 14:01:57 +01006191 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006192 compl_length = curs_col - compl_col;
6193
6194 return OK;
6195}
6196
Girish Palya98c29db2025-06-01 19:40:00 +02006197#ifdef FEAT_COMPL_FUNC
6198/*
6199 * Set global variables related to completion:
6200 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6201 */
6202 static int
6203set_compl_globals(
6204 int startcol UNUSED,
6205 colnr_T curs_col UNUSED,
6206 int is_cpt_compl UNUSED)
6207{
6208 char_u *line = NULL;
6209 string_T *pattern = NULL;
6210 int len;
6211
6212 if (startcol < 0 || startcol > curs_col)
6213 startcol = curs_col;
6214 len = curs_col - startcol;
6215
6216 // Re-obtain line in case it has changed
6217 line = ml_get(curwin->w_cursor.lnum);
6218
6219 pattern = is_cpt_compl ? &cpt_compl_pattern : &compl_pattern;
6220 pattern->string = vim_strnsave(line + startcol, (size_t)len);
6221 if (pattern->string == NULL)
6222 {
6223 pattern->length = 0;
6224 return FAIL;
6225 }
6226 pattern->length = (size_t)len;
6227 if (!is_cpt_compl)
6228 {
6229 compl_col = startcol;
6230 compl_length = len;
6231 }
6232 return OK;
6233}
6234#endif
6235
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006236/*
6237 * Get the pattern, column and length for user defined completion ('omnifunc',
6238 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006239 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006240 * Callback function "cb" is set if triggered by a function in the 'cpt'
6241 * option; otherwise, it is NULL.
6242 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006243 */
6244 static int
glepnir19e1dd62025-05-08 22:50:38 +02006245get_userdefined_compl_info(
6246 colnr_T curs_col UNUSED,
6247 callback_T *cb UNUSED,
6248 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006249{
6250 int ret = FAIL;
6251
6252#ifdef FEAT_COMPL_FUNC
6253 // Call user defined function 'completefunc' with "a:findstart"
6254 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006255 typval_T args[3];
6256 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006257 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006258 pos_T pos;
6259 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006260 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006261
Girish Palyacbe53192025-04-14 22:13:15 +02006262 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006263 {
Girish Palyacbe53192025-04-14 22:13:15 +02006264 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6265 // length as a string
6266 funcname = get_complete_funcname(ctrl_x_mode);
6267 if (*funcname == NUL)
6268 {
6269 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6270 ? "completefunc" : "omnifunc");
6271 return FAIL;
6272 }
6273 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006274 }
6275
6276 args[0].v_type = VAR_NUMBER;
6277 args[0].vval.v_number = 1;
6278 args[1].v_type = VAR_STRING;
6279 args[1].vval.v_string = (char_u *)"";
6280 args[2].v_type = VAR_UNKNOWN;
6281 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006282 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006283 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006284 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006285
6286 State = save_State;
6287 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006288 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006289 validate_cursor();
6290 if (!EQUAL_POS(curwin->w_cursor, pos))
6291 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006292 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006293 return FAIL;
6294 }
6295
Girish Palyacbe53192025-04-14 22:13:15 +02006296 if (startcol != NULL)
6297 *startcol = col;
6298
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006299 // Return value -2 means the user complete function wants to cancel the
6300 // complete without an error, do the same if the function did not execute
6301 // successfully.
6302 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006303 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006304
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006305 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006306 if (col == -3)
6307 {
Girish Palyacbe53192025-04-14 22:13:15 +02006308 if (is_cpt_function)
6309 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006310 ctrl_x_mode = CTRL_X_NORMAL;
6311 edit_submode = NULL;
6312 if (!shortmess(SHM_COMPLETIONMENU))
6313 msg_clr_cmdline();
6314 return FAIL;
6315 }
6316
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006317 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006318 // completion.
6319 compl_opt_refresh_always = FALSE;
6320 compl_opt_suppress_empty = FALSE;
6321
Girish Palya98c29db2025-06-01 19:40:00 +02006322 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006323#endif
6324
6325 return ret;
6326}
6327
6328/*
6329 * Get the pattern, column and length for spell completion.
6330 * Sets the global variables: compl_col, compl_length and compl_pattern.
6331 * Uses the global variable: spell_bad_len
6332 */
6333 static int
6334get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6335{
6336 int ret = FAIL;
6337#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006338 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006339
6340 if (spell_bad_len > 0)
6341 compl_col = curs_col - spell_bad_len;
6342 else
6343 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006344
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006345 if (compl_col >= (colnr_T)startcol)
6346 {
6347 compl_length = 0;
6348 compl_col = curs_col;
6349 }
6350 else
6351 {
6352 spell_expand_check_cap(compl_col);
6353 compl_length = (int)curs_col - compl_col;
6354 }
6355 // Need to obtain "line" again, it may have become invalid.
6356 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006357 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6358 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006359 {
John Marriott5e6ea922024-11-23 14:01:57 +01006360 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006361 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006362 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006363
John Marriott5e6ea922024-11-23 14:01:57 +01006364 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006365 ret = OK;
6366#endif
6367
6368 return ret;
6369}
6370
6371/*
6372 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006373 * "startcol" - start column number of the completion pattern/text
6374 * "cur_col" - current cursor column
6375 * On return, "line_invalid" is set to TRUE, if the current line may have
6376 * become invalid and needs to be fetched again.
6377 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006378 */
6379 static int
6380compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6381{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006382 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006383 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6384 && !thesaurus_func_complete(ctrl_x_mode)))
6385 {
6386 return get_normal_compl_info(line, startcol, curs_col);
6387 }
6388 else if (ctrl_x_mode_line_or_eval())
6389 {
6390 return get_wholeline_compl_info(line, curs_col);
6391 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006392 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006393 {
6394 return get_filename_compl_info(line, startcol, curs_col);
6395 }
6396 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6397 {
6398 return get_cmdline_compl_info(line, curs_col);
6399 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006400 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006401 || thesaurus_func_complete(ctrl_x_mode))
6402 {
Girish Palyacbe53192025-04-14 22:13:15 +02006403 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006404 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006405 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006406 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006407 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006408 {
6409 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6410 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006411 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006412 }
glepnir05460682025-05-26 18:23:27 +02006413 else if (ctrl_x_mode_register())
6414 {
6415 return get_normal_compl_info(line, startcol, curs_col);
6416 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006417 else
6418 {
6419 internal_error("ins_complete()");
6420 return FAIL;
6421 }
6422
6423 return OK;
6424}
6425
6426/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006427 * Continue an interrupted completion mode search in "line".
6428 *
6429 * If this same ctrl_x_mode has been interrupted use the text from
6430 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6431 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6432 * the same line as the cursor then fix it (the line has been split because it
6433 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6434 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006435 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006436 static void
6437ins_compl_continue_search(char_u *line)
6438{
6439 // it is a continued search
6440 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006441 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6442 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006443 {
6444 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6445 {
6446 // line (probably) wrapped, set compl_startpos to the
6447 // first non_blank in the line, if it is not a wordchar
6448 // include it to get a better pattern, but then we don't
6449 // want the "\\<" prefix, check it below
6450 compl_col = (colnr_T)getwhitecols(line);
6451 compl_startpos.col = compl_col;
6452 compl_startpos.lnum = curwin->w_cursor.lnum;
6453 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6454 }
6455 else
6456 {
6457 // S_IPOS was set when we inserted a word that was at the
6458 // beginning of the line, which means that we'll go to SOL
6459 // mode but first we need to redefine compl_startpos
6460 if (compl_cont_status & CONT_S_IPOS)
6461 {
6462 compl_cont_status |= CONT_SOL;
6463 compl_startpos.col = (colnr_T)(skipwhite(
6464 line + compl_length
6465 + compl_startpos.col) - line);
6466 }
6467 compl_col = compl_startpos.col;
6468 }
6469 compl_length = curwin->w_cursor.col - (int)compl_col;
6470 // IObuff is used to add a "word from the next line" would we
6471 // have enough space? just being paranoid
6472#define MIN_SPACE 75
6473 if (compl_length > (IOSIZE - MIN_SPACE))
6474 {
6475 compl_cont_status &= ~CONT_SOL;
6476 compl_length = (IOSIZE - MIN_SPACE);
6477 compl_col = curwin->w_cursor.col - compl_length;
6478 }
6479 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6480 if (compl_length < 1)
6481 compl_cont_status &= CONT_LOCAL;
6482 }
6483 else if (ctrl_x_mode_line_or_eval())
6484 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6485 else
6486 compl_cont_status = 0;
6487}
6488
6489/*
6490 * start insert mode completion
6491 */
6492 static int
6493ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006494{
glepnir19e1dd62025-05-08 22:50:38 +02006495 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006496 int startcol = 0; // column where searched text starts
6497 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006498 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006499 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006500 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006501
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006502 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006503 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006504 did_si = FALSE;
6505 can_si = FALSE;
6506 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006507 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006508 return FAIL;
6509
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006510 line = ml_get(curwin->w_cursor.lnum);
6511 curs_col = curwin->w_cursor.col;
6512 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006513 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006514
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006515 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6516 && compl_cont_mode == ctrl_x_mode)
6517 // this same ctrl-x_mode was interrupted previously. Continue the
6518 // completion.
6519 ins_compl_continue_search(line);
6520 else
6521 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006522
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006523 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006524 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006525 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006526 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006527 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6528 compl_cont_status = 0;
6529 compl_cont_status |= CONT_N_ADDS;
6530 compl_startpos = curwin->w_cursor;
6531 startcol = (int)curs_col;
6532 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006533 }
6534
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006535 // Work out completion pattern and original text -- webb
6536 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6537 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006538 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6539 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006540 // restore did_ai, so that adding comment leader works
6541 did_ai = save_did_ai;
6542 return FAIL;
6543 }
6544 // If "line" was changed while getting completion info get it again.
6545 if (line_invalid)
6546 line = ml_get(curwin->w_cursor.lnum);
6547
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006548 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006549 {
6550 edit_submode_pre = (char_u *)_(" Adding");
6551 if (ctrl_x_mode_line_or_eval())
6552 {
6553 // Insert a new line, keep indentation but ignore 'comments'.
6554 char_u *old = curbuf->b_p_com;
6555
6556 curbuf->b_p_com = (char_u *)"";
6557 compl_startpos.lnum = curwin->w_cursor.lnum;
6558 compl_startpos.col = compl_col;
6559 ins_eol('\r');
6560 curbuf->b_p_com = old;
6561 compl_length = 0;
6562 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006563 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006564 }
glepnircfe502c2025-04-17 20:17:53 +02006565 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006566 {
6567 compl_startpos = curwin->w_cursor;
6568 compl_cont_status &= CONT_S_IPOS;
6569 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006570 }
6571 else
6572 {
6573 edit_submode_pre = NULL;
6574 compl_startpos.col = compl_col;
6575 }
6576
6577 if (compl_cont_status & CONT_LOCAL)
6578 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6579 else
6580 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6581
6582 // If any of the original typed text has been changed we need to fix
6583 // the redo buffer.
6584 ins_compl_fixRedoBufForLeader(NULL);
6585
6586 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006587 VIM_CLEAR_STRING(compl_orig_text);
6588 compl_orig_text.length = (size_t)compl_length;
6589 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006590 if (p_ic)
6591 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006592 if (compl_orig_text.string == NULL
6593 || ins_compl_add(compl_orig_text.string,
6594 (int)compl_orig_text.length,
6595 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006596 {
John Marriott5e6ea922024-11-23 14:01:57 +01006597 VIM_CLEAR_STRING(compl_pattern);
6598 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006599 return FAIL;
6600 }
6601
6602 // showmode might reset the internal line pointers, so it must
6603 // be called before line = ml_get(), or when this address is no
6604 // longer needed. -- Acevedo.
6605 edit_submode_extra = (char_u *)_("-- Searching...");
6606 edit_submode_highl = HLF_COUNT;
6607 showmode();
6608 edit_submode_extra = NULL;
6609 out_flush();
6610
6611 return OK;
6612}
6613
6614/*
6615 * display the completion status message
6616 */
6617 static void
6618ins_compl_show_statusmsg(void)
6619{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006620 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006621 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006622 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006623 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006624 ? (char_u *)_("Hit end of paragraph")
6625 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006626 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006627 }
6628
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006629 if (edit_submode_extra == NULL)
6630 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006631 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006632 {
6633 edit_submode_extra = (char_u *)_("Back at original");
6634 edit_submode_highl = HLF_W;
6635 }
6636 else if (compl_cont_status & CONT_S_IPOS)
6637 {
6638 edit_submode_extra = (char_u *)_("Word from other line");
6639 edit_submode_highl = HLF_COUNT;
6640 }
6641 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6642 {
6643 edit_submode_extra = (char_u *)_("The only match");
6644 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006645 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006646 }
6647 else
6648 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006649#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006650 // Update completion sequence number when needed.
6651 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006652 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006653#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006654 // The match should always have a sequence number now, this is
6655 // just a safety check.
6656 if (compl_curr_match->cp_number != -1)
6657 {
6658 // Space for 10 text chars. + 2x10-digit no.s = 31.
6659 // Translations may need more than twice that.
6660 static char_u match_ref[81];
6661
6662 if (compl_matches > 0)
6663 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006664 _("match %d of %d"),
6665 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006666 else
6667 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006668 _("match %d"),
6669 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006670 edit_submode_extra = match_ref;
6671 edit_submode_highl = HLF_R;
6672 if (dollar_vcol >= 0)
6673 curs_columns(FALSE);
6674 }
6675 }
6676 }
6677
6678 // Show a message about what (completion) mode we're in.
6679 if (!compl_opt_suppress_empty)
6680 {
6681 showmode();
6682 if (!shortmess(SHM_COMPLETIONMENU))
6683 {
6684 if (edit_submode_extra != NULL)
6685 {
6686 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006687 {
6688 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006689 msg_attr((char *)edit_submode_extra,
6690 edit_submode_highl < HLF_COUNT
6691 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006692 msg_hist_off = FALSE;
6693 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006694 }
6695 else
6696 msg_clr_cmdline(); // necessary for "noshowmode"
6697 }
6698 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006699}
6700
6701/*
6702 * Do Insert mode completion.
6703 * Called when character "c" was typed, which has a meaning for completion.
6704 * Returns OK if completion was done, FAIL if something failed (out of mem).
6705 */
6706 int
6707ins_complete(int c, int enable_pum)
6708{
6709 int n;
6710 int save_w_wrow;
6711 int save_w_leftcol;
6712 int insert_match;
6713
6714 compl_direction = ins_compl_key2dir(c);
6715 insert_match = ins_compl_use_match(c);
6716
6717 if (!compl_started)
6718 {
6719 if (ins_compl_start() == FAIL)
6720 return FAIL;
6721 }
6722 else if (insert_match && stop_arrow() == FAIL)
6723 return FAIL;
6724
glepnircf7f0122025-04-15 19:02:00 +02006725 compl_curr_win = curwin;
6726 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006727 compl_shown_match = compl_curr_match;
6728 compl_shows_dir = compl_direction;
6729
6730 // Find next match (and following matches).
6731 save_w_wrow = curwin->w_wrow;
6732 save_w_leftcol = curwin->w_leftcol;
6733 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6734
6735 // may undisplay the popup menu
6736 ins_compl_upd_pum();
6737
6738 if (n > 1) // all matches have been found
6739 compl_matches = n;
6740 compl_curr_match = compl_shown_match;
6741 compl_direction = compl_shows_dir;
6742
6743 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6744 // mode.
6745 if (got_int && !global_busy)
6746 {
6747 (void)vgetc();
6748 got_int = FALSE;
6749 }
6750
6751 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006752 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006753 {
6754 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6755 // because we couldn't expand anything at first place, but if we used
6756 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6757 // (such as M in M'exico) if not tried already. -- Acevedo
6758 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006759 || compl_status_adding()
6760 || (ctrl_x_mode_not_default()
6761 && !ctrl_x_mode_path_patterns()
6762 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006763 compl_cont_status &= ~CONT_N_ADDS;
6764 }
6765
6766 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6767 compl_cont_status |= CONT_S_IPOS;
6768 else
6769 compl_cont_status &= ~CONT_S_IPOS;
6770
6771 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006772
6773 // Show the popup menu, unless we got interrupted.
6774 if (enable_pum && !compl_interrupted)
6775 show_pum(save_w_wrow, save_w_leftcol);
6776
6777 compl_was_interrupted = compl_interrupted;
6778 compl_interrupted = FALSE;
6779
6780 return OK;
6781}
6782
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006783/*
6784 * Remove (if needed) and show the popup menu
6785 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006786 static void
6787show_pum(int prev_w_wrow, int prev_w_leftcol)
6788{
6789 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006790 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006791 RedrawingDisabled = 0;
6792
6793 // If the cursor moved or the display scrolled we need to remove the pum
6794 // first.
6795 setcursor();
6796 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6797 ins_compl_del_pum();
6798
6799 ins_compl_show_pum();
6800 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006801
6802 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006803}
6804
6805/*
6806 * Looks in the first "len" chars. of "src" for search-metachars.
6807 * If dest is not NULL the chars. are copied there quoting (with
6808 * a backslash) the metachars, and dest would be NUL terminated.
6809 * Returns the length (needed) of dest
6810 */
6811 static unsigned
6812quote_meta(char_u *dest, char_u *src, int len)
6813{
6814 unsigned m = (unsigned)len + 1; // one extra for the NUL
6815
6816 for ( ; --len >= 0; src++)
6817 {
6818 switch (*src)
6819 {
6820 case '.':
6821 case '*':
6822 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006823 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006824 break;
6825 // FALLTHROUGH
6826 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006827 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006828 break;
6829 // FALLTHROUGH
6830 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006831 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006832 break;
6833 // FALLTHROUGH
6834 case '^': // currently it's not needed.
6835 case '$':
6836 m++;
6837 if (dest != NULL)
6838 *dest++ = '\\';
6839 break;
6840 }
6841 if (dest != NULL)
6842 *dest++ = *src;
6843 // Copy remaining bytes of a multibyte character.
6844 if (has_mbyte)
6845 {
glepnir19e1dd62025-05-08 22:50:38 +02006846 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006847 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006848 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006849 {
6850 --len;
6851 ++src;
6852 if (dest != NULL)
6853 *dest++ = *src;
6854 }
6855 }
6856 }
6857 if (dest != NULL)
6858 *dest = NUL;
6859
6860 return m;
6861}
6862
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006863#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006864 void
6865free_insexpand_stuff(void)
6866{
John Marriott5e6ea922024-11-23 14:01:57 +01006867 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006868# ifdef FEAT_EVAL
6869 free_callback(&cfu_cb);
6870 free_callback(&ofu_cb);
6871 free_callback(&tsrfu_cb);
6872# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006873}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006874#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006875
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006876#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006877/*
6878 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6879 * spelled word, if there is one.
6880 */
6881 static void
6882spell_back_to_badword(void)
6883{
6884 pos_T tpos = curwin->w_cursor;
6885
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006886 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006887 if (curwin->w_cursor.col != tpos.col)
6888 start_arrow(&tpos);
6889}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006890#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006891
6892/*
6893 * Reset the info associated with completion sources.
6894 */
6895 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006896cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006897{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006898 VIM_CLEAR(cpt_sources_array);
6899 cpt_sources_index = -1;
6900 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006901}
6902
6903/*
Girish Palya98c29db2025-06-01 19:40:00 +02006904 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006905 */
6906 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006907setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006908{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006909 char_u buf[LSIZE];
6910 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006911 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006912 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006913
Girish Palya0ac1eb32025-04-16 20:18:33 +02006914 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006915 {
6916 while (*p == ',' || *p == ' ') // Skip delimiters
6917 p++;
6918 if (*p) // If not end of string, count this segment
6919 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006920 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006921 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006922 }
6923 }
Girish Palya98c29db2025-06-01 19:40:00 +02006924 if (count == 0)
6925 return OK;
6926
Girish Palya0ac1eb32025-04-16 20:18:33 +02006927 cpt_sources_clear();
6928 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006929 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6930 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006931 {
Girish Palya98c29db2025-06-01 19:40:00 +02006932 cpt_sources_count = 0;
6933 return FAIL;
6934 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006935
Girish Palya98c29db2025-06-01 19:40:00 +02006936 for (p = curbuf->b_p_cpt; *p;)
6937 {
6938 while (*p == ',' || *p == ' ') // Skip delimiters
6939 p++;
6940 if (*p) // If not end of string, count this segment
6941 {
6942 char_u *t;
6943
6944 vim_memset(buf, 0, LSIZE);
6945 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6946 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
6947 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
6948 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006949 }
Girish Palyacbe53192025-04-14 22:13:15 +02006950 }
6951 return OK;
6952}
6953
6954/*
6955 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6956 */
6957 static int
6958is_cpt_func_refresh_always(void)
6959{
6960#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02006961 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02006962 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02006963 return TRUE;
6964#endif
6965 return FALSE;
6966}
6967
6968/*
6969 * Make the completion list non-cyclic.
6970 */
6971#ifdef FEAT_COMPL_FUNC
6972 static void
6973ins_compl_make_linear(void)
6974{
6975 compl_T *m;
6976
6977 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6978 return;
6979 m = compl_first_match->cp_prev;
6980 m->cp_next = NULL;
6981 compl_first_match->cp_prev = NULL;
6982}
6983#endif
6984
6985/*
6986 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02006987 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02006988 */
6989#ifdef FEAT_COMPL_FUNC
6990 static compl_T *
6991remove_old_matches(void)
6992{
6993 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6994 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006995 int compl_shown_removed = FALSE;
6996 int forward = (compl_first_match->cp_cpt_source_idx < 0);
6997
6998 compl_direction = forward ? FORWARD : BACKWARD;
6999 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02007000
7001 // Identify the sublist of old matches that needs removal
7002 for (current = compl_first_match; current != NULL; current = current->cp_next)
7003 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02007004 if (current->cp_cpt_source_idx < cpt_sources_index &&
7005 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02007006 insert_at = current;
7007
Girish Palya0ac1eb32025-04-16 20:18:33 +02007008 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02007009 {
7010 if (!sublist_start)
7011 sublist_start = current;
7012 sublist_end = current;
7013 if (!compl_shown_removed && compl_shown_match == current)
7014 compl_shown_removed = TRUE;
7015 }
7016
Girish Palya0ac1eb32025-04-16 20:18:33 +02007017 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
7018 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02007019 break;
7020 }
7021
7022 // Re-assign compl_shown_match if necessary
7023 if (compl_shown_removed)
7024 {
7025 if (forward)
7026 compl_shown_match = compl_first_match;
7027 else
7028 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02007029 for (current = compl_first_match; current->cp_next != NULL;
7030 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02007031 ;
7032 compl_shown_match = current;
7033 }
7034 }
7035
7036 if (!sublist_start) // No nodes to remove
7037 return insert_at;
7038
7039 // Update links to remove sublist
7040 if (sublist_start->cp_prev)
7041 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
7042 else
7043 compl_first_match = sublist_end->cp_next;
7044
7045 if (sublist_end->cp_next)
7046 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
7047
7048 // Free all nodes in the sublist
7049 sublist_end->cp_next = NULL;
7050 for (current = sublist_start; current != NULL; current = next)
7051 {
7052 next = current->cp_next;
7053 ins_compl_item_free(current);
7054 }
7055
7056 return insert_at;
7057}
7058#endif
7059
7060/*
7061 * Retrieve completion matches using the callback function "cb" and store the
7062 * 'refresh:always' flag.
7063 */
7064#ifdef FEAT_COMPL_FUNC
7065 static void
7066get_cpt_func_completion_matches(callback_T *cb UNUSED)
7067{
Girish Palya98c29db2025-06-01 19:40:00 +02007068 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palyacbe53192025-04-14 22:13:15 +02007069
7070 VIM_CLEAR_STRING(cpt_compl_pattern);
Girish Palya98c29db2025-06-01 19:40:00 +02007071
7072 if (startcol == -2 || startcol == -3)
7073 return;
7074
7075 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02007076 {
7077 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02007078 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02007079 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02007080 compl_opt_refresh_always = FALSE;
7081 }
7082}
7083#endif
7084
7085/*
7086 * Retrieve completion matches from functions in the 'cpt' option where the
7087 * 'refresh:always' flag is set.
7088 */
7089 static void
7090cpt_compl_refresh(void)
7091{
7092#ifdef FEAT_COMPL_FUNC
7093 char_u *cpt;
7094 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007095 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007096 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007097
7098 // Make the completion list linear (non-cyclic)
7099 ins_compl_make_linear();
7100 // Make a copy of 'cpt' in case the buffer gets wiped out
7101 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007102 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007103
Girish Palya0ac1eb32025-04-16 20:18:33 +02007104 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007105 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007106 {
7107 while (*p == ',' || *p == ' ') // Skip delimiters
7108 p++;
7109
Girish Palya98c29db2025-06-01 19:40:00 +02007110 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007111 {
Girish Palya98c29db2025-06-01 19:40:00 +02007112 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007113 if (cb)
7114 {
7115 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007116 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7117 &startcol);
7118 if (ret == FAIL)
7119 {
7120 if (startcol == -3)
7121 cpt_sources_array[cpt_sources_index].cs_refresh_always
7122 = FALSE;
7123 else
7124 startcol = -2;
7125 }
7126 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7127 if (ret == OK)
7128 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007129 }
7130 }
7131
Girish Palya7c621052025-05-26 19:41:59 +02007132 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7133 if (may_advance_cpt_index(p))
7134 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007135 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007136 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007137
7138 vim_free(cpt);
7139 // Make the list cyclic
7140 compl_matches = ins_compl_make_cyclic();
7141#endif
7142}