blob: 3b9494bb216dcb412fe21e1afc20ffd537e971c8 [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
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020061 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010062 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010091 * Structure used to store one match for insert completion.
92 */
93typedef struct compl_S compl_T;
94struct compl_S
95{
96 compl_T *cp_next;
97 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +010098 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +010099 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200100 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100101#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100102 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100103#endif
glepnir0fe17f82024-10-08 22:26:44 +0200104 char_u *cp_fname; // file containing the match, allocated when
105 // cp_flags has CP_FREE_FNAME
106 int cp_flags; // CP_ values
107 int cp_number; // sequence number
108 int cp_score; // fuzzy match score
glepnird4088ed2024-12-31 10:55:22 +0100109 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200110 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200111 int cp_user_kind_hlattr; // highlight attribute for kind
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100112};
113
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200114// values for cp_flags
115# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
116# define CP_FREE_FNAME 2 // cp_fname is allocated
117# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
118# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
119# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200120# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100121
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100122/*
123 * All the current matches are stored in a list.
124 * "compl_first_match" points to the start of the list.
125 * "compl_curr_match" points to the currently selected entry.
126 * "compl_shown_match" is different from compl_curr_match during
127 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000128 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100129 */
130static compl_T *compl_first_match = NULL;
131static compl_T *compl_curr_match = NULL;
132static compl_T *compl_shown_match = NULL;
133static compl_T *compl_old_match = NULL;
134
135// After using a cursor key <Enter> selects a match in the popup menu,
136// otherwise it inserts a line break.
137static int compl_enter_selects = FALSE;
138
139// When "compl_leader" is not NULL only matches that start with this string
140// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100141static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100142
143static int compl_get_longest = FALSE; // put longest common string
144 // in compl_leader
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// Selected one of the matches. When FALSE the match was edited or using the
147// longest common string.
148static int compl_used_match;
149
150// didn't finish finding completions.
151static int compl_was_interrupted = FALSE;
152
153// Set when character typed while looking for matches and it means we should
154// stop looking for matches.
155static int compl_interrupted = FALSE;
156
157static int compl_restarting = FALSE; // don't insert match
158
159// When the first completion is done "compl_started" is set. When it's
160// FALSE the word to be completed must be located.
161static int compl_started = FALSE;
162
163// Which Ctrl-X mode are we in?
164static int ctrl_x_mode = CTRL_X_NORMAL;
165
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000166static int compl_matches = 0; // number of completion matches
John Marriott5e6ea922024-11-23 14:01:57 +0100167static string_T compl_pattern = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100168static int compl_direction = FORWARD;
169static int compl_shows_dir = FORWARD;
170static int compl_pending = 0; // > 1 for postponed CTRL-N
171static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000172// Length in bytes of the text being completed (this is deleted to be replaced
173// by the match.)
174static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100175static colnr_T compl_col = 0; // column where the text starts
176 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100177static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100178static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100179 // completion started
180static int compl_cont_mode = 0;
181static expand_T compl_xp;
182
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000183// List of flags for method of completion.
184static int compl_cont_status = 0;
185# define CONT_ADDING 1 // "normal" or "adding" expansion
186# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
187 // it's set only iff N_ADDS is set
188# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
189# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
190 // if so, word-wise-expansion will set SOL
191# define CONT_SOL 16 // pattern includes start of line, just for
192 // word-wise expansion, not set for ^X^L
193# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
194 // expansion, (eg use complete=.)
195
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100196static int compl_opt_refresh_always = FALSE;
197static int compl_opt_suppress_empty = FALSE;
198
glepnira218cc62024-06-03 19:32:39 +0200199static int compl_selected_item = -1;
200
glepnir8159fb12024-07-17 20:32:54 +0200201static int *compl_fuzzy_scores;
202
glepnir6a38aff2024-12-16 21:56:16 +0100203// "compl_match_array" points the currently displayed list of entries in the
204// popup menu. It is NULL when there is no popup menu.
205static pumitem_T *compl_match_array = NULL;
206static int compl_match_arraysize;
207
glepnir80b66202024-11-27 21:53:53 +0100208static 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);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100209static void ins_compl_longest_match(compl_T *match);
210static void ins_compl_del_pum(void);
211static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
212static char_u *find_line_end(char_u *ptr);
213static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100214static int ins_compl_need_restart(void);
215static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000216static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100217static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100218static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100219static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
220# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
221static void ins_compl_add_list(list_T *list);
222static void ins_compl_add_dict(dict_T *dict);
223# endif
224static int ins_compl_key2dir(int c);
225static int ins_compl_pum_key(int c);
226static int ins_compl_key2count(int c);
227static void show_pum(int prev_w_wrow, int prev_w_leftcol);
228static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100229
230#ifdef FEAT_SPELL
231static void spell_back_to_badword(void);
232static int spell_bad_len = 0; // length of located bad word
233#endif
234
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100235/*
236 * CTRL-X pressed in Insert mode.
237 */
238 void
239ins_ctrl_x(void)
240{
zeertzjqdca29d92021-08-31 19:12:51 +0200241 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000243 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100244 if (compl_cont_status & CONT_N_ADDS)
245 compl_cont_status |= CONT_INTRPT;
246 else
247 compl_cont_status = 0;
248 // We're not sure which CTRL-X mode it will be yet
249 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
250 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
251 edit_submode_pre = NULL;
252 showmode();
253 }
zeertzjqdca29d92021-08-31 19:12:51 +0200254 else
255 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
256 // CTRL-V look like CTRL-N
257 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100258
LemonBoy2bf52dd2022-04-09 18:17:34 +0100259 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100260}
261
262/*
263 * Functions to check the current CTRL-X mode.
264 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000265int ctrl_x_mode_none(void)
266 { return ctrl_x_mode == 0; }
267int ctrl_x_mode_normal(void)
268 { return ctrl_x_mode == CTRL_X_NORMAL; }
269int ctrl_x_mode_scroll(void)
270 { return ctrl_x_mode == CTRL_X_SCROLL; }
271int ctrl_x_mode_whole_line(void)
272 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
273int ctrl_x_mode_files(void)
274 { return ctrl_x_mode == CTRL_X_FILES; }
275int ctrl_x_mode_tags(void)
276 { return ctrl_x_mode == CTRL_X_TAGS; }
277int ctrl_x_mode_path_patterns(void)
278 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
279int ctrl_x_mode_path_defines(void)
280 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
281int ctrl_x_mode_dictionary(void)
282 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
283int ctrl_x_mode_thesaurus(void)
284 { return ctrl_x_mode == CTRL_X_THESAURUS; }
285int ctrl_x_mode_cmdline(void)
286 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200287 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000288int ctrl_x_mode_function(void)
289 { return ctrl_x_mode == CTRL_X_FUNCTION; }
290int ctrl_x_mode_omni(void)
291 { return ctrl_x_mode == CTRL_X_OMNI; }
292int ctrl_x_mode_spell(void)
293 { return ctrl_x_mode == CTRL_X_SPELL; }
294static int ctrl_x_mode_eval(void)
295 { return ctrl_x_mode == CTRL_X_EVAL; }
296int ctrl_x_mode_line_or_eval(void)
297 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100298
299/*
300 * Whether other than default completion has been selected.
301 */
302 int
303ctrl_x_mode_not_default(void)
304{
305 return ctrl_x_mode != CTRL_X_NORMAL;
306}
307
308/*
zeertzjqdca29d92021-08-31 19:12:51 +0200309 * Whether CTRL-X was typed without a following character,
310 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100311 */
312 int
313ctrl_x_mode_not_defined_yet(void)
314{
315 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
316}
317
318/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000319 * Return TRUE if currently in "normal" or "adding" insert completion matches
320 * state
321 */
322 int
323compl_status_adding(void)
324{
325 return compl_cont_status & CONT_ADDING;
326}
327
328/*
329 * Return TRUE if the completion pattern includes start of line, just for
330 * word-wise expansion.
331 */
332 int
333compl_status_sol(void)
334{
335 return compl_cont_status & CONT_SOL;
336}
337
338/*
339 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
340 */
341 int
342compl_status_local(void)
343{
344 return compl_cont_status & CONT_LOCAL;
345}
346
347/*
348 * Clear the completion status flags
349 */
350 void
351compl_status_clear(void)
352{
353 compl_cont_status = 0;
354}
355
356/*
357 * Return TRUE if completion is using the forward direction matches
358 */
359 static int
360compl_dir_forward(void)
361{
362 return compl_direction == FORWARD;
363}
364
365/*
366 * Return TRUE if currently showing forward completion matches
367 */
368 static int
369compl_shows_dir_forward(void)
370{
371 return compl_shows_dir == FORWARD;
372}
373
374/*
375 * Return TRUE if currently showing backward completion matches
376 */
377 static int
378compl_shows_dir_backward(void)
379{
380 return compl_shows_dir == BACKWARD;
381}
382
383/*
384 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100385 */
386 int
387has_compl_option(int dict_opt)
388{
389 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200390#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100391 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200392#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100393 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100394 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
395#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100396 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100397#endif
398 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100399 {
400 ctrl_x_mode = CTRL_X_NORMAL;
401 edit_submode = NULL;
402 msg_attr(dict_opt ? _("'dictionary' option is empty")
403 : _("'thesaurus' option is empty"),
404 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100405 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100406 {
407 vim_beep(BO_COMPL);
408 setcursor();
409 out_flush();
410#ifdef FEAT_EVAL
411 if (!get_vim_var_nr(VV_TESTING))
412#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100413 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100414 }
415 return FALSE;
416 }
417 return TRUE;
418}
419
420/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000421 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100422 * This depends on the current mode.
423 */
424 int
425vim_is_ctrl_x_key(int c)
426{
427 // Always allow ^R - let its results then be checked
428 if (c == Ctrl_R)
429 return TRUE;
430
431 // Accept <PageUp> and <PageDown> if the popup menu is visible.
432 if (ins_compl_pum_key(c))
433 return TRUE;
434
435 switch (ctrl_x_mode)
436 {
437 case 0: // Not in any CTRL-X mode
438 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
439 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200440 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100441 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
442 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
443 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
444 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
445 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200446 || c == Ctrl_S || c == Ctrl_K || c == 's'
447 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100448 case CTRL_X_SCROLL:
449 return (c == Ctrl_Y || c == Ctrl_E);
450 case CTRL_X_WHOLE_LINE:
451 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
452 case CTRL_X_FILES:
453 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
454 case CTRL_X_DICTIONARY:
455 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
456 case CTRL_X_THESAURUS:
457 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
458 case CTRL_X_TAGS:
459 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
460#ifdef FEAT_FIND_ID
461 case CTRL_X_PATH_PATTERNS:
462 return (c == Ctrl_P || c == Ctrl_N);
463 case CTRL_X_PATH_DEFINES:
464 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
465#endif
466 case CTRL_X_CMDLINE:
467 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
468 || c == Ctrl_X);
469#ifdef FEAT_COMPL_FUNC
470 case CTRL_X_FUNCTION:
471 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
472 case CTRL_X_OMNI:
473 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
474#endif
475 case CTRL_X_SPELL:
476 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
477 case CTRL_X_EVAL:
478 return (c == Ctrl_P || c == Ctrl_N);
479 }
480 internal_error("vim_is_ctrl_x_key()");
481 return FALSE;
482}
483
484/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000485 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000486 */
487 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000488match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000489{
490 return match->cp_flags & CP_ORIGINAL_TEXT;
491}
492
493/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000494 * Returns TRUE if "match" is the first match in the completion list.
495 */
496 static int
497is_first_match(compl_T *match)
498{
499 return match == compl_first_match;
500}
501
502/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100503 * Return TRUE when character "c" is part of the item currently being
504 * completed. Used to decide whether to abandon complete mode when the menu
505 * is visible.
506 */
507 int
508ins_compl_accept_char(int c)
509{
510 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
511 // When expanding an identifier only accept identifier chars.
512 return vim_isIDc(c);
513
514 switch (ctrl_x_mode)
515 {
516 case CTRL_X_FILES:
517 // When expanding file name only accept file name chars. But not
518 // path separators, so that "proto/<Tab>" expands files in
519 // "proto", not "proto/" as a whole
520 return vim_isfilec(c) && !vim_ispathsep(c);
521
522 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200523 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100524 case CTRL_X_OMNI:
525 // Command line and Omni completion can work with just about any
526 // printable character, but do stop at white space.
527 return vim_isprintc(c) && !VIM_ISWHITE(c);
528
529 case CTRL_X_WHOLE_LINE:
530 // For while line completion a space can be part of the line.
531 return vim_isprintc(c);
532 }
533 return vim_iswordc(c);
534}
535
536/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000537 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100538 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000539 */
540 static char_u *
541ins_compl_infercase_gettext(
542 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100543 int char_len,
544 int compl_char_len,
545 int min_len,
546 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000547{
548 int *wca; // Wide character array.
549 char_u *p;
550 int i, c;
551 int has_lower = FALSE;
552 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100553 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000554
555 IObuff[0] = NUL;
556
557 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100558 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000559 if (wca == NULL)
560 return IObuff;
561
562 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100563 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100564 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000565 if (has_mbyte)
566 wca[i] = mb_ptr2char_adv(&p);
567 else
568 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100569 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000570
571 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100572 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000573 for (i = 0; i < min_len; ++i)
574 {
glepnir6e199932024-12-14 21:13:27 +0100575 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000576 if (MB_ISLOWER(c))
577 {
578 has_lower = TRUE;
579 if (MB_ISUPPER(wca[i]))
580 {
581 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100582 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000583 wca[i] = MB_TOLOWER(wca[i]);
584 break;
585 }
586 }
587 }
588
589 // Rule 2: No lower case, 2nd consecutive letter converted to
590 // upper case.
591 if (!has_lower)
592 {
John Marriott5e6ea922024-11-23 14:01:57 +0100593 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000594 for (i = 0; i < min_len; ++i)
595 {
glepnir6e199932024-12-14 21:13:27 +0100596 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000597 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
598 {
599 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100600 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000601 wca[i] = MB_TOUPPER(wca[i]);
602 break;
603 }
604 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
605 }
606 }
607
608 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100609 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000610 for (i = 0; i < min_len; ++i)
611 {
glepnir6e199932024-12-14 21:13:27 +0100612 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000613 if (MB_ISLOWER(c))
614 wca[i] = MB_TOLOWER(wca[i]);
615 else if (MB_ISUPPER(c))
616 wca[i] = MB_TOUPPER(wca[i]);
617 }
618
619 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000620 p = IObuff;
621 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100622 ga_init2(&gap, 1, 500);
623 while (i < char_len)
624 {
625 if (gap.ga_data != NULL)
626 {
627 if (ga_grow(&gap, 10) == FAIL)
628 {
629 ga_clear(&gap);
630 return (char_u *)"[failed]";
631 }
632 p = (char_u *)gap.ga_data + gap.ga_len;
633 if (has_mbyte)
634 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
635 else
636 {
637 *p = wca[i++];
638 ++gap.ga_len;
639 }
640 }
641 else if ((p - IObuff) + 6 >= IOSIZE)
642 {
643 // Multi-byte characters can occupy up to five bytes more than
644 // ASCII characters, and we also need one byte for NUL, so when
645 // getting to six bytes from the edge of IObuff switch to using a
646 // growarray. Add the character in the next round.
647 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100648 {
649 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100650 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100651 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100652 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100653 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100654 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100655 }
656 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000657 p += (*mb_char2bytes)(wca[i++], p);
658 else
659 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100660 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000661 vim_free(wca);
662
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100663 if (gap.ga_data != NULL)
664 {
665 *tofree = gap.ga_data;
666 return gap.ga_data;
667 }
668
669 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000670 return IObuff;
671}
672
673/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100674 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
675 * case of the originally typed text is used, and the case of the completed
676 * text is inferred, ie this tries to work out what case you probably wanted
677 * the rest of the word to be in -- webb
678 */
679 int
680ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200681 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100682 int len,
683 int icase,
684 char_u *fname,
685 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200686 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100687{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200688 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100689 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100690 int char_len; // count multi-byte characters
691 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200693 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100694 int res;
695 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100696
697 if (p_ic && curbuf->b_p_inf && len > 0)
698 {
699 // Infer case of completed part.
700
701 // Find actual length of completion.
702 if (has_mbyte)
703 {
704 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100705 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100706 while (*p != NUL)
707 {
708 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100709 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100710 }
711 }
712 else
glepnir6e199932024-12-14 21:13:27 +0100713 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100714 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100715 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100716
717 // Find actual length of original text.
718 if (has_mbyte)
719 {
John Marriott5e6ea922024-11-23 14:01:57 +0100720 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100721 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100722 while (*p != NUL)
723 {
724 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100725 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100726 }
727 }
728 else
glepnir6e199932024-12-14 21:13:27 +0100729 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100730 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100731 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100732
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100733 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100734 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100735 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100736
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100737 str = ins_compl_infercase_gettext(str, char_len,
738 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100739 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200740 if (cont_s_ipos)
741 flags |= CP_CONT_S_IPOS;
742 if (icase)
743 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200744
glepnir5c66e232024-11-15 19:58:27 +0100745 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100746 vim_free(tofree);
747 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100748}
749
750/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000751 * Add a match to the list of matches. The arguments are:
752 * str - text of the match to add
753 * len - length of "str". If -1, then the length of "str" is
754 * computed.
755 * fname - file name to associate with this match.
756 * cptext - list of strings to use with this match (for abbr, menu, info
757 * and kind)
758 * user_data - user supplied data (any vim type) for this match
759 * cdir - match direction. If 0, use "compl_direction".
760 * flags_arg - match flags (cp_flags)
761 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100762 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000763 * If "cdir" is FORWARD, then the match is added after the current match.
764 * Otherwise, it is added before the current match.
765 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 * If the given string is already in the list of completions, then return
767 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
768 * maybe because alloc() returns NULL, then FAIL is returned.
769 */
770 static int
771ins_compl_add(
772 char_u *str,
773 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100774 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100775 char_u **cptext, // extra text for popup menu or NULL
776 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200778 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200779 int adup, // accept duplicate match
glepnir80b66202024-11-27 21:53:53 +0100780 int *user_hl) // user abbr/kind hlattr
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100781{
782 compl_T *match;
783 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200784 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100785
Bram Moolenaarceb06192021-04-04 15:05:22 +0200786 if (flags & CP_FAST)
787 fast_breakcheck();
788 else
789 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100790 if (got_int)
791 return FAIL;
792 if (len < 0)
793 len = (int)STRLEN(str);
794
795 // If the same match is already present, don't add it.
796 if (compl_first_match != NULL && !adup)
797 {
798 match = compl_first_match;
799 do
800 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000801 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100802 && STRNCMP(match->cp_str.string, str, len) == 0
803 && ((int)match->cp_str.length <= len
804 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100805 return NOTDONE;
806 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000807 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100808 }
809
810 // Remove any popup menu before changing the list of matches.
811 ins_compl_del_pum();
812
813 // Allocate a new match structure.
814 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200815 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100816 if (match == NULL)
817 return FAIL;
818 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200819 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100820 match->cp_number = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100821 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100822 {
823 vim_free(match);
824 return FAIL;
825 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100826
John Marriott5e6ea922024-11-23 14:01:57 +0100827 match->cp_str.length = len;
828
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829 // match-fname is:
830 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200831 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100832 // - NULL otherwise. --Acevedo
833 if (fname != NULL
834 && compl_curr_match != NULL
835 && compl_curr_match->cp_fname != NULL
836 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
837 match->cp_fname = compl_curr_match->cp_fname;
838 else if (fname != NULL)
839 {
840 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200841 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100842 }
843 else
844 match->cp_fname = NULL;
845 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100846 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
847 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100848
849 if (cptext != NULL)
850 {
851 int i;
852
853 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100854 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100855 if (cptext[i] != NULL && *cptext[i] != NUL)
856 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100857 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100858 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100859#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100860 if (user_data != NULL)
861 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100862#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100863
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000864 // Link the new match structure after (FORWARD) or before (BACKWARD) the
865 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100866 if (compl_first_match == NULL)
867 match->cp_next = match->cp_prev = NULL;
868 else if (dir == FORWARD)
869 {
870 match->cp_next = compl_curr_match->cp_next;
871 match->cp_prev = compl_curr_match;
872 }
873 else // BACKWARD
874 {
875 match->cp_next = compl_curr_match;
876 match->cp_prev = compl_curr_match->cp_prev;
877 }
878 if (match->cp_next)
879 match->cp_next->cp_prev = match;
880 if (match->cp_prev)
881 match->cp_prev->cp_next = match;
882 else // if there's nothing before, it is the first match
883 compl_first_match = match;
884 compl_curr_match = match;
885
886 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200887 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100888 ins_compl_longest_match(match);
889
890 return OK;
891}
892
893/*
894 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200895 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100896 */
897 static int
898ins_compl_equal(compl_T *match, char_u *str, int len)
899{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200900 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200901 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200902 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100903 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
904 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100905}
906
907/*
glepnir6a38aff2024-12-16 21:56:16 +0100908 * when len is -1 mean use whole length of p otherwise part of p
909 */
910 static void
911ins_compl_insert_bytes(char_u *p, int len)
912{
913 if (len == -1)
914 len = (int)STRLEN(p);
915 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +0100916 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +0100917}
918
919/*
zeertzjqd32bf0a2024-12-17 20:55:13 +0100920 * Checks if the column is within the currently inserted completion text
921 * column range. If it is, it returns a special highlight attribute.
922 * -1 mean normal item.
glepnir6a38aff2024-12-16 21:56:16 +0100923 */
924 int
925ins_compl_col_range_attr(int col)
926{
glepnire8908872025-01-08 18:30:45 +0100927 if ((get_cot_flags() & COT_FUZZY))
928 return -1;
929
glepnir9fddb8a2025-01-11 16:42:50 +0100930 if (col >= (compl_col + (int)ins_compl_leader_len()) && col < compl_ins_end_col)
glepnir6a38aff2024-12-16 21:56:16 +0100931 return syn_name2attr((char_u *)"ComplMatchIns");
932
933 return -1;
934}
935
936/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100937 * Reduce the longest common string for match "match".
938 */
939 static void
940ins_compl_longest_match(compl_T *match)
941{
942 char_u *p, *s;
943 int c1, c2;
944 int had_match;
945
John Marriott5e6ea922024-11-23 14:01:57 +0100946 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100947 {
948 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +0100949 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
950 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000951 return;
952
John Marriott5e6ea922024-11-23 14:01:57 +0100953 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000954 had_match = (curwin->w_cursor.col > compl_col);
955 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +0100956 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000957 ins_redraw(FALSE);
958
959 // When the match isn't there (to avoid matching itself) remove it
960 // again after redrawing.
961 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100962 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100963 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000964
965 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100966 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000967
968 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +0100969 p = compl_leader.string;
970 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000971 while (*p != NUL)
972 {
973 if (has_mbyte)
974 {
975 c1 = mb_ptr2char(p);
976 c2 = mb_ptr2char(s);
977 }
978 else
979 {
980 c1 = *p;
981 c2 = *s;
982 }
983 if ((match->cp_flags & CP_ICASE)
984 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
985 break;
986 if (has_mbyte)
987 {
988 MB_PTR_ADV(p);
989 MB_PTR_ADV(s);
990 }
991 else
992 {
993 ++p;
994 ++s;
995 }
996 }
997
998 if (*p != NUL)
999 {
1000 // Leader was shortened, need to change the inserted text.
1001 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001002 compl_leader.length = (size_t)(p - compl_leader.string);
1003
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001004 had_match = (curwin->w_cursor.col > compl_col);
1005 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01001006 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001007 ins_redraw(FALSE);
1008
1009 // When the match isn't there (to avoid matching itself) remove it
1010 // again after redrawing.
1011 if (!had_match)
1012 ins_compl_delete();
1013 }
1014
1015 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001016}
1017
1018/*
1019 * Add an array of matches to the list of matches.
1020 * Frees matches[].
1021 */
1022 static void
1023ins_compl_add_matches(
1024 int num_matches,
1025 char_u **matches,
1026 int icase)
1027{
1028 int i;
1029 int add_r = OK;
1030 int dir = compl_direction;
1031
1032 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001033 {
1034 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
1035 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL);
1036 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001037 // if dir was BACKWARD then honor it just once
1038 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001039 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001040 FreeWild(num_matches, matches);
1041}
1042
1043/*
1044 * Make the completion list cyclic.
1045 * Return the number of matches (excluding the original).
1046 */
1047 static int
1048ins_compl_make_cyclic(void)
1049{
1050 compl_T *match;
1051 int count = 0;
1052
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001053 if (compl_first_match == NULL)
1054 return 0;
1055
1056 // Find the end of the list.
1057 match = compl_first_match;
1058 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001059 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001060 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001061 match = match->cp_next;
1062 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001063 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001064 match->cp_next = compl_first_match;
1065 compl_first_match->cp_prev = match;
1066
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001067 return count;
1068}
1069
1070/*
1071 * Return whether there currently is a shown match.
1072 */
1073 int
1074ins_compl_has_shown_match(void)
1075{
1076 return compl_shown_match == NULL
1077 || compl_shown_match != compl_shown_match->cp_next;
1078}
1079
1080/*
1081 * Return whether the shown match is long enough.
1082 */
1083 int
1084ins_compl_long_shown_match(void)
1085{
John Marriott5e6ea922024-11-23 14:01:57 +01001086 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001087 > curwin->w_cursor.col - compl_col;
1088}
1089
1090/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001091 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001092 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001093 unsigned int
1094get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001095{
zeertzjq529b9ad2024-06-05 20:27:06 +02001096 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001097}
1098
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001099/*
1100 * Update the screen and when there is any scrolling remove the popup menu.
1101 */
1102 static void
1103ins_compl_upd_pum(void)
1104{
1105 int h;
1106
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001107 if (compl_match_array == NULL)
1108 return;
1109
1110 h = curwin->w_cline_height;
1111 // Update the screen later, before drawing the popup menu over it.
1112 pum_call_update_screen();
1113 if (h != curwin->w_cline_height)
1114 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001115}
1116
1117/*
1118 * Remove any popup menu.
1119 */
1120 static void
1121ins_compl_del_pum(void)
1122{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001123 if (compl_match_array == NULL)
1124 return;
1125
1126 pum_undisplay();
1127 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001128}
1129
1130/*
1131 * Return TRUE if the popup menu should be displayed.
1132 */
1133 int
1134pum_wanted(void)
1135{
1136 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001137 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001138 return FALSE;
1139
1140 // The display looks bad on a B&W display.
1141 if (t_colors < 8
1142#ifdef FEAT_GUI
1143 && !gui.in_use
1144#endif
1145 )
1146 return FALSE;
1147 return TRUE;
1148}
1149
1150/*
1151 * Return TRUE if there are two or more matches to be shown in the popup menu.
1152 * One if 'completopt' contains "menuone".
1153 */
1154 static int
1155pum_enough_matches(void)
1156{
1157 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001158 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001159
1160 // Don't display the popup menu if there are no matches or there is only
1161 // one (ignoring the original text).
1162 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001163 do
1164 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001165 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001166 break;
1167 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001168 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001169
zeertzjq529b9ad2024-06-05 20:27:06 +02001170 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001171 return (i >= 1);
1172 return (i >= 2);
1173}
1174
Bram Moolenaar3075a452021-11-17 15:51:52 +00001175#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001176/*
1177 * Allocate Dict for the completed item.
1178 * { word, abbr, menu, kind, info }
1179 */
1180 static dict_T *
1181ins_compl_dict_alloc(compl_T *match)
1182{
1183 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1184
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001185 if (dict == NULL)
1186 return NULL;
1187
John Marriott5e6ea922024-11-23 14:01:57 +01001188 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001189 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1190 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1191 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1192 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1193 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1194 dict_add_string(dict, "user_data", (char_u *)"");
1195 else
1196 dict_add_tv(dict, "user_data", &match->cp_user_data);
1197
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001198 return dict;
1199}
1200
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001201/*
1202 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1203 * completion menu is changed.
1204 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001205 static void
1206trigger_complete_changed_event(int cur)
1207{
1208 dict_T *v_event;
1209 dict_T *item;
1210 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001211 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001212
1213 if (recursive)
1214 return;
1215
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001216 if (cur < 0)
1217 item = dict_alloc();
1218 else
1219 item = ins_compl_dict_alloc(compl_curr_match);
1220 if (item == NULL)
1221 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001222 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001223 dict_add_dict(v_event, "completed_item", item);
1224 pum_set_event_info(v_event);
1225 dict_set_items_ro(v_event);
1226
1227 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001228 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001229 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001230 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001231 recursive = FALSE;
1232
Bram Moolenaar3075a452021-11-17 15:51:52 +00001233 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001234}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001235#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001236
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001237/*
glepnira218cc62024-06-03 19:32:39 +02001238 * pumitem qsort compare func
1239 */
1240 static int
zeertzjq8e567472024-06-14 20:04:42 +02001241ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001242{
1243 const int sa = (*(pumitem_T *)a).pum_score;
1244 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001245 const int ia = (*(pumitem_T *)a).pum_idx;
1246 const int ib = (*(pumitem_T *)b).pum_idx;
1247 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001248}
1249
1250/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001251 * Build a popup menu to show the completion matches.
1252 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1253 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001254 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001255 static int
1256ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001257{
1258 compl_T *compl;
1259 compl_T *shown_compl = NULL;
1260 int did_find_shown_match = FALSE;
1261 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001262 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001263 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001264 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001265 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001266 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001267 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1268 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001269 compl_T *match_head = NULL;
1270 compl_T *match_tail = NULL;
1271 compl_T *match_next = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001272
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001273 // Need to build the popup menu list.
1274 compl_match_arraysize = 0;
1275 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001276
glepnira49c0772024-11-30 10:56:30 +01001277 // If the current match is the original text don't find the first
1278 // match after it, don't highlight anything.
1279 if (match_at_original_text(compl_shown_match))
1280 shown_match_ok = TRUE;
1281
1282 if (compl_leader.string != NULL
1283 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1284 && shown_match_ok == FALSE)
1285 compl_shown_match = compl_no_select ? compl_first_match
1286 : compl_first_match->cp_next;
1287
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001288 do
1289 {
glepnird4088ed2024-12-31 10:55:22 +01001290 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001291 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1292 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001293 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001294 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001295
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001296 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001297 && (compl_leader.string == NULL
1298 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001299 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001300 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001301 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001302 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001303 if (match_head == NULL)
1304 match_head = compl;
1305 else
glepnira49c0772024-11-30 10:56:30 +01001306 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001307 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001308
glepnirf400a0c2025-01-23 19:55:14 +01001309 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001310 {
1311 if (compl == compl_shown_match || did_find_shown_match)
1312 {
1313 // This item is the shown match or this is the
1314 // first displayed item after the shown match.
1315 compl_shown_match = compl;
1316 did_find_shown_match = TRUE;
1317 shown_match_ok = TRUE;
1318 }
1319 else
1320 // Remember this displayed match for when the
1321 // shown match is just below it.
1322 shown_compl = compl;
1323 cur = i;
1324 }
glepnirf400a0c2025-01-23 19:55:14 +01001325 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001326 {
1327 if (i == 0)
1328 shown_compl = compl;
1329 // Update the maximum fuzzy score and the shown match
1330 // if the current item's score is higher
zeertzjqd65aa1b2025-01-25 15:29:03 +01001331 if (fuzzy_sort && compl->cp_score > max_fuzzy_score)
glepnira49c0772024-11-30 10:56:30 +01001332 {
1333 did_find_shown_match = TRUE;
1334 max_fuzzy_score = compl->cp_score;
1335 if (!compl_no_select)
1336 compl_shown_match = compl;
1337 }
zeertzjqd65aa1b2025-01-25 15:29:03 +01001338 else if (!fuzzy_sort && i == 0 && !compl_no_select)
glepnirf400a0c2025-01-23 19:55:14 +01001339 compl_shown_match = shown_compl;
glepnira49c0772024-11-30 10:56:30 +01001340
1341 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1342 {
1343 cur = i;
1344 shown_match_ok = TRUE;
1345 }
1346 }
1347 i++;
glepnir80b66202024-11-27 21:53:53 +01001348 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001349
glepnirf400a0c2025-01-23 19:55:14 +01001350 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001351 {
1352 did_find_shown_match = TRUE;
1353
1354 // When the original text is the shown match don't set
1355 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001356 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001357 shown_match_ok = TRUE;
1358
1359 if (!shown_match_ok && shown_compl != NULL)
1360 {
1361 // The shown match isn't displayed, set it to the
1362 // previously displayed match.
1363 compl_shown_match = shown_compl;
1364 shown_match_ok = TRUE;
1365 }
1366 }
glepnira49c0772024-11-30 10:56:30 +01001367 compl = compl->cp_next;
1368 } while (compl != NULL && !is_first_match(compl));
1369
1370 if (compl_match_arraysize == 0)
1371 return -1;
1372
1373 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1374 if (compl_match_array == NULL)
1375 return -1;
1376
1377 compl = match_head;
1378 i = 0;
1379 while (compl != NULL)
1380 {
glepnir6e199932024-12-14 21:13:27 +01001381 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1382 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001383 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1384 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1385 compl_match_array[i].pum_score = compl->cp_score;
1386 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1387 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001388 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1389 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001390 match_next = compl->cp_match_next;
1391 compl->cp_match_next = NULL;
1392 compl = match_next;
1393 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001394
zeertzjqd65aa1b2025-01-25 15:29:03 +01001395 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001396 {
1397 for (i = 0; i < compl_match_arraysize; i++)
1398 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001399 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001400 qsort(compl_match_array, (size_t)compl_match_arraysize,
1401 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001402 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001403 }
glepnira218cc62024-06-03 19:32:39 +02001404
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001405 if (!shown_match_ok) // no displayed match at all
1406 cur = -1;
1407
1408 return cur;
1409}
1410
1411/*
1412 * Show the popup menu for the list of matches.
1413 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1414 */
1415 void
1416ins_compl_show_pum(void)
1417{
1418 int i;
1419 int cur = -1;
1420 colnr_T col;
1421
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001422 if (!pum_wanted() || !pum_enough_matches())
1423 return;
1424
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001425 // Update the screen later, before drawing the popup menu over it.
1426 pum_call_update_screen();
1427
1428 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001429 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001430 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001431 else
1432 {
1433 // popup menu already exists, only need to find the current item.
1434 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001435 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001436 || compl_match_array[i].pum_text
1437 == compl_shown_match->cp_text[CPT_ABBR])
1438 {
1439 cur = i;
1440 break;
1441 }
1442 }
1443
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001444 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001445 {
1446#ifdef FEAT_EVAL
1447 if (compl_started && has_completechanged())
1448 trigger_complete_changed_event(cur);
1449#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001450 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001451 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001452
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001453 // In Replace mode when a $ is displayed at the end of the line only
1454 // part of the screen would be updated. We do need to redraw here.
1455 dollar_vcol = -1;
1456
1457 // Compute the screen column of the start of the completed text.
1458 // Use the cursor to get all wrapping and other settings right.
1459 col = curwin->w_cursor.col;
1460 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001461 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001462 pum_display(compl_match_array, compl_match_arraysize, cur);
1463 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001464
glepnircbb46b42024-02-03 18:11:13 +01001465 // After adding leader, set the current match to shown match.
1466 if (compl_started && compl_curr_match != compl_shown_match)
1467 compl_curr_match = compl_shown_match;
1468
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001469#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001470 if (has_completechanged())
1471 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001472#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001473}
1474
1475#define DICT_FIRST (1) // use just first element in "dict"
1476#define DICT_EXACT (2) // "dict" is the exact name of a file
1477
1478/*
glepnir40c1c332024-06-11 19:37:04 +02001479 * Get current completion leader
1480 */
1481 char_u *
1482ins_compl_leader(void)
1483{
John Marriott5e6ea922024-11-23 14:01:57 +01001484 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1485}
1486
1487/*
1488 * Get current completion leader length
1489 */
1490 size_t
1491ins_compl_leader_len(void)
1492{
1493 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001494}
1495
1496/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001497 * Add any identifiers that match the given pattern "pat" in the list of
1498 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001499 */
1500 static void
1501ins_compl_dictionaries(
1502 char_u *dict_start,
1503 char_u *pat,
1504 int flags, // DICT_FIRST and/or DICT_EXACT
1505 int thesaurus) // Thesaurus completion
1506{
1507 char_u *dict = dict_start;
1508 char_u *ptr;
1509 char_u *buf;
1510 regmatch_T regmatch;
1511 char_u **files;
1512 int count;
1513 int save_p_scs;
1514 int dir = compl_direction;
1515
1516 if (*dict == NUL)
1517 {
1518#ifdef FEAT_SPELL
1519 // When 'dictionary' is empty and spell checking is enabled use
1520 // "spell".
1521 if (!thesaurus && curwin->w_p_spell)
1522 dict = (char_u *)"spell";
1523 else
1524#endif
1525 return;
1526 }
1527
1528 buf = alloc(LSIZE);
1529 if (buf == NULL)
1530 return;
1531 regmatch.regprog = NULL; // so that we can goto theend
1532
1533 // If 'infercase' is set, don't use 'smartcase' here
1534 save_p_scs = p_scs;
1535 if (curbuf->b_p_inf)
1536 p_scs = FALSE;
1537
1538 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1539 // to only match at the start of a line. Otherwise just match the
1540 // pattern. Also need to double backslashes.
1541 if (ctrl_x_mode_line_or_eval())
1542 {
1543 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1544 size_t len;
1545
1546 if (pat_esc == NULL)
1547 goto theend;
1548 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001549 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001550 if (ptr == NULL)
1551 {
1552 vim_free(pat_esc);
1553 goto theend;
1554 }
1555 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1556 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1557 vim_free(pat_esc);
1558 vim_free(ptr);
1559 }
1560 else
1561 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001562 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001563 if (regmatch.regprog == NULL)
1564 goto theend;
1565 }
1566
1567 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1568 regmatch.rm_ic = ignorecase(pat);
1569 while (*dict != NUL && !got_int && !compl_interrupted)
1570 {
1571 // copy one dictionary file name into buf
1572 if (flags == DICT_EXACT)
1573 {
1574 count = 1;
1575 files = &dict;
1576 }
1577 else
1578 {
1579 // Expand wildcards in the dictionary name, but do not allow
1580 // backticks (for security, the 'dict' option may have been set in
1581 // a modeline).
1582 copy_option_part(&dict, buf, LSIZE, ",");
1583# ifdef FEAT_SPELL
1584 if (!thesaurus && STRCMP(buf, "spell") == 0)
1585 count = -1;
1586 else
1587# endif
1588 if (vim_strchr(buf, '`') != NULL
1589 || expand_wildcards(1, &buf, &count, &files,
1590 EW_FILE|EW_SILENT) != OK)
1591 count = 0;
1592 }
1593
1594# ifdef FEAT_SPELL
1595 if (count == -1)
1596 {
1597 // Complete from active spelling. Skip "\<" in the pattern, we
1598 // don't use it as a RE.
1599 if (pat[0] == '\\' && pat[1] == '<')
1600 ptr = pat + 2;
1601 else
1602 ptr = pat;
1603 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1604 }
1605 else
1606# endif
1607 if (count > 0) // avoid warning for using "files" uninit
1608 {
1609 ins_compl_files(count, files, thesaurus, flags,
1610 &regmatch, buf, &dir);
1611 if (flags != DICT_EXACT)
1612 FreeWild(count, files);
1613 }
1614 if (flags != 0)
1615 break;
1616 }
1617
1618theend:
1619 p_scs = save_p_scs;
1620 vim_regfree(regmatch.regprog);
1621 vim_free(buf);
1622}
1623
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001624/*
1625 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1626 * skipping the word at 'skip_word'. Returns OK on success.
1627 */
1628 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001629thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001630 char_u *fname,
1631 char_u **buf_arg,
1632 int dir,
1633 char_u *skip_word)
1634{
1635 int status = OK;
1636 char_u *ptr;
1637 char_u *wstart;
1638
1639 // Add the other matches on the line
1640 ptr = *buf_arg;
1641 while (!got_int)
1642 {
1643 // Find start of the next word. Skip white
1644 // space and punctuation.
1645 ptr = find_word_start(ptr);
1646 if (*ptr == NUL || *ptr == NL)
1647 break;
1648 wstart = ptr;
1649
1650 // Find end of the word.
1651 if (has_mbyte)
1652 // Japanese words may have characters in
1653 // different classes, only separate words
1654 // with single-byte non-word characters.
1655 while (*ptr != NUL)
1656 {
1657 int l = (*mb_ptr2len)(ptr);
1658
1659 if (l < 2 && !vim_iswordc(*ptr))
1660 break;
1661 ptr += l;
1662 }
1663 else
1664 ptr = find_word_end(ptr);
1665
1666 // Add the word. Skip the regexp match.
1667 if (wstart != skip_word)
1668 {
1669 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1670 fname, dir, FALSE);
1671 if (status == FAIL)
1672 break;
1673 }
1674 }
1675
1676 *buf_arg = ptr;
1677 return status;
1678}
1679
1680/*
1681 * Process "count" dictionary/thesaurus "files" and add the text matching
1682 * "regmatch".
1683 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001684 static void
1685ins_compl_files(
1686 int count,
1687 char_u **files,
1688 int thesaurus,
1689 int flags,
1690 regmatch_T *regmatch,
1691 char_u *buf,
1692 int *dir)
1693{
1694 char_u *ptr;
1695 int i;
1696 FILE *fp;
1697 int add_r;
1698
1699 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1700 {
1701 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001702 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001703 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001704 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001705 vim_snprintf((char *)IObuff, IOSIZE,
1706 _("Scanning dictionary: %s"), (char *)files[i]);
1707 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1708 }
1709
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001710 if (fp == NULL)
1711 continue;
1712
1713 // Read dictionary file line by line.
1714 // Check each line for a match.
1715 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001716 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001717 ptr = buf;
1718 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001719 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001720 ptr = regmatch->startp[0];
glepnir6e199932024-12-14 21:13:27 +01001721 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1722 : find_word_end(ptr);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001723 add_r = ins_compl_add_infercase(regmatch->startp[0],
1724 (int)(ptr - regmatch->startp[0]),
1725 p_ic, files[i], *dir, FALSE);
1726 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001727 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001728 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001729 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001730 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001731 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001732 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001733 if (add_r == OK)
1734 // if dir was BACKWARD then honor it just once
1735 *dir = FORWARD;
1736 else if (add_r == FAIL)
1737 break;
1738 // avoid expensive call to vim_regexec() when at end
1739 // of line
1740 if (*ptr == '\n' || got_int)
1741 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001742 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001743 line_breakcheck();
1744 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001745 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001746 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001747 }
1748}
1749
1750/*
1751 * Find the start of the next word.
1752 * Returns a pointer to the first char of the word. Also stops at a NUL.
1753 */
1754 char_u *
1755find_word_start(char_u *ptr)
1756{
1757 if (has_mbyte)
1758 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1759 ptr += (*mb_ptr2len)(ptr);
1760 else
1761 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1762 ++ptr;
1763 return ptr;
1764}
1765
1766/*
1767 * Find the end of the word. Assumes it starts inside a word.
1768 * Returns a pointer to just after the word.
1769 */
1770 char_u *
1771find_word_end(char_u *ptr)
1772{
1773 int start_class;
1774
1775 if (has_mbyte)
1776 {
1777 start_class = mb_get_class(ptr);
1778 if (start_class > 1)
1779 while (*ptr != NUL)
1780 {
1781 ptr += (*mb_ptr2len)(ptr);
1782 if (mb_get_class(ptr) != start_class)
1783 break;
1784 }
1785 }
1786 else
1787 while (vim_iswordc(*ptr))
1788 ++ptr;
1789 return ptr;
1790}
1791
1792/*
1793 * Find the end of the line, omitting CR and NL at the end.
1794 * Returns a pointer to just after the line.
1795 */
1796 static char_u *
1797find_line_end(char_u *ptr)
1798{
1799 char_u *s;
1800
1801 s = ptr + STRLEN(ptr);
1802 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1803 --s;
1804 return s;
1805}
1806
1807/*
1808 * Free the list of completions
1809 */
1810 static void
1811ins_compl_free(void)
1812{
1813 compl_T *match;
1814 int i;
1815
John Marriott5e6ea922024-11-23 14:01:57 +01001816 VIM_CLEAR_STRING(compl_pattern);
1817 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001818
1819 if (compl_first_match == NULL)
1820 return;
1821
1822 ins_compl_del_pum();
1823 pum_clear();
1824
1825 compl_curr_match = compl_first_match;
1826 do
1827 {
1828 match = compl_curr_match;
1829 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001830 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001831 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001832 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001833 vim_free(match->cp_fname);
1834 for (i = 0; i < CPT_COUNT; ++i)
1835 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001836#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001837 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001838#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001839 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001840 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001841 compl_first_match = compl_curr_match = NULL;
1842 compl_shown_match = NULL;
1843 compl_old_match = NULL;
1844}
1845
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001846/*
1847 * Reset/clear the completion state.
1848 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001849 void
1850ins_compl_clear(void)
1851{
1852 compl_cont_status = 0;
1853 compl_started = FALSE;
1854 compl_matches = 0;
glepnir6a38aff2024-12-16 21:56:16 +01001855 compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001856 VIM_CLEAR_STRING(compl_pattern);
1857 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001858 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001859 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001860 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001861#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001862 // clear v:completed_item
1863 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001864#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001865}
1866
1867/*
1868 * Return TRUE when Insert completion is active.
1869 */
1870 int
1871ins_compl_active(void)
1872{
1873 return compl_started;
1874}
1875
1876/*
glepnir8d0bb6d2024-12-24 09:44:35 +01001877 * Return True when wp is the actual completion window
1878 */
1879 int
1880ins_compl_win_active(win_T *wp UNUSED)
1881{
1882 return ins_compl_active()
1883#if defined(FEAT_QUICKFIX)
1884 && (!wp->w_p_pvw
1885# ifdef FEAT_PROP_POPUP
1886 && !(wp->w_popup_flags & POPF_INFO)
1887# endif
1888 )
1889#endif
1890 ;
1891}
1892
1893/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001894 * Selected one of the matches. When FALSE the match was edited or using the
1895 * longest common string.
1896 */
1897 int
1898ins_compl_used_match(void)
1899{
1900 return compl_used_match;
1901}
1902
1903/*
1904 * Initialize get longest common string.
1905 */
1906 void
1907ins_compl_init_get_longest(void)
1908{
1909 compl_get_longest = FALSE;
1910}
1911
1912/*
1913 * Returns TRUE when insert completion is interrupted.
1914 */
1915 int
1916ins_compl_interrupted(void)
1917{
1918 return compl_interrupted;
1919}
1920
1921/*
1922 * Returns TRUE if the <Enter> key selects a match in the completion popup
1923 * menu.
1924 */
1925 int
1926ins_compl_enter_selects(void)
1927{
1928 return compl_enter_selects;
1929}
1930
1931/*
1932 * Return the column where the text starts that is being completed
1933 */
1934 colnr_T
1935ins_compl_col(void)
1936{
1937 return compl_col;
1938}
1939
1940/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001941 * Return the length in bytes of the text being completed
1942 */
1943 int
1944ins_compl_len(void)
1945{
1946 return compl_length;
1947}
1948
1949/*
glepniredd4ac32025-01-29 18:53:51 +01001950 * Return TRUE when preinsert is set otherwise FALSE.
1951 */
1952 static int
1953ins_compl_has_preinsert(void)
1954{
1955 return (get_cot_flags() & (COT_PREINSERT | COT_FUZZY)) == COT_PREINSERT;
1956}
1957
1958/*
1959 * Returns TRUE if the pre-insert effect is valid and the cursor is within
1960 * the `compl_ins_end_col` range.
1961 */
1962 int
1963ins_compl_preinsert_effect(void)
1964{
1965 if (!ins_compl_has_preinsert())
1966 return FALSE;
1967
1968 return curwin->w_cursor.col < compl_ins_end_col;
1969}
1970
1971/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001972 * Delete one character before the cursor and show the subset of the matches
1973 * that match the word that is now before the cursor.
1974 * Returns the character to be used, NUL if the work is done and another char
1975 * to be got from the user.
1976 */
1977 int
1978ins_compl_bs(void)
1979{
1980 char_u *line;
1981 char_u *p;
1982
glepniredd4ac32025-01-29 18:53:51 +01001983 if (ins_compl_preinsert_effect())
1984 ins_compl_delete();
1985
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001986 line = ml_get_curline();
1987 p = line + curwin->w_cursor.col;
1988 MB_PTR_BACK(line, p);
1989
1990 // Stop completion when the whole word was deleted. For Omni completion
1991 // allow the word to be deleted, we won't match everything.
1992 // Respect the 'backspace' option.
1993 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001994 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1995 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001996 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1997 - compl_length < 0))
1998 return K_BS;
1999
2000 // Deleted more than what was used to find matches or didn't finish
2001 // finding all matches: need to look for matches all over again.
2002 if (curwin->w_cursor.col <= compl_col + compl_length
2003 || ins_compl_need_restart())
2004 ins_compl_restart();
2005
John Marriott5e6ea922024-11-23 14:01:57 +01002006 VIM_CLEAR_STRING(compl_leader);
2007 compl_leader.length = (size_t)((p - line) - compl_col);
2008 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2009 if (compl_leader.string == NULL)
2010 {
2011 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002012 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002013 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002014
2015 ins_compl_new_leader();
2016 if (compl_shown_match != NULL)
2017 // Make sure current match is not a hidden item.
2018 compl_curr_match = compl_shown_match;
2019 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002020}
2021
2022/*
2023 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2024 * be called.
2025 */
2026 static int
2027ins_compl_need_restart(void)
2028{
2029 // Return TRUE if we didn't complete finding matches or when the
2030 // 'completefunc' returned "always" in the "refresh" dictionary item.
2031 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002032 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002033 && compl_opt_refresh_always);
2034}
2035
2036/*
2037 * Called after changing "compl_leader".
2038 * Show the popup menu with a different set of matches.
2039 * May also search for matches again if the previous search was interrupted.
2040 */
2041 static void
2042ins_compl_new_leader(void)
2043{
2044 ins_compl_del_pum();
2045 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002046 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002047 compl_used_match = FALSE;
2048
2049 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01002050 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002051 else
2052 {
2053#ifdef FEAT_SPELL
2054 spell_bad_len = 0; // need to redetect bad word
2055#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002056 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002057 // the popup menu display the changed text before the cursor. Set
2058 // "compl_restarting" to avoid that the first match is inserted.
2059 pum_call_update_screen();
2060#ifdef FEAT_GUI
2061 if (gui.in_use)
2062 {
2063 // Show the cursor after the match, not after the redrawn text.
2064 setcursor();
2065 out_flush_cursor(FALSE, FALSE);
2066 }
2067#endif
2068 compl_restarting = TRUE;
2069 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2070 compl_cont_status = 0;
2071 compl_restarting = FALSE;
2072 }
2073
2074 compl_enter_selects = !compl_used_match;
2075
2076 // Show the popup menu with a different set of matches.
2077 ins_compl_show_pum();
2078
2079 // Don't let Enter select the original text when there is no popup menu.
2080 if (compl_match_array == NULL)
2081 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002082 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2083 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002084}
2085
2086/*
2087 * Return the length of the completion, from the completion start column to
2088 * the cursor column. Making sure it never goes below zero.
2089 */
2090 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002091get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002092{
2093 int off = (int)curwin->w_cursor.col - (int)compl_col;
2094
2095 if (off < 0)
2096 return 0;
2097 return off;
2098}
2099
2100/*
2101 * Append one character to the match leader. May reduce the number of
2102 * matches.
2103 */
2104 void
2105ins_compl_addleader(int c)
2106{
2107 int cc;
2108
glepniredd4ac32025-01-29 18:53:51 +01002109 if (ins_compl_preinsert_effect())
2110 ins_compl_delete();
2111
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002112 if (stop_arrow() == FAIL)
2113 return;
2114 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2115 {
2116 char_u buf[MB_MAXBYTES + 1];
2117
2118 (*mb_char2bytes)(c, buf);
2119 buf[cc] = NUL;
2120 ins_char_bytes(buf, cc);
2121 if (compl_opt_refresh_always)
2122 AppendToRedobuff(buf);
2123 }
2124 else
2125 {
2126 ins_char(c);
2127 if (compl_opt_refresh_always)
2128 AppendCharToRedobuff(c);
2129 }
2130
2131 // If we didn't complete finding matches we must search again.
2132 if (ins_compl_need_restart())
2133 ins_compl_restart();
2134
2135 // When 'always' is set, don't reset compl_leader. While completing,
2136 // cursor doesn't point original position, changing compl_leader would
2137 // break redo.
2138 if (!compl_opt_refresh_always)
2139 {
John Marriott5e6ea922024-11-23 14:01:57 +01002140 VIM_CLEAR_STRING(compl_leader);
2141 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2142 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2143 compl_leader.length);
2144 if (compl_leader.string == NULL)
2145 {
2146 compl_leader.length = 0;
2147 return;
2148 }
2149
2150 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002151 }
2152}
2153
2154/*
2155 * Setup for finding completions again without leaving CTRL-X mode. Used when
2156 * BS or a key was typed while still searching for matches.
2157 */
2158 static void
2159ins_compl_restart(void)
2160{
2161 ins_compl_free();
2162 compl_started = FALSE;
2163 compl_matches = 0;
2164 compl_cont_status = 0;
2165 compl_cont_mode = 0;
2166}
2167
2168/*
2169 * Set the first match, the original text.
2170 */
2171 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002172ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002173{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002174 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002175 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2176 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002177 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002178 {
John Marriott5e6ea922024-11-23 14:01:57 +01002179 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002180 if (p != NULL)
2181 {
John Marriott5e6ea922024-11-23 14:01:57 +01002182 VIM_CLEAR_STRING(compl_first_match->cp_str);
2183 compl_first_match->cp_str.string = p;
2184 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002185 }
2186 }
2187 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002188 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002189 {
John Marriott5e6ea922024-11-23 14:01:57 +01002190 char_u *p = vim_strnsave(str, len);
2191 if (p != NULL)
2192 {
2193 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2194 compl_first_match->cp_prev->cp_str.string = p;
2195 compl_first_match->cp_prev->cp_str.length = len;
2196 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002197 }
2198}
2199
2200/*
2201 * Append one character to the match leader. May reduce the number of
2202 * matches.
2203 */
2204 void
2205ins_compl_addfrommatch(void)
2206{
2207 char_u *p;
2208 int len = (int)curwin->w_cursor.col - (int)compl_col;
2209 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002210
John Marriott5e6ea922024-11-23 14:01:57 +01002211 p = compl_shown_match->cp_str.string;
2212 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002213 {
John Marriott5e6ea922024-11-23 14:01:57 +01002214 size_t plen;
2215 compl_T *cp;
2216
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002217 // When still at the original match use the first entry that matches
2218 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002219 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002220 return;
2221
2222 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002223 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002224 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002225 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002226 {
John Marriott5e6ea922024-11-23 14:01:57 +01002227 if (compl_leader.string == NULL
2228 || ins_compl_equal(cp, compl_leader.string,
2229 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002230 {
John Marriott5e6ea922024-11-23 14:01:57 +01002231 p = cp->cp_str.string;
2232 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002233 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002234 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002235 }
John Marriott5e6ea922024-11-23 14:01:57 +01002236 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002237 return;
2238 }
2239 p += len;
2240 c = PTR2CHAR(p);
2241 ins_compl_addleader(c);
2242}
2243
2244/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002245 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002246 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2247 * compl_cont_mode and compl_cont_status.
2248 * Returns TRUE when the character is not to be inserted.
2249 */
2250 static int
2251set_ctrl_x_mode(int c)
2252{
2253 int retval = FALSE;
2254
2255 switch (c)
2256 {
2257 case Ctrl_E:
2258 case Ctrl_Y:
2259 // scroll the window one line up or down
2260 ctrl_x_mode = CTRL_X_SCROLL;
2261 if (!(State & REPLACE_FLAG))
2262 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2263 else
2264 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2265 edit_submode_pre = NULL;
2266 showmode();
2267 break;
2268 case Ctrl_L:
2269 // complete whole line
2270 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2271 break;
2272 case Ctrl_F:
2273 // complete filenames
2274 ctrl_x_mode = CTRL_X_FILES;
2275 break;
2276 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002277 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002278 ctrl_x_mode = CTRL_X_DICTIONARY;
2279 break;
2280 case Ctrl_R:
2281 // Register insertion without exiting CTRL-X mode
2282 // Simply allow ^R to happen without affecting ^X mode
2283 break;
2284 case Ctrl_T:
2285 // complete words from a thesaurus
2286 ctrl_x_mode = CTRL_X_THESAURUS;
2287 break;
2288#ifdef FEAT_COMPL_FUNC
2289 case Ctrl_U:
2290 // user defined completion
2291 ctrl_x_mode = CTRL_X_FUNCTION;
2292 break;
2293 case Ctrl_O:
2294 // omni completion
2295 ctrl_x_mode = CTRL_X_OMNI;
2296 break;
2297#endif
2298 case 's':
2299 case Ctrl_S:
2300 // complete spelling suggestions
2301 ctrl_x_mode = CTRL_X_SPELL;
2302#ifdef FEAT_SPELL
2303 ++emsg_off; // Avoid getting the E756 error twice.
2304 spell_back_to_badword();
2305 --emsg_off;
2306#endif
2307 break;
2308 case Ctrl_RSB:
2309 // complete tag names
2310 ctrl_x_mode = CTRL_X_TAGS;
2311 break;
2312#ifdef FEAT_FIND_ID
2313 case Ctrl_I:
2314 case K_S_TAB:
2315 // complete keywords from included files
2316 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2317 break;
2318 case Ctrl_D:
2319 // complete definitions from included files
2320 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2321 break;
2322#endif
2323 case Ctrl_V:
2324 case Ctrl_Q:
2325 // complete vim commands
2326 ctrl_x_mode = CTRL_X_CMDLINE;
2327 break;
2328 case Ctrl_Z:
2329 // stop completion
2330 ctrl_x_mode = CTRL_X_NORMAL;
2331 edit_submode = NULL;
2332 showmode();
2333 retval = TRUE;
2334 break;
2335 case Ctrl_P:
2336 case Ctrl_N:
2337 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2338 // just started ^X mode, or there were enough ^X's to cancel
2339 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2340 // do normal expansion when interrupting a different mode (say
2341 // ^X^F^X^P or ^P^X^X^P, see below)
2342 // nothing changes if interrupting mode 0, (eg, the flag
2343 // doesn't change when going to ADDING mode -- Acevedo
2344 if (!(compl_cont_status & CONT_INTRPT))
2345 compl_cont_status |= CONT_LOCAL;
2346 else if (compl_cont_mode != 0)
2347 compl_cont_status &= ~CONT_LOCAL;
2348 // FALLTHROUGH
2349 default:
2350 // If we have typed at least 2 ^X's... for modes != 0, we set
2351 // compl_cont_status = 0 (eg, as if we had just started ^X
2352 // mode).
2353 // For mode 0, we set "compl_cont_mode" to an impossible
2354 // value, in both cases ^X^X can be used to restart the same
2355 // mode (avoiding ADDING mode).
2356 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2357 // 'complete' and local ^P expansions respectively.
2358 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2359 // mode -- Acevedo
2360 if (c == Ctrl_X)
2361 {
2362 if (compl_cont_mode != 0)
2363 compl_cont_status = 0;
2364 else
2365 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2366 }
2367 ctrl_x_mode = CTRL_X_NORMAL;
2368 edit_submode = NULL;
2369 showmode();
2370 break;
2371 }
2372
2373 return retval;
2374}
2375
2376/*
glepnir1c5a1202024-12-04 20:27:34 +01002377 * Trigger CompleteDone event and adds relevant information to v:event
2378 */
2379 static void
2380trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2381{
2382#if defined(FEAT_EVAL)
2383 save_v_event_T save_v_event;
2384 dict_T *v_event = get_v_event(&save_v_event);
2385 char_u *mode_str = NULL;
2386
2387 mode = mode & ~CTRL_X_WANT_IDENT;
2388 if (ctrl_x_mode_names[mode])
2389 mode_str = (char_u *)ctrl_x_mode_names[mode];
2390
2391 (void)dict_add_string(v_event, "complete_word",
2392 word == NULL ? (char_u *)"" : word);
2393 (void)dict_add_string(v_event, "complete_type",
2394 mode_str != NULL ? mode_str : (char_u *)"");
2395
2396 dict_set_items_ro(v_event);
2397#endif
2398 ins_apply_autocmds(EVENT_COMPLETEDONE);
2399
2400#if defined(FEAT_EVAL)
2401 restore_v_event(v_event, &save_v_event);
2402#endif
2403}
2404
2405/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002406 * Stop insert completion mode
2407 */
2408 static int
2409ins_compl_stop(int c, int prev_mode, int retval)
2410{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002411 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002412 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002413
2414 // Get here when we have finished typing a sequence of ^N and
2415 // ^P or other completion characters in CTRL-X mode. Free up
2416 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002417 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002418 {
John Marriott5e6ea922024-11-23 14:01:57 +01002419 char_u *ptr;
2420
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002421 // If any of the original typed text has been changed, eg when
2422 // ignorecase is set, we must add back-spaces to the redo
2423 // buffer. We add as few as necessary to delete just the part
2424 // of the original text that has changed.
2425 // When using the longest match, edited the match or used
2426 // CTRL-E then don't use the current match.
2427 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002428 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002429 else
2430 ptr = NULL;
2431 ins_compl_fixRedoBufForLeader(ptr);
2432 }
2433
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002434 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002435
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002436 // When completing whole lines: fix indent for 'cindent'.
2437 // Otherwise, break line if it's too long.
2438 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2439 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002440 // re-indent the current line
2441 if (want_cindent)
2442 {
2443 do_c_expr_indent();
2444 want_cindent = FALSE; // don't do it again
2445 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002446 }
2447 else
2448 {
2449 int prev_col = curwin->w_cursor.col;
2450
2451 // put the cursor on the last char, for 'tw' formatting
2452 if (prev_col > 0)
2453 dec_cursor();
2454 // only format when something was inserted
2455 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2456 insertchar(NUL, 0, -1);
2457 if (prev_col > 0
2458 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2459 inc_cursor();
2460 }
2461
2462 // If the popup menu is displayed pressing CTRL-Y means accepting
2463 // the selection without inserting anything. When
2464 // compl_enter_selects is set the Enter key does the same.
2465 if ((c == Ctrl_Y || (compl_enter_selects
2466 && (c == CAR || c == K_KENTER || c == NL)))
2467 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002468 {
2469 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002470 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002471 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002472
2473 // CTRL-E means completion is Ended, go back to the typed text.
2474 // but only do this, if the Popup is still visible
2475 if (c == Ctrl_E)
2476 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002477 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002478 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002479
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002480 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002481 if (compl_leader.string != NULL)
2482 {
2483 p = compl_leader.string;
2484 plen = compl_leader.length;
2485 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002486 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002487 {
2488 p = compl_orig_text.string;
2489 plen = compl_orig_text.length;
2490 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002491 if (p != NULL)
2492 {
2493 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002494
John Marriott5e6ea922024-11-23 14:01:57 +01002495 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002496 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002497 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002498 retval = TRUE;
2499 }
2500
2501 auto_format(FALSE, TRUE);
2502
2503 // Trigger the CompleteDonePre event to give scripts a chance to
2504 // act upon the completion before clearing the info, and restore
2505 // ctrl_x_mode, so that complete_info() can be used.
2506 ctrl_x_mode = prev_mode;
2507 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2508
2509 ins_compl_free();
2510 compl_started = FALSE;
2511 compl_matches = 0;
2512 if (!shortmess(SHM_COMPLETIONMENU))
2513 msg_clr_cmdline(); // necessary for "noshowmode"
2514 ctrl_x_mode = CTRL_X_NORMAL;
2515 compl_enter_selects = FALSE;
2516 if (edit_submode != NULL)
2517 {
2518 edit_submode = NULL;
2519 showmode();
2520 }
2521
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002522 if (c == Ctrl_C && cmdwin_type != 0)
2523 // Avoid the popup menu remains displayed when leaving the
2524 // command line window.
2525 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002526 // Indent now if a key was typed that is in 'cinkeys'.
2527 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2528 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002529 // Trigger the CompleteDone event to give scripts a chance to act
2530 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002531 trigger_complete_done_event(prev_mode, word);
2532 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002533
2534 return retval;
2535}
2536
2537/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002538 * Prepare for Insert mode completion, or stop it.
2539 * Called just after typing a character in Insert mode.
2540 * Returns TRUE when the character is not to be inserted;
2541 */
2542 int
2543ins_compl_prep(int c)
2544{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002545 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002546 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002547
2548 // Forget any previous 'special' messages if this is actually
2549 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2550 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2551 edit_submode_extra = NULL;
2552
zeertzjq440d4cb2023-03-02 17:51:32 +00002553 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002554 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002555 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002556 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002557 return retval;
2558
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002559#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002560 // Ignore mouse events in a popup window
2561 if (is_mouse_key(c))
2562 {
2563 // Ignore drag and release events, the position does not need to be in
2564 // the popup and it may have just closed.
2565 if (c == K_LEFTRELEASE
2566 || c == K_LEFTRELEASE_NM
2567 || c == K_MIDDLERELEASE
2568 || c == K_RIGHTRELEASE
2569 || c == K_X1RELEASE
2570 || c == K_X2RELEASE
2571 || c == K_LEFTDRAG
2572 || c == K_MIDDLEDRAG
2573 || c == K_RIGHTDRAG
2574 || c == K_X1DRAG
2575 || c == K_X2DRAG)
2576 return retval;
2577 if (popup_visible)
2578 {
2579 int row = mouse_row;
2580 int col = mouse_col;
2581 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2582
2583 if (wp != NULL && WIN_IS_POPUP(wp))
2584 return retval;
2585 }
2586 }
2587#endif
2588
zeertzjqdca29d92021-08-31 19:12:51 +02002589 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2590 {
2591 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2592 || !vim_is_ctrl_x_key(c))
2593 {
2594 // Not starting another completion mode.
2595 ctrl_x_mode = CTRL_X_CMDLINE;
2596
2597 // CTRL-X CTRL-Z should stop completion without inserting anything
2598 if (c == Ctrl_Z)
2599 retval = TRUE;
2600 }
2601 else
2602 {
2603 ctrl_x_mode = CTRL_X_CMDLINE;
2604
2605 // Other CTRL-X keys first stop completion, then start another
2606 // completion mode.
2607 ins_compl_prep(' ');
2608 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2609 }
2610 }
2611
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002612 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002613 if (ctrl_x_mode_not_defined_yet()
2614 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002615 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002616 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002617 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002618 }
2619
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002620 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002621 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2622 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002623 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002624 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002625 {
2626 // We're already in CTRL-X mode, do we stay in it?
2627 if (!vim_is_ctrl_x_key(c))
2628 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002629 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002630 ctrl_x_mode = CTRL_X_NORMAL;
2631 else
2632 ctrl_x_mode = CTRL_X_FINISHED;
2633 edit_submode = NULL;
2634 }
2635 showmode();
2636 }
2637
2638 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2639 {
2640 // Show error message from attempted keyword completion (probably
2641 // 'Pattern not found') until another key is hit, then go back to
2642 // showing what mode we are in.
2643 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002644 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002645 && c != Ctrl_R && !ins_compl_pum_key(c))
2646 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002647 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002648 }
2649 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2650 // Trigger the CompleteDone event to give scripts a chance to act
2651 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002652 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002653
LemonBoy2bf52dd2022-04-09 18:17:34 +01002654 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002655
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002656 // reset continue_* if we left expansion-mode, if we stay they'll be
2657 // (re)set properly in ins_complete()
2658 if (!vim_is_ctrl_x_key(c))
2659 {
2660 compl_cont_status = 0;
2661 compl_cont_mode = 0;
2662 }
2663
2664 return retval;
2665}
2666
2667/*
2668 * Fix the redo buffer for the completion leader replacing some of the typed
2669 * text. This inserts backspaces and appends the changed text.
2670 * "ptr" is the known leader text or NUL.
2671 */
2672 static void
2673ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2674{
John Marriott5e6ea922024-11-23 14:01:57 +01002675 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002676 char_u *p;
2677 char_u *ptr = ptr_arg;
2678
2679 if (ptr == NULL)
2680 {
John Marriott5e6ea922024-11-23 14:01:57 +01002681 if (compl_leader.string != NULL)
2682 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002683 else
2684 return; // nothing to do
2685 }
John Marriott5e6ea922024-11-23 14:01:57 +01002686 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002687 {
John Marriott5e6ea922024-11-23 14:01:57 +01002688 p = compl_orig_text.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002689 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2690 ;
2691 if (len > 0)
2692 len -= (*mb_head_off)(p, p + len);
2693 for (p += len; *p != NUL; MB_PTR_ADV(p))
2694 AppendCharToRedobuff(K_BS);
2695 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002696 if (ptr != NULL)
2697 AppendToRedobuffLit(ptr + len, -1);
2698}
2699
2700/*
2701 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2702 * (depending on flag) starting from buf and looking for a non-scanned
2703 * buffer (other than curbuf). curbuf is special, if it is called with
2704 * buf=curbuf then it has to be the first call for a given flag/expansion.
2705 *
2706 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2707 */
2708 static buf_T *
2709ins_compl_next_buf(buf_T *buf, int flag)
2710{
2711 static win_T *wp = NULL;
2712
2713 if (flag == 'w') // just windows
2714 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002715 if (buf == curbuf || !win_valid(wp))
2716 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002717 wp = curwin;
2718 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2719 && wp->w_buffer->b_scanned)
2720 ;
2721 buf = wp->w_buffer;
2722 }
2723 else
2724 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2725 // (unlisted buffers)
2726 // When completing whole lines skip unloaded buffers.
2727 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2728 && ((flag == 'U'
2729 ? buf->b_p_bl
2730 : (!buf->b_p_bl
2731 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2732 || buf->b_scanned))
2733 ;
2734 return buf;
2735}
2736
2737#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002738
2739# ifdef FEAT_EVAL
2740static callback_T cfu_cb; // 'completefunc' callback function
2741static callback_T ofu_cb; // 'omnifunc' callback function
2742static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2743# endif
2744
2745/*
2746 * Copy a global callback function to a buffer local callback.
2747 */
2748 static void
2749copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2750{
2751 free_callback(bufcb);
2752 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2753 copy_callback(bufcb, globcb);
2754}
2755
2756/*
2757 * Parse the 'completefunc' option value and set the callback function.
2758 * Invoked when the 'completefunc' option is set. The option value can be a
2759 * name of a function (string), or function(<name>) or funcref(<name>) or a
2760 * lambda expression.
2761 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002762 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002763did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002764{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002765 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2766 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002767
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002768 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002769
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002770 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002771}
2772
2773/*
2774 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002775 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002776 */
2777 void
2778set_buflocal_cfu_callback(buf_T *buf UNUSED)
2779{
2780# ifdef FEAT_EVAL
2781 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2782# endif
2783}
2784
2785/*
2786 * Parse the 'omnifunc' option value and set the callback function.
2787 * Invoked when the 'omnifunc' option is set. The option value can be a
2788 * name of a function (string), or function(<name>) or funcref(<name>) or a
2789 * lambda expression.
2790 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002791 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002792did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002793{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002794 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2795 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002796
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002797 set_buflocal_ofu_callback(curbuf);
2798 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002799}
2800
2801/*
2802 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002803 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002804 */
2805 void
2806set_buflocal_ofu_callback(buf_T *buf UNUSED)
2807{
2808# ifdef FEAT_EVAL
2809 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2810# endif
2811}
2812
2813/*
2814 * Parse the 'thesaurusfunc' option value and set the callback function.
2815 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2816 * name of a function (string), or function(<name>) or funcref(<name>) or a
2817 * lambda expression.
2818 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002819 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002820did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002821{
2822 int retval;
2823
zeertzjq6eda2692024-11-03 09:23:33 +01002824 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002825 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002826 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2827 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002828 else
2829 {
2830 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002831 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002832 // when using :set, free the local callback
2833 if (!(args->os_flags & OPT_GLOBAL))
2834 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002835 }
2836
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002837 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002838}
2839
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002840/*
2841 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002842 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002843 */
2844 int
2845set_ref_in_insexpand_funcs(int copyID)
2846{
2847 int abort = FALSE;
2848
2849 abort = set_ref_in_callback(&cfu_cb, copyID);
2850 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2851 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2852
2853 return abort;
2854}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002855
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002856/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002857 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002858 */
2859 static char_u *
2860get_complete_funcname(int type)
2861{
2862 switch (type)
2863 {
2864 case CTRL_X_FUNCTION:
2865 return curbuf->b_p_cfu;
2866 case CTRL_X_OMNI:
2867 return curbuf->b_p_ofu;
2868 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002869 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002870 default:
2871 return (char_u *)"";
2872 }
2873}
2874
2875/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002876 * Get the callback to use for insert mode completion.
2877 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002878 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002879get_insert_callback(int type)
2880{
2881 if (type == CTRL_X_FUNCTION)
2882 return &curbuf->b_cfu_cb;
2883 if (type == CTRL_X_OMNI)
2884 return &curbuf->b_ofu_cb;
2885 // CTRL_X_THESAURUS
2886 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2887}
2888
2889/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002890 * Execute user defined complete function 'completefunc', 'omnifunc' or
2891 * 'thesaurusfunc', and get matches in "matches".
2892 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002893 */
2894 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002895expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002896{
2897 list_T *matchlist = NULL;
2898 dict_T *matchdict = NULL;
2899 typval_T args[3];
2900 char_u *funcname;
2901 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002902 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002903 typval_T rettv;
2904 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002905 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002906
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002907 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002908 if (*funcname == NUL)
2909 return;
2910
2911 // Call 'completefunc' to obtain the list of matches.
2912 args[0].v_type = VAR_NUMBER;
2913 args[0].vval.v_number = 0;
2914 args[1].v_type = VAR_STRING;
2915 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2916 args[2].v_type = VAR_UNKNOWN;
2917
2918 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002919 // Lock the text to avoid weird things from happening. Also disallow
2920 // switching to another window, it should not be needed and may end up in
2921 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002922 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002923
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002924 cb = get_insert_callback(type);
2925 retval = call_callback(cb, 0, &rettv, 2, args);
2926
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002927 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002928 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002929 {
2930 switch (rettv.v_type)
2931 {
2932 case VAR_LIST:
2933 matchlist = rettv.vval.v_list;
2934 break;
2935 case VAR_DICT:
2936 matchdict = rettv.vval.v_dict;
2937 break;
2938 case VAR_SPECIAL:
2939 if (rettv.vval.v_number == VVAL_NONE)
2940 compl_opt_suppress_empty = TRUE;
2941 // FALLTHROUGH
2942 default:
2943 // TODO: Give error message?
2944 clear_tv(&rettv);
2945 break;
2946 }
2947 }
zeertzjqcfe45652022-05-27 17:26:55 +01002948 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002949
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002950 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002951 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002952 validate_cursor();
2953 if (!EQUAL_POS(curwin->w_cursor, pos))
2954 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002955 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002956 goto theend;
2957 }
2958
2959 if (matchlist != NULL)
2960 ins_compl_add_list(matchlist);
2961 else if (matchdict != NULL)
2962 ins_compl_add_dict(matchdict);
2963
2964theend:
2965 // Restore State, it might have been changed.
2966 State = save_State;
2967
2968 if (matchdict != NULL)
2969 dict_unref(matchdict);
2970 if (matchlist != NULL)
2971 list_unref(matchlist);
2972}
2973#endif // FEAT_COMPL_FUNC
2974
2975#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02002976
2977 static inline int
2978get_user_highlight_attr(char_u *hlname)
2979{
2980 if (hlname != NULL && *hlname != NUL)
2981 return syn_name2attr(hlname);
2982 return -1;
2983}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002984/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002985 * Add a match to the list of matches from a typeval_T.
2986 * If the given string is already in the list of completions, then return
2987 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2988 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002989 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002990 */
2991 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002992ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002993{
2994 char_u *word;
2995 int dup = FALSE;
2996 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002997 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002998 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002999 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003000 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003001 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003002 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003003 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003004
Bram Moolenaar08928322020-01-04 14:32:48 +01003005 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003006 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3007 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003008 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3009 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3010 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3011 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3012 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003013
glepnir0fe17f82024-10-08 22:26:44 +02003014 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003015 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003016
3017 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003018 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003019
Bram Moolenaard61efa52022-07-23 09:52:04 +01003020 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3021 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3022 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003023 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003024 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3025 dup = dict_get_number(tv->vval.v_dict, "dup");
3026 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3027 empty = dict_get_number(tv->vval.v_dict, "empty");
3028 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3029 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003030 flags |= CP_EQUAL;
3031 }
3032 else
3033 {
3034 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003035 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003036 }
3037 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003038 {
3039 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003040 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003041 }
glepnir508e7852024-07-25 21:39:08 +02003042 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01003043 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003044 if (status != OK)
3045 clear_tv(&user_data);
3046 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003047}
3048
3049/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003050 * Add completions from a list.
3051 */
3052 static void
3053ins_compl_add_list(list_T *list)
3054{
3055 listitem_T *li;
3056 int dir = compl_direction;
3057
3058 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003059 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003060 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003061 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003062 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003063 // if dir was BACKWARD then honor it just once
3064 dir = FORWARD;
3065 else if (did_emsg)
3066 break;
3067 }
3068}
3069
3070/*
3071 * Add completions from a dict.
3072 */
3073 static void
3074ins_compl_add_dict(dict_T *dict)
3075{
3076 dictitem_T *di_refresh;
3077 dictitem_T *di_words;
3078
3079 // Check for optional "refresh" item.
3080 compl_opt_refresh_always = FALSE;
3081 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3082 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3083 {
3084 char_u *v = di_refresh->di_tv.vval.v_string;
3085
3086 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3087 compl_opt_refresh_always = TRUE;
3088 }
3089
3090 // Add completions from a "words" list.
3091 di_words = dict_find(dict, (char_u *)"words", 5);
3092 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3093 ins_compl_add_list(di_words->di_tv.vval.v_list);
3094}
3095
3096/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003097 * Start completion for the complete() function.
3098 * "startcol" is where the matched text starts (1 is first column).
3099 * "list" is the list of matches.
3100 */
3101 static void
3102set_completion(colnr_T startcol, list_T *list)
3103{
3104 int save_w_wrow = curwin->w_wrow;
3105 int save_w_leftcol = curwin->w_leftcol;
3106 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003107 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003108 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3109 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3110 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003111
3112 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003113 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003114 ins_compl_prep(' ');
3115 ins_compl_clear();
3116 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003117 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003118
3119 compl_direction = FORWARD;
3120 if (startcol > curwin->w_cursor.col)
3121 startcol = curwin->w_cursor.col;
3122 compl_col = startcol;
3123 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3124 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003125 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3126 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003127 if (p_ic)
3128 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003129 if (compl_orig_text.string == NULL)
3130 {
3131 compl_orig_text.length = 0;
3132 return;
3133 }
3134 compl_orig_text.length = (size_t)compl_length;
3135 if (ins_compl_add(compl_orig_text.string,
3136 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3137 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003138 return;
3139
3140 ctrl_x_mode = CTRL_X_EVAL;
3141
3142 ins_compl_add_list(list);
3143 compl_matches = ins_compl_make_cyclic();
3144 compl_started = TRUE;
3145 compl_used_match = TRUE;
3146 compl_cont_status = 0;
3147
3148 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003149 int no_select = compl_no_select || compl_longest;
3150 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003151 {
3152 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003153 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003154 // Down/Up has no real effect.
3155 ins_complete(K_UP, FALSE);
3156 }
3157 else
3158 ins_complete(Ctrl_N, FALSE);
3159 compl_enter_selects = compl_no_insert;
3160
3161 // Lazily show the popup menu, unless we got interrupted.
3162 if (!compl_interrupted)
3163 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003164 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003165 out_flush();
3166}
3167
3168/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003169 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003170 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003171 void
3172f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003173{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003174 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003175
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003176 if (in_vim9script()
3177 && (check_for_number_arg(argvars, 0) == FAIL
3178 || check_for_list_arg(argvars, 1) == FAIL))
3179 return;
3180
Bram Moolenaar24959102022-05-07 20:01:16 +01003181 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003182 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003183 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003184 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003185 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003186
3187 // Check for undo allowed here, because if something was already inserted
3188 // the line was already saved for undo and this check isn't done.
3189 if (!undo_allowed())
3190 return;
3191
Bram Moolenaard83392a2022-09-01 12:22:46 +01003192 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003193 {
3194 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3195 if (startcol > 0)
3196 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003197 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003198}
3199
3200/*
3201 * "complete_add()" function
3202 */
3203 void
3204f_complete_add(typval_T *argvars, typval_T *rettv)
3205{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003206 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003207 return;
3208
Bram Moolenaar440cf092021-04-03 20:13:30 +02003209 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003210}
3211
3212/*
3213 * "complete_check()" function
3214 */
3215 void
3216f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3217{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003218 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003219 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003220
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003221 ins_compl_check_keys(0, TRUE);
3222 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003223
3224 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003225}
3226
3227/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003228 * Return Insert completion mode name string
3229 */
3230 static char_u *
3231ins_compl_mode(void)
3232{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003233 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003234 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3235
3236 return (char_u *)"";
3237}
3238
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003239/*
3240 * Assign the sequence number to all the completion matches which don't have
3241 * one assigned yet.
3242 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003243 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003244ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003245{
3246 int number = 0;
3247 compl_T *match;
3248
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003249 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003250 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003251 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003252 // This should normally succeed already at the first loop
3253 // cycle, so it's fast!
3254 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003255 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003256 if (match->cp_number != -1)
3257 {
3258 number = match->cp_number;
3259 break;
3260 }
3261 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003262 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003263 for (match = match->cp_next;
3264 match != NULL && match->cp_number == -1;
3265 match = match->cp_next)
3266 match->cp_number = ++number;
3267 }
3268 else // BACKWARD
3269 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003270 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003271 // number. This should normally succeed already at the
3272 // first loop cycle, so it's fast!
3273 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003274 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003275 if (match->cp_number != -1)
3276 {
3277 number = match->cp_number;
3278 break;
3279 }
3280 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003281 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003282 for (match = match->cp_prev; match
3283 && match->cp_number == -1;
3284 match = match->cp_prev)
3285 match->cp_number = ++number;
3286 }
3287}
3288
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003289/*
glepnir037b0282025-01-16 14:37:44 +01003290 * Fill the dict of complete_info
3291 */
3292 static void
3293fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3294{
3295 dict_add_string(di, "word", match->cp_str.string);
3296 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3297 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3298 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3299 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3300 if (add_match)
3301 dict_add_bool(di, "match", match->cp_in_match_array);
3302 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3303 // Add an empty string for backwards compatibility
3304 dict_add_string(di, "user_data", (char_u *)"");
3305 else
3306 dict_add_tv(di, "user_data", &match->cp_user_data);
3307}
3308
3309/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003310 * Get complete information
3311 */
3312 static void
3313get_complete_info(list_T *what_list, dict_T *retdict)
3314{
3315 int ret = OK;
3316 listitem_T *item;
3317#define CI_WHAT_MODE 0x01
3318#define CI_WHAT_PUM_VISIBLE 0x02
3319#define CI_WHAT_ITEMS 0x04
3320#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003321#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003322#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003323#define CI_WHAT_ALL 0xff
3324 int what_flag;
3325
3326 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003327 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003328 else
3329 {
3330 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003331 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003332 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003333 {
3334 char_u *what = tv_get_string(&item->li_tv);
3335
3336 if (STRCMP(what, "mode") == 0)
3337 what_flag |= CI_WHAT_MODE;
3338 else if (STRCMP(what, "pum_visible") == 0)
3339 what_flag |= CI_WHAT_PUM_VISIBLE;
3340 else if (STRCMP(what, "items") == 0)
3341 what_flag |= CI_WHAT_ITEMS;
3342 else if (STRCMP(what, "selected") == 0)
3343 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003344 else if (STRCMP(what, "completed") == 0)
3345 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003346 else if (STRCMP(what, "matches") == 0)
3347 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003348 }
3349 }
3350
3351 if (ret == OK && (what_flag & CI_WHAT_MODE))
3352 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3353
3354 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3355 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3356
glepnir037b0282025-01-16 14:37:44 +01003357 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3358 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003359 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003360 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003361 dict_T *di;
3362 compl_T *match;
3363 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003364 int has_items = what_flag & CI_WHAT_ITEMS;
3365 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003366 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003367
glepnird4088ed2024-12-31 10:55:22 +01003368 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003369 {
3370 li = list_alloc();
3371 if (li == NULL)
3372 return;
glepnird4088ed2024-12-31 10:55:22 +01003373 ret = dict_add_list(retdict, (has_matches && !has_items)
3374 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003375 }
3376 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3377 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3378 ins_compl_update_sequence_numbers();
3379 if (ret == OK && compl_first_match != NULL)
3380 {
3381 int list_idx = 0;
3382 match = compl_first_match;
3383 do
3384 {
3385 if (!match_at_original_text(match))
3386 {
glepnird4088ed2024-12-31 10:55:22 +01003387 if (has_items
3388 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003389 {
3390 di = dict_alloc();
3391 if (di == NULL)
3392 return;
3393 ret = list_append_dict(li, di);
3394 if (ret != OK)
3395 return;
glepnir037b0282025-01-16 14:37:44 +01003396 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003397 }
glepnird4088ed2024-12-31 10:55:22 +01003398 if (compl_curr_match != NULL
3399 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003400 selected_idx = list_idx;
3401 list_idx += 1;
3402 }
3403 match = match->cp_next;
3404 }
3405 while (match != NULL && !is_first_match(match));
3406 }
3407 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3408 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003409
glepnir037b0282025-01-16 14:37:44 +01003410 if (ret == OK && selected_idx != -1 && has_completed)
3411 {
3412 di = dict_alloc();
3413 if (di == NULL)
3414 return;
3415 fill_complete_info_dict(di, compl_curr_match, FALSE);
3416 ret = dict_add_dict(retdict, "completed", di);
3417 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003418 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003419}
3420
3421/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003422 * "complete_info()" function
3423 */
3424 void
3425f_complete_info(typval_T *argvars, typval_T *rettv)
3426{
3427 list_T *what_list = NULL;
3428
Bram Moolenaar93a10962022-06-16 11:42:09 +01003429 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003430 return;
3431
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003432 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3433 return;
3434
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003435 if (argvars[0].v_type != VAR_UNKNOWN)
3436 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003437 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003438 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003439 what_list = argvars[0].vval.v_list;
3440 }
3441 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003442}
3443#endif
3444
3445/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003446 * Returns TRUE when using a user-defined function for thesaurus completion.
3447 */
3448 static int
3449thesaurus_func_complete(int type UNUSED)
3450{
3451#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003452 return type == CTRL_X_THESAURUS
3453 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003454#else
3455 return FALSE;
3456#endif
3457}
3458
3459/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003460 * Return value of process_next_cpt_value()
3461 */
3462enum
3463{
3464 INS_COMPL_CPT_OK = 1,
3465 INS_COMPL_CPT_CONT,
3466 INS_COMPL_CPT_END
3467};
3468
3469/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003470 * state information used for getting the next set of insert completion
3471 * matches.
3472 */
3473typedef struct
3474{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003475 char_u *e_cpt_copy; // copy of 'complete'
3476 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003477 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003478 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003479 pos_T prev_match_pos; // previous match position
3480 int set_match_pos; // save first_match_pos/last_match_pos
3481 pos_T first_match_pos; // first match position
3482 pos_T last_match_pos; // last match position
3483 int found_all; // found all matches of a certain type.
3484 char_u *dict; // dictionary file to search
3485 int dict_f; // "dict" is an exact file name or not
3486} ins_compl_next_state_T;
3487
3488/*
3489 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003490 *
3491 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003492 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003493 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003494 * st->found_all - all matches of this type are found
3495 * st->ins_buf - search for completions in this buffer
3496 * st->first_match_pos - position of the first completion match
3497 * st->last_match_pos - position of the last completion match
3498 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003499 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003500 * st->dict - name of the dictionary or thesaurus file to search
3501 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003502 *
3503 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003504 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3505 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003506 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003507 */
3508 static int
3509process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003510 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003511 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003512 pos_T *start_match_pos,
3513 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003514{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003515 int compl_type = -1;
3516 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003517
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003518 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003519
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003520 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3521 st->e_cpt++;
3522
3523 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003524 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003525 st->ins_buf = curbuf;
3526 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003527 // Move the cursor back one character so that ^N can match the
3528 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003529 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003530 {
3531 // Move the cursor to after the last character in the
3532 // buffer, so that word at start of buffer is found
3533 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003534 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003535 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003536 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003537 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003538 compl_type = 0;
3539
3540 // Remember the first match so that the loop stops when we
3541 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003542 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003543 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003544 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003545 && (st->ins_buf = ins_compl_next_buf(
3546 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003547 {
3548 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003549 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003550 {
3551 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003552 st->first_match_pos.col = st->last_match_pos.col = 0;
3553 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3554 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003555 compl_type = 0;
3556 }
3557 else // unloaded buffer, scan like dictionary
3558 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003559 st->found_all = TRUE;
3560 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003561 {
3562 status = INS_COMPL_CPT_CONT;
3563 goto done;
3564 }
3565 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003566 st->dict = st->ins_buf->b_fname;
3567 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003568 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003569 if (!shortmess(SHM_COMPLETIONSCAN))
3570 {
3571 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3572 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3573 st->ins_buf->b_fname == NULL
3574 ? buf_spname(st->ins_buf)
3575 : st->ins_buf->b_sfname == NULL
3576 ? st->ins_buf->b_fname
3577 : st->ins_buf->b_sfname);
3578 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3579 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003580 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003581 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003582 status = INS_COMPL_CPT_END;
3583 else
3584 {
3585 if (ctrl_x_mode_line_or_eval())
3586 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003587 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003588 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003589 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003590 compl_type = CTRL_X_DICTIONARY;
3591 else
3592 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003593 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003594 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003595 st->dict = st->e_cpt;
3596 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003597 }
3598 }
3599#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003600 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003601 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003602 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003603 compl_type = CTRL_X_PATH_DEFINES;
3604#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003605 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003606 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003607 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003608 if (!shortmess(SHM_COMPLETIONSCAN))
3609 {
3610 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3611 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3612 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3613 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003614 }
3615 else
3616 compl_type = -1;
3617
3618 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003619 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003620
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003621 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003622 if (compl_type == -1)
3623 status = INS_COMPL_CPT_CONT;
3624 }
3625
3626done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003627 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003628 return status;
3629}
3630
3631#ifdef FEAT_FIND_ID
3632/*
3633 * Get the next set of identifiers or defines matching "compl_pattern" in
3634 * included files.
3635 */
3636 static void
3637get_next_include_file_completion(int compl_type)
3638{
John Marriott5e6ea922024-11-23 14:01:57 +01003639 find_pattern_in_path(compl_pattern.string, compl_direction,
3640 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003641 (compl_type == CTRL_X_PATH_DEFINES
3642 && !(compl_cont_status & CONT_SOL))
3643 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003644 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003645}
3646#endif
3647
3648/*
3649 * Get the next set of words matching "compl_pattern" in dictionary or
3650 * thesaurus files.
3651 */
3652 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003653get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003654{
3655#ifdef FEAT_COMPL_FUNC
3656 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003657 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003658 else
3659#endif
3660 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003661 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003662 : (compl_type == CTRL_X_THESAURUS
3663 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3664 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003665 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003666 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003667 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003668}
3669
3670/*
3671 * Get the next set of tag names matching "compl_pattern".
3672 */
3673 static void
3674get_next_tag_completion(void)
3675{
3676 int save_p_ic;
3677 char_u **matches;
3678 int num_matches;
3679
3680 // set p_ic according to p_ic, p_scs and pat for find_tags().
3681 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003682 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003683
3684 // Find up to TAG_MANY matches. Avoids that an enormous number
3685 // of matches is found when compl_pattern is empty
3686 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003687 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003688 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003689 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003690 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3691 ins_compl_add_matches(num_matches, matches, p_ic);
3692 g_tag_at_cursor = FALSE;
3693 p_ic = save_p_ic;
3694}
3695
3696/*
glepnir8159fb12024-07-17 20:32:54 +02003697 * Compare function for qsort
3698 */
3699static int compare_scores(const void *a, const void *b)
3700{
3701 int idx_a = *(const int *)a;
3702 int idx_b = *(const int *)b;
3703 int score_a = compl_fuzzy_scores[idx_a];
3704 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003705 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3706 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003707}
3708
3709/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003710 * Get the next set of filename matching "compl_pattern".
3711 */
3712 static void
3713get_next_filename_completion(void)
3714{
3715 char_u **matches;
3716 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003717 char_u *ptr;
3718 garray_T fuzzy_indices;
3719 int i;
3720 int score;
3721 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003722 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003723 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3724 char_u **sorted_matches;
3725 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003726 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003727
glepnirb9de1a02024-08-02 19:14:38 +02003728#ifdef BACKSLASH_IN_FILENAME
3729 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3730 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3731#else
3732 char pathsep = PATHSEP;
3733#endif
3734
glepnir8159fb12024-07-17 20:32:54 +02003735 if (in_fuzzy)
3736 {
glepnirb9de1a02024-08-02 19:14:38 +02003737#ifdef BACKSLASH_IN_FILENAME
3738 if (curbuf->b_p_csl[0] == 's')
3739 {
John Marriott5e6ea922024-11-23 14:01:57 +01003740 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003741 {
3742 if (leader[i] == '\\')
3743 leader[i] = '/';
3744 }
3745 }
3746 else if (curbuf->b_p_csl[0] == 'b')
3747 {
John Marriott5e6ea922024-11-23 14:01:57 +01003748 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003749 {
3750 if (leader[i] == '/')
3751 leader[i] = '\\';
3752 }
3753 }
3754#endif
3755 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003756 if (last_sep == NULL)
3757 {
3758 // No path separator or separator is the last character,
3759 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003760 VIM_CLEAR_STRING(compl_pattern);
3761 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3762 if (compl_pattern.string == NULL)
3763 return;
3764 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003765 }
3766 else if (*(last_sep + 1) == '\0')
3767 in_fuzzy = FALSE;
3768 else
3769 {
3770 // Split leader into path and file parts
3771 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003772 char_u *path_with_wildcard;
3773
3774 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003775 if (path_with_wildcard != NULL)
3776 {
John Marriott5e6ea922024-11-23 14:01:57 +01003777 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3778 VIM_CLEAR_STRING(compl_pattern);
3779 compl_pattern.string = path_with_wildcard;
3780 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003781
3782 // Move leader to the file part
3783 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003784 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003785 }
3786 }
glepnir8159fb12024-07-17 20:32:54 +02003787 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003788
John Marriott5e6ea922024-11-23 14:01:57 +01003789 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003790 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3791 return;
3792
3793 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003794 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003795#ifdef BACKSLASH_IN_FILENAME
3796 if (curbuf->b_p_csl[0] != NUL)
3797 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003798 for (i = 0; i < num_matches; ++i)
3799 {
glepnir8159fb12024-07-17 20:32:54 +02003800 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003801 while (*ptr != NUL)
3802 {
3803 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3804 *ptr = '/';
3805 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3806 *ptr = '\\';
3807 ptr += (*mb_ptr2len)(ptr);
3808 }
3809 }
3810 }
3811#endif
glepnir8159fb12024-07-17 20:32:54 +02003812
3813 if (in_fuzzy)
3814 {
3815 ga_init2(&fuzzy_indices, sizeof(int), 10);
3816 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3817
3818 for (i = 0; i < num_matches; i++)
3819 {
3820 ptr = matches[i];
3821 score = fuzzy_match_str(ptr, leader);
3822 if (score > 0)
3823 {
3824 if (ga_grow(&fuzzy_indices, 1) == OK)
3825 {
3826 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3827 compl_fuzzy_scores[i] = score;
3828 fuzzy_indices.ga_len++;
3829 }
3830 }
3831 }
3832
Christian Brabandt220474d2024-07-20 13:26:44 +02003833 // prevent qsort from deref NULL pointer
3834 if (fuzzy_indices.ga_len > 0)
3835 {
3836 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3837 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003838
Christian Brabandt220474d2024-07-20 13:26:44 +02003839 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3840 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3841 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003842
Christian Brabandt220474d2024-07-20 13:26:44 +02003843 FreeWild(num_matches, matches);
3844 matches = sorted_matches;
3845 num_matches = fuzzy_indices.ga_len;
3846 }
glepnir6b6280c2024-07-27 16:25:45 +02003847 else if (leader_len > 0)
3848 {
3849 FreeWild(num_matches, matches);
3850 num_matches = 0;
3851 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003852
glepnir8159fb12024-07-17 20:32:54 +02003853 vim_free(compl_fuzzy_scores);
3854 ga_clear(&fuzzy_indices);
3855 }
3856
glepnir6b6280c2024-07-27 16:25:45 +02003857 if (num_matches > 0)
3858 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003859}
3860
3861/*
3862 * Get the next set of command-line completions matching "compl_pattern".
3863 */
3864 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003865get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003866{
3867 char_u **matches;
3868 int num_matches;
3869
John Marriott5e6ea922024-11-23 14:01:57 +01003870 if (expand_cmdline(&compl_xp, compl_pattern.string,
3871 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003872 ins_compl_add_matches(num_matches, matches, FALSE);
3873}
3874
3875/*
3876 * Get the next set of spell suggestions matching "compl_pattern".
3877 */
3878 static void
3879get_next_spell_completion(linenr_T lnum UNUSED)
3880{
3881#ifdef FEAT_SPELL
3882 char_u **matches;
3883 int num_matches;
3884
John Marriott5e6ea922024-11-23 14:01:57 +01003885 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003886 if (num_matches > 0)
3887 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003888 else
3889 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003890#endif
3891}
3892
3893/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003894 * Return the next word or line from buffer "ins_buf" at position
3895 * "cur_match_pos" for completion. The length of the match is set in "len".
3896 */
3897 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003898ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003899 buf_T *ins_buf, // buffer being scanned
3900 pos_T *cur_match_pos, // current match position
3901 int *match_len,
3902 int *cont_s_ipos) // next ^X<> will set initial_pos
3903{
3904 char_u *ptr;
3905 int len;
3906
3907 *match_len = 0;
3908 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3909 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003910 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003911 if (ctrl_x_mode_line_or_eval())
3912 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003913 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003914 {
3915 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3916 return NULL;
3917 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003918 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003919 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003920 {
3921 char_u *tmp_ptr = ptr;
3922
3923 ptr = skipwhite(tmp_ptr);
3924 len -= (int)(ptr - tmp_ptr);
3925 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003926 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003927 }
3928 else
3929 {
3930 char_u *tmp_ptr = ptr;
3931
John Marriott5e6ea922024-11-23 14:01:57 +01003932 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003933 {
3934 tmp_ptr += compl_length;
3935 // Skip if already inside a word.
3936 if (vim_iswordp(tmp_ptr))
3937 return NULL;
3938 // Find start of next word.
3939 tmp_ptr = find_word_start(tmp_ptr);
3940 }
3941 // Find end of this word.
3942 tmp_ptr = find_word_end(tmp_ptr);
3943 len = (int)(tmp_ptr - ptr);
3944
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003945 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003946 {
3947 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3948 {
3949 // Try next line, if any. the new word will be
3950 // "join" as if the normal command "J" was used.
3951 // IOSIZE is always greater than
3952 // compl_length, so the next STRNCPY always
3953 // works -- Acevedo
3954 STRNCPY(IObuff, ptr, len);
3955 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3956 tmp_ptr = ptr = skipwhite(ptr);
3957 // Find start of next word.
3958 tmp_ptr = find_word_start(tmp_ptr);
3959 // Find end of next word.
3960 tmp_ptr = find_word_end(tmp_ptr);
3961 if (tmp_ptr > ptr)
3962 {
3963 if (*ptr != ')' && IObuff[len - 1] != TAB)
3964 {
3965 if (IObuff[len - 1] != ' ')
3966 IObuff[len++] = ' ';
3967 // IObuf =~ "\k.* ", thus len >= 2
3968 if (p_js
3969 && (IObuff[len - 2] == '.'
3970 || (vim_strchr(p_cpo, CPO_JOINSP)
3971 == NULL
3972 && (IObuff[len - 2] == '?'
3973 || IObuff[len - 2] == '!'))))
3974 IObuff[len++] = ' ';
3975 }
3976 // copy as much as possible of the new word
3977 if (tmp_ptr - ptr >= IOSIZE - len)
3978 tmp_ptr = ptr + IOSIZE - len - 1;
3979 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3980 len += (int)(tmp_ptr - ptr);
3981 *cont_s_ipos = TRUE;
3982 }
3983 IObuff[len] = NUL;
3984 ptr = IObuff;
3985 }
3986 if (len == compl_length)
3987 return NULL;
3988 }
3989 }
3990
3991 *match_len = len;
3992 return ptr;
3993}
3994
3995/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003996 * Get the next set of words matching "compl_pattern" for default completion(s)
3997 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003998 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3999 * position "st->start_pos" in the "compl_direction" direction. If
4000 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4001 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004002 * Returns OK if a new next match is found, otherwise returns FAIL.
4003 */
4004 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004005get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004006{
4007 int found_new_match = FAIL;
4008 int save_p_scs;
4009 int save_p_ws;
4010 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004011 char_u *ptr = NULL;
4012 int len = 0;
4013 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
4014 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004015
4016 // If 'infercase' is set, don't use 'smartcase' here
4017 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004018 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004019 p_scs = FALSE;
4020
4021 // Buffers other than curbuf are scanned from the beginning or the
4022 // end but never from the middle, thus setting nowrapscan in this
4023 // buffer is a good idea, on the other hand, we always set
4024 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4025 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004026 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004027 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004028 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004029 p_ws = TRUE;
4030 looped_around = FALSE;
4031 for (;;)
4032 {
4033 int cont_s_ipos = FALSE;
4034
4035 ++msg_silent; // Don't want messages for wrapscan.
4036
4037 // ctrl_x_mode_line_or_eval() || word-wise search that
4038 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02004039 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004040 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01004041 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02004042 else if (in_fuzzy)
4043 found_new_match = search_for_fuzzy_match(st->ins_buf,
4044 st->cur_match_pos, leader, compl_direction,
4045 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004046 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004047 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004048 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004049 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004050 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004051 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004052 {
4053 // set "compl_started" even on fail
4054 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004055 st->first_match_pos = *st->cur_match_pos;
4056 st->last_match_pos = *st->cur_match_pos;
4057 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004058 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004059 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4060 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004061 {
4062 found_new_match = FAIL;
4063 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004064 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004065 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4066 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4067 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004068 {
4069 if (looped_around)
4070 found_new_match = FAIL;
4071 else
4072 looped_around = TRUE;
4073 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004074 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004075 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4076 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4077 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004078 {
4079 if (looped_around)
4080 found_new_match = FAIL;
4081 else
4082 looped_around = TRUE;
4083 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004084 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004085 if (found_new_match == FAIL)
4086 break;
4087
4088 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004089 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004090 && start_pos->lnum == st->cur_match_pos->lnum
4091 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004092 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004093
glepnir8159fb12024-07-17 20:32:54 +02004094 if (!in_fuzzy)
4095 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4096 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004097 if (ptr == NULL)
4098 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004099
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004100 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004101 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004102 0, cont_s_ipos) != NOTDONE)
4103 {
4104 found_new_match = OK;
4105 break;
4106 }
4107 }
4108 p_scs = save_p_scs;
4109 p_ws = save_p_ws;
4110
4111 return found_new_match;
4112}
4113
4114/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004115 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004116 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004117 */
4118 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004119get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004120{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004121 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004122
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004123 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004124 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004125 case -1:
4126 break;
4127#ifdef FEAT_FIND_ID
4128 case CTRL_X_PATH_PATTERNS:
4129 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004130 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004131 break;
4132#endif
4133
4134 case CTRL_X_DICTIONARY:
4135 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004136 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4137 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004138 break;
4139
4140 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004141 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004142 break;
4143
4144 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004145 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004146 break;
4147
4148 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004149 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004150 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004151 break;
4152
4153#ifdef FEAT_COMPL_FUNC
4154 case CTRL_X_FUNCTION:
4155 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004156 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004157 break;
4158#endif
4159
4160 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004161 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004162 break;
4163
4164 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004165 found_new_match = get_next_default_completion(st, ini);
4166 if (found_new_match == FAIL && st->ins_buf == curbuf)
4167 st->found_all = TRUE;
4168 }
4169
4170 // check if compl_curr_match has changed, (e.g. other type of
4171 // expansion added something)
4172 if (type != 0 && compl_curr_match != compl_old_match)
4173 found_new_match = OK;
4174
4175 return found_new_match;
4176}
4177
4178/*
4179 * Get the next expansion(s), using "compl_pattern".
4180 * The search starts at position "ini" in curbuf and in the direction
4181 * compl_direction.
4182 * When "compl_started" is FALSE start at that position, otherwise continue
4183 * where we stopped searching before.
4184 * This may return before finding all the matches.
4185 * Return the total number of matches or -1 if still unknown -- Acevedo
4186 */
4187 static int
4188ins_compl_get_exp(pos_T *ini)
4189{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004190 static ins_compl_next_state_T st;
4191 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004192 int i;
4193 int found_new_match;
4194 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004195 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004196
4197 if (!compl_started)
4198 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004199 buf_T *buf;
4200
4201 FOR_ALL_BUFFERS(buf)
4202 buf->b_scanned = 0;
4203 if (!st_cleared)
4204 {
4205 CLEAR_FIELD(st);
4206 st_cleared = TRUE;
4207 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004208 st.found_all = FALSE;
4209 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004210 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004211 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004212 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4213 ? (char_u *)"." : curbuf->b_p_cpt);
4214 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004215 st.last_match_pos = st.first_match_pos = *ini;
4216 }
4217 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4218 st.ins_buf = curbuf; // In case the buffer was wiped out.
4219
4220 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004221 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004222 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004223
4224 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4225 for (;;)
4226 {
4227 found_new_match = FAIL;
4228 st.set_match_pos = FALSE;
4229
4230 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4231 // or if found_all says this entry is done. For ^X^L only use the
4232 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004233 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004234 && (!compl_started || st.found_all))
4235 {
glepnir8159fb12024-07-17 20:32:54 +02004236 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004237
4238 if (status == INS_COMPL_CPT_END)
4239 break;
4240 if (status == INS_COMPL_CPT_CONT)
4241 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004242 }
4243
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004244 // If complete() was called then compl_pattern has been reset. The
4245 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004246 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004247 break;
4248
4249 // get the next set of completion matches
4250 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004251
4252 // break the loop for specialized modes (use 'complete' just for the
4253 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4254 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004255 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4256 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004257 {
4258 if (got_int)
4259 break;
4260 // Fill the popup menu as soon as possible.
4261 if (type != -1)
4262 ins_compl_check_keys(0, FALSE);
4263
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004264 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004265 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4266 break;
4267 compl_started = TRUE;
4268 }
4269 else
4270 {
4271 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004272 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004273 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004274
4275 compl_started = FALSE;
4276 }
4277 }
4278 compl_started = TRUE;
4279
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004280 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004281 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004282 found_new_match = FAIL;
4283
4284 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004285 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004286 && !ctrl_x_mode_line_or_eval()))
4287 i = ins_compl_make_cyclic();
4288
4289 if (compl_old_match != NULL)
4290 {
4291 // If several matches were added (FORWARD) or the search failed and has
4292 // just been made cyclic then we have to move compl_curr_match to the
4293 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004294 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004295 : compl_old_match->cp_prev;
4296 if (compl_curr_match == NULL)
4297 compl_curr_match = compl_old_match;
4298 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004299 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004300
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004301 return i;
4302}
4303
4304/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004305 * Update "compl_shown_match" to the actually shown match, it may differ when
4306 * "compl_leader" is used to omit some of the matches.
4307 */
4308 static void
4309ins_compl_update_shown_match(void)
4310{
4311 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004312 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004313 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004314 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004315 compl_shown_match = compl_shown_match->cp_next;
4316
4317 // If we didn't find it searching forward, and compl_shows_dir is
4318 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004319 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004320 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004321 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004322 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004323 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004324 {
4325 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004326 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004327 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004328 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004329 compl_shown_match = compl_shown_match->cp_prev;
4330 }
4331}
4332
4333/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004334 * Delete the old text being completed.
4335 */
4336 void
4337ins_compl_delete(void)
4338{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004339 // In insert mode: Delete the typed part.
4340 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004341 int col = compl_col + (compl_status_adding() ? compl_length : 0);
4342 int has_preinsert = ins_compl_preinsert_effect();
4343 if (has_preinsert)
4344 {
4345 col = compl_col + ins_compl_leader_len() - compl_length;
4346 curwin->w_cursor.col = compl_ins_end_col;
4347 }
4348
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004349 if ((int)curwin->w_cursor.col > col)
4350 {
4351 if (stop_arrow() == FAIL)
4352 return;
4353 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004354 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004355 }
4356
4357 // TODO: is this sufficient for redrawing? Redrawing everything causes
4358 // flicker, thus we can't do that.
4359 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004360#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004361 // clear v:completed_item
4362 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004363#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004364}
4365
4366/*
4367 * Insert the new text being completed.
4368 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004369 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4370 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004371 */
4372 void
glepniredd4ac32025-01-29 18:53:51 +01004373ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004374{
glepniredd4ac32025-01-29 18:53:51 +01004375 int compl_len = get_compl_len();
4376 int preinsert = ins_compl_has_preinsert();
4377 char_u *str = compl_shown_match->cp_str.string;
4378 int leader_len = ins_compl_leader_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004379
4380 // Make sure we don't go over the end of the string, this can happen with
4381 // illegal bytes.
John Marriott5e6ea922024-11-23 14:01:57 +01004382 if (compl_len < (int)compl_shown_match->cp_str.length)
glepniredd4ac32025-01-29 18:53:51 +01004383 {
4384 ins_compl_insert_bytes(str + compl_len, -1);
4385 if (preinsert && move_cursor)
4386 curwin->w_cursor.col -= ((size_t)STRLEN(str) - leader_len);
4387 }
4388 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004389 compl_used_match = FALSE;
4390 else
4391 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004392#ifdef FEAT_EVAL
4393 {
4394 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4395
4396 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4397 }
4398#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004399 if (!in_compl_func)
4400 compl_curr_match = compl_shown_match;
4401}
4402
4403/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004404 * show the file name for the completion match (if any). Truncate the file
4405 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004406 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004407 static void
4408ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004409{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004410 char *lead = _("match in file");
4411 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4412 char_u *s;
4413 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004414
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004415 if (space <= 0)
4416 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004417
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004418 // We need the tail that fits. With double-byte encoding going
4419 // back from the end is very slow, thus go from the start and keep
4420 // the text that fits in "space" between "s" and "e".
4421 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004422 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004423 space -= ptr2cells(e);
4424 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004425 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004426 space += ptr2cells(s);
4427 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004428 }
4429 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004430 msg_hist_off = TRUE;
4431 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4432 s > compl_shown_match->cp_fname ? "<" : "", s);
4433 msg((char *)IObuff);
4434 msg_hist_off = FALSE;
4435 redraw_cmdline = FALSE; // don't overwrite!
4436}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004437
glepnirdca57fb2024-06-04 22:01:21 +02004438/*
zeertzjq551d8c32024-06-05 19:53:32 +02004439 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004440 */
glepnira218cc62024-06-03 19:32:39 +02004441 static compl_T *
4442find_comp_when_fuzzy(void)
4443{
4444 int score;
4445 char_u* str;
4446 int target_idx = -1;
4447 int is_forward = compl_shows_dir_forward();
4448 int is_backward = compl_shows_dir_backward();
4449 compl_T *comp = NULL;
4450
glepnir43eef882024-06-19 20:20:48 +02004451 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004452 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004453 return compl_first_match != compl_shown_match ? compl_first_match :
4454 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004455
4456 if (is_forward)
4457 target_idx = compl_selected_item + 1;
4458 else if (is_backward)
4459 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004460 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004461
4462 score = compl_match_array[target_idx].pum_score;
4463 str = compl_match_array[target_idx].pum_text;
4464
4465 comp = compl_first_match;
4466 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004467 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004468 return comp;
4469 comp = comp->cp_next;
4470 } while (comp != NULL && !is_first_match(comp));
4471
4472 return NULL;
4473}
4474
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004475/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004476 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004477 * times. The number of matches found is returned in 'num_matches'.
4478 *
4479 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4480 * get more completions. If it is FALSE, then do nothing when there are no more
4481 * completions in the given direction.
4482 *
4483 * If "advance" is TRUE, then completion will move to the first match.
4484 * Otherwise, the original text will be shown.
4485 *
4486 * Returns OK on success and -1 if the number of matches are unknown.
4487 */
4488 static int
4489find_next_completion_match(
4490 int allow_get_expansion,
4491 int todo, // repeat completion this many times
4492 int advance,
4493 int *num_matches)
4494{
4495 int found_end = FALSE;
4496 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004497 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004498 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4499 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004500
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004501 while (--todo >= 0)
4502 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004503 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004504 {
glepniraced8c22024-06-15 15:13:05 +02004505 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4506 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004507 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004508 && (is_first_match(compl_shown_match->cp_next)
4509 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004510 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004511 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004512 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004513 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004514 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004515 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4516 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004517 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004518 }
4519 else
4520 {
4521 if (!allow_get_expansion)
4522 {
4523 if (advance)
4524 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004525 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004526 compl_pending -= todo + 1;
4527 else
4528 compl_pending += todo + 1;
4529 }
4530 return -1;
4531 }
4532
4533 if (!compl_no_select && advance)
4534 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004535 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004536 --compl_pending;
4537 else
4538 ++compl_pending;
4539 }
4540
4541 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004542 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004543
4544 // handle any pending completions
4545 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004546 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004547 {
4548 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4549 {
4550 compl_shown_match = compl_shown_match->cp_next;
4551 --compl_pending;
4552 }
4553 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4554 {
4555 compl_shown_match = compl_shown_match->cp_prev;
4556 ++compl_pending;
4557 }
4558 else
4559 break;
4560 }
4561 found_end = FALSE;
4562 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004563 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004564 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004565 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004566 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004567 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004568 ++todo;
4569 else
4570 // Remember a matching item.
4571 found_compl = compl_shown_match;
4572
4573 // Stop at the end of the list when we found a usable match.
4574 if (found_end)
4575 {
4576 if (found_compl != NULL)
4577 {
4578 compl_shown_match = found_compl;
4579 break;
4580 }
4581 todo = 1; // use first usable match after wrapping around
4582 }
4583 }
4584
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004585 return OK;
4586}
4587
4588/*
4589 * Fill in the next completion in the current direction.
4590 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4591 * get more completions. If it is FALSE, then we just do nothing when there
4592 * are no more completions in a given direction. The latter case is used when
4593 * we are still in the middle of finding completions, to allow browsing
4594 * through the ones found so far.
4595 * Return the total number of matches, or -1 if still unknown -- webb.
4596 *
4597 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4598 * compl_shown_match here.
4599 *
4600 * Note that this function may be called recursively once only. First with
4601 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4602 * calls this function with "allow_get_expansion" FALSE.
4603 */
4604 static int
4605ins_compl_next(
4606 int allow_get_expansion,
4607 int count, // repeat completion this many times; should
4608 // be at least 1
4609 int insert_match, // Insert the newly selected match
4610 int in_compl_func) // called from complete_check()
4611{
4612 int num_matches = -1;
4613 int todo = count;
4614 int advance;
4615 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004616 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004617 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004618 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4619 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01004620 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004621
4622 // When user complete function return -1 for findstart which is next
4623 // time of 'always', compl_shown_match become NULL.
4624 if (compl_shown_match == NULL)
4625 return -1;
4626
John Marriott5e6ea922024-11-23 14:01:57 +01004627 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004628 && !match_at_original_text(compl_shown_match)
4629 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004630 // Update "compl_shown_match" to the actually shown match
4631 ins_compl_update_shown_match();
4632
4633 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004634 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004635 // Delete old text to be replaced
4636 ins_compl_delete();
4637
4638 // When finding the longest common text we stick at the original text,
4639 // don't let CTRL-N or CTRL-P move to the first match.
4640 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4641
4642 // When restarting the search don't insert the first match either.
4643 if (compl_restarting)
4644 {
4645 advance = FALSE;
4646 compl_restarting = FALSE;
4647 }
4648
4649 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4650 // around.
4651 if (find_next_completion_match(allow_get_expansion, todo, advance,
4652 &num_matches) == -1)
4653 return -1;
4654
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004655 if (curbuf != orig_curbuf)
4656 {
4657 // In case some completion function switched buffer, don't want to
4658 // insert the completion elsewhere.
4659 return -1;
4660 }
4661
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004662 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01004663 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004664 {
glepnir6a38aff2024-12-16 21:56:16 +01004665 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004666 compl_used_match = FALSE;
4667 }
4668 else if (insert_match)
4669 {
4670 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01004671 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004672 else
glepnir6a38aff2024-12-16 21:56:16 +01004673 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004674 }
4675 else
4676 compl_used_match = FALSE;
4677
4678 if (!allow_get_expansion)
4679 {
4680 // may undisplay the popup menu first
4681 ins_compl_upd_pum();
4682
4683 if (pum_enough_matches())
4684 // Will display the popup menu, don't redraw yet to avoid flicker.
4685 pum_call_update_screen();
4686 else
4687 // Not showing the popup menu yet, redraw to show the user what was
4688 // inserted.
4689 update_screen(0);
4690
4691 // display the updated popup menu
4692 ins_compl_show_pum();
4693#ifdef FEAT_GUI
4694 if (gui.in_use)
4695 {
4696 // Show the cursor after the match, not after the redrawn text.
4697 setcursor();
4698 out_flush_cursor(FALSE, FALSE);
4699 }
4700#endif
4701
4702 // Delete old text to be replaced, since we're still searching and
4703 // don't want to match ourselves!
4704 ins_compl_delete();
4705 }
4706
4707 // Enter will select a match when the match wasn't inserted and the popup
4708 // menu is visible.
4709 if (compl_no_insert && !started)
4710 compl_enter_selects = TRUE;
4711 else
4712 compl_enter_selects = !insert_match && compl_match_array != NULL;
4713
4714 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004715 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004716 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004717
4718 return num_matches;
4719}
4720
4721/*
4722 * Call this while finding completions, to check whether the user has hit a key
4723 * that should change the currently displayed completion, or exit completion
4724 * mode. Also, when compl_pending is not zero, show a completion as soon as
4725 * possible. -- webb
4726 * "frequency" specifies out of how many calls we actually check.
4727 * "in_compl_func" is TRUE when called from complete_check(), don't set
4728 * compl_curr_match.
4729 */
4730 void
4731ins_compl_check_keys(int frequency, int in_compl_func)
4732{
4733 static int count = 0;
4734 int c;
4735
4736 // Don't check when reading keys from a script, :normal or feedkeys().
4737 // That would break the test scripts. But do check for keys when called
4738 // from complete_check().
4739 if (!in_compl_func && (using_script() || ex_normal_busy))
4740 return;
4741
4742 // Only do this at regular intervals
4743 if (++count < frequency)
4744 return;
4745 count = 0;
4746
4747 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4748 // can't do its work correctly.
4749 c = vpeekc_any();
4750 if (c != NUL)
4751 {
4752 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4753 {
4754 c = safe_vgetc(); // Eat the character
4755 compl_shows_dir = ins_compl_key2dir(c);
4756 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4757 c != K_UP && c != K_DOWN, in_compl_func);
4758 }
4759 else
4760 {
4761 // Need to get the character to have KeyTyped set. We'll put it
4762 // back with vungetc() below. But skip K_IGNORE.
4763 c = safe_vgetc();
4764 if (c != K_IGNORE)
4765 {
4766 // Don't interrupt completion when the character wasn't typed,
4767 // e.g., when doing @q to replay keys.
4768 if (c != Ctrl_R && KeyTyped)
4769 compl_interrupted = TRUE;
4770
4771 vungetc(c);
4772 }
4773 }
4774 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004775 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004776 {
4777 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4778
4779 compl_pending = 0;
4780 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4781 }
4782}
4783
4784/*
4785 * Decide the direction of Insert mode complete from the key typed.
4786 * Returns BACKWARD or FORWARD.
4787 */
4788 static int
4789ins_compl_key2dir(int c)
4790{
4791 if (c == Ctrl_P || c == Ctrl_L
4792 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4793 return BACKWARD;
4794 return FORWARD;
4795}
4796
4797/*
4798 * Return TRUE for keys that are used for completion only when the popup menu
4799 * is visible.
4800 */
4801 static int
4802ins_compl_pum_key(int c)
4803{
4804 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4805 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4806 || c == K_UP || c == K_DOWN);
4807}
4808
4809/*
4810 * Decide the number of completions to move forward.
4811 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4812 */
4813 static int
4814ins_compl_key2count(int c)
4815{
4816 int h;
4817
4818 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4819 {
4820 h = pum_get_height();
4821 if (h > 3)
4822 h -= 2; // keep some context
4823 return h;
4824 }
4825 return 1;
4826}
4827
4828/*
4829 * Return TRUE if completion with "c" should insert the match, FALSE if only
4830 * to change the currently selected completion.
4831 */
4832 static int
4833ins_compl_use_match(int c)
4834{
4835 switch (c)
4836 {
4837 case K_UP:
4838 case K_DOWN:
4839 case K_PAGEDOWN:
4840 case K_KPAGEDOWN:
4841 case K_S_DOWN:
4842 case K_PAGEUP:
4843 case K_KPAGEUP:
4844 case K_S_UP:
4845 return FALSE;
4846 }
4847 return TRUE;
4848}
4849
4850/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004851 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4852 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004853 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004854 * Uses the global variables: compl_cont_status and ctrl_x_mode
4855 */
4856 static int
4857get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4858{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004859 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004860 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004861 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004862 {
4863 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4864 ;
4865 compl_col += ++startcol;
4866 compl_length = curs_col - startcol;
4867 }
4868 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004869 {
John Marriott5e6ea922024-11-23 14:01:57 +01004870 compl_pattern.string = str_foldcase(line + compl_col,
4871 compl_length, NULL, 0);
4872 if (compl_pattern.string == NULL)
4873 {
4874 compl_pattern.length = 0;
4875 return FAIL;
4876 }
4877 compl_pattern.length = STRLEN(compl_pattern.string);
4878 }
4879 else
4880 {
4881 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4882 if (compl_pattern.string == NULL)
4883 {
4884 compl_pattern.length = 0;
4885 return FAIL;
4886 }
4887 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02004888 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004889 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004890 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004891 {
4892 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004893 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01004894 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004895
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004896 if (!vim_iswordp(line + compl_col)
4897 || (compl_col > 0
4898 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004899 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004900 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004901 prefixlen = 0;
4902 }
John Marriott5e6ea922024-11-23 14:01:57 +01004903
4904 // we need up to 2 extra chars for the prefix
4905 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
4906 compl_pattern.string = alloc(n);
4907 if (compl_pattern.string == NULL)
4908 {
4909 compl_pattern.length = 0;
4910 return FAIL;
4911 }
4912 STRCPY((char *)compl_pattern.string, prefix);
4913 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004914 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004915 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004916 }
4917 else if (--startcol < 0
4918 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4919 {
John Marriott5e6ea922024-11-23 14:01:57 +01004920 size_t len = STRLEN_LITERAL("\\<\\k\\k");
4921
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004922 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01004923 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
4924 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004925 {
John Marriott5e6ea922024-11-23 14:01:57 +01004926 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004927 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004928 }
John Marriott5e6ea922024-11-23 14:01:57 +01004929 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004930 compl_col += curs_col;
4931 compl_length = 0;
4932 }
4933 else
4934 {
4935 // Search the point of change class of multibyte character
4936 // or not a word single byte character backward.
4937 if (has_mbyte)
4938 {
4939 int base_class;
4940 int head_off;
4941
4942 startcol -= (*mb_head_off)(line, line + startcol);
4943 base_class = mb_get_class(line + startcol);
4944 while (--startcol >= 0)
4945 {
4946 head_off = (*mb_head_off)(line, line + startcol);
4947 if (base_class != mb_get_class(line + startcol
4948 - head_off))
4949 break;
4950 startcol -= head_off;
4951 }
4952 }
4953 else
4954 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4955 ;
4956 compl_col += ++startcol;
4957 compl_length = (int)curs_col - startcol;
4958 if (compl_length == 1)
4959 {
4960 // Only match word with at least two chars -- webb
4961 // there's no need to call quote_meta,
4962 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01004963 compl_pattern.string = alloc(7);
4964 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004965 {
John Marriott5e6ea922024-11-23 14:01:57 +01004966 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004967 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004968 }
John Marriott5e6ea922024-11-23 14:01:57 +01004969 STRCPY((char *)compl_pattern.string, "\\<");
4970 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
4971 STRCAT((char *)compl_pattern.string, "\\k");
4972 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004973 }
4974 else
4975 {
John Marriott5e6ea922024-11-23 14:01:57 +01004976 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
4977
4978 compl_pattern.string = alloc(n);
4979 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004980 {
John Marriott5e6ea922024-11-23 14:01:57 +01004981 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004982 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004983 }
John Marriott5e6ea922024-11-23 14:01:57 +01004984 STRCPY((char *)compl_pattern.string, "\\<");
4985 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004986 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004987 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004988 }
4989 }
4990
4991 return OK;
4992}
4993
4994/*
4995 * Get the pattern, column and length for whole line completion or for the
4996 * complete() function.
4997 * Sets the global variables: compl_col, compl_length and compl_pattern.
4998 */
4999 static int
5000get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5001{
5002 compl_col = (colnr_T)getwhitecols(line);
5003 compl_length = (int)curs_col - (int)compl_col;
5004 if (compl_length < 0) // cursor in indent: empty pattern
5005 compl_length = 0;
5006 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005007 {
John Marriott5e6ea922024-11-23 14:01:57 +01005008 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5009 NULL, 0);
5010 if (compl_pattern.string == NULL)
5011 {
5012 compl_pattern.length = 0;
5013 return FAIL;
5014 }
5015 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005016 }
John Marriott5e6ea922024-11-23 14:01:57 +01005017 else
5018 {
5019 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5020 if (compl_pattern.string == NULL)
5021 {
5022 compl_pattern.length = 0;
5023 return FAIL;
5024 }
5025 compl_pattern.length = (size_t)compl_length;
5026 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005027
5028 return OK;
5029}
5030
5031/*
5032 * Get the pattern, column and length for filename completion.
5033 * Sets the global variables: compl_col, compl_length and compl_pattern.
5034 */
5035 static int
5036get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5037{
5038 // Go back to just before the first filename character.
5039 if (startcol > 0)
5040 {
5041 char_u *p = line + startcol;
5042
5043 MB_PTR_BACK(line, p);
5044 while (p > line && vim_isfilec(PTR2CHAR(p)))
5045 MB_PTR_BACK(line, p);
5046 if (p == line && vim_isfilec(PTR2CHAR(p)))
5047 startcol = 0;
5048 else
5049 startcol = (int)(p - line) + 1;
5050 }
5051
5052 compl_col += startcol;
5053 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005054 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5055 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005056 {
John Marriott5e6ea922024-11-23 14:01:57 +01005057 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005058 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005059 }
5060
John Marriott5e6ea922024-11-23 14:01:57 +01005061 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005062
5063 return OK;
5064}
5065
5066/*
5067 * Get the pattern, column and length for command-line completion.
5068 * Sets the global variables: compl_col, compl_length and compl_pattern.
5069 */
5070 static int
5071get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5072{
John Marriott5e6ea922024-11-23 14:01:57 +01005073 compl_pattern.string = vim_strnsave(line, curs_col);
5074 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005075 {
John Marriott5e6ea922024-11-23 14:01:57 +01005076 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005077 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005078 }
John Marriott5e6ea922024-11-23 14:01:57 +01005079 compl_pattern.length = curs_col;
5080 set_cmd_context(&compl_xp, compl_pattern.string,
5081 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005082 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5083 || compl_xp.xp_context == EXPAND_NOTHING)
5084 // No completion possible, use an empty pattern to get a
5085 // "pattern not found" message.
5086 compl_col = curs_col;
5087 else
John Marriott5e6ea922024-11-23 14:01:57 +01005088 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005089 compl_length = curs_col - compl_col;
5090
5091 return OK;
5092}
5093
5094/*
5095 * Get the pattern, column and length for user defined completion ('omnifunc',
5096 * 'completefunc' and 'thesaurusfunc')
5097 * Sets the global variables: compl_col, compl_length and compl_pattern.
5098 * Uses the global variable: spell_bad_len
5099 */
5100 static int
5101get_userdefined_compl_info(colnr_T curs_col UNUSED)
5102{
5103 int ret = FAIL;
5104
5105#ifdef FEAT_COMPL_FUNC
5106 // Call user defined function 'completefunc' with "a:findstart"
5107 // set to 1 to obtain the length of text to use for completion.
5108 char_u *line;
5109 typval_T args[3];
5110 int col;
5111 char_u *funcname;
5112 pos_T pos;
5113 int save_State = State;
5114 callback_T *cb;
5115
5116 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5117 // length as a string
5118 funcname = get_complete_funcname(ctrl_x_mode);
5119 if (*funcname == NUL)
5120 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005121 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005122 ? "completefunc" : "omnifunc");
5123 return FAIL;
5124 }
5125
5126 args[0].v_type = VAR_NUMBER;
5127 args[0].vval.v_number = 1;
5128 args[1].v_type = VAR_STRING;
5129 args[1].vval.v_string = (char_u *)"";
5130 args[2].v_type = VAR_UNKNOWN;
5131 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005132 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005133 cb = get_insert_callback(ctrl_x_mode);
5134 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005135 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005136
5137 State = save_State;
5138 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005139 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005140 validate_cursor();
5141 if (!EQUAL_POS(curwin->w_cursor, pos))
5142 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005143 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005144 return FAIL;
5145 }
5146
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005147 // Return value -2 means the user complete function wants to cancel the
5148 // complete without an error, do the same if the function did not execute
5149 // successfully.
5150 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005151 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005152 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005153 if (col == -3)
5154 {
5155 ctrl_x_mode = CTRL_X_NORMAL;
5156 edit_submode = NULL;
5157 if (!shortmess(SHM_COMPLETIONMENU))
5158 msg_clr_cmdline();
5159 return FAIL;
5160 }
5161
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005162 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005163 // completion.
5164 compl_opt_refresh_always = FALSE;
5165 compl_opt_suppress_empty = FALSE;
5166
5167 if (col < 0)
5168 col = curs_col;
5169 compl_col = col;
5170 if (compl_col > curs_col)
5171 compl_col = curs_col;
5172
5173 // Setup variables for completion. Need to obtain "line" again,
5174 // it may have become invalid.
5175 line = ml_get(curwin->w_cursor.lnum);
5176 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005177 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5178 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005179 {
John Marriott5e6ea922024-11-23 14:01:57 +01005180 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005181 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005182 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005183
John Marriott5e6ea922024-11-23 14:01:57 +01005184 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005185 ret = OK;
5186#endif
5187
5188 return ret;
5189}
5190
5191/*
5192 * Get the pattern, column and length for spell completion.
5193 * Sets the global variables: compl_col, compl_length and compl_pattern.
5194 * Uses the global variable: spell_bad_len
5195 */
5196 static int
5197get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5198{
5199 int ret = FAIL;
5200#ifdef FEAT_SPELL
5201 char_u *line;
5202
5203 if (spell_bad_len > 0)
5204 compl_col = curs_col - spell_bad_len;
5205 else
5206 compl_col = spell_word_start(startcol);
5207 if (compl_col >= (colnr_T)startcol)
5208 {
5209 compl_length = 0;
5210 compl_col = curs_col;
5211 }
5212 else
5213 {
5214 spell_expand_check_cap(compl_col);
5215 compl_length = (int)curs_col - compl_col;
5216 }
5217 // Need to obtain "line" again, it may have become invalid.
5218 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005219 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5220 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005221 {
John Marriott5e6ea922024-11-23 14:01:57 +01005222 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005223 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005224 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005225
John Marriott5e6ea922024-11-23 14:01:57 +01005226 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005227 ret = OK;
5228#endif
5229
5230 return ret;
5231}
5232
5233/*
5234 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005235 * "startcol" - start column number of the completion pattern/text
5236 * "cur_col" - current cursor column
5237 * On return, "line_invalid" is set to TRUE, if the current line may have
5238 * become invalid and needs to be fetched again.
5239 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005240 */
5241 static int
5242compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5243{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005244 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005245 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5246 && !thesaurus_func_complete(ctrl_x_mode)))
5247 {
5248 return get_normal_compl_info(line, startcol, curs_col);
5249 }
5250 else if (ctrl_x_mode_line_or_eval())
5251 {
5252 return get_wholeline_compl_info(line, curs_col);
5253 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005254 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005255 {
5256 return get_filename_compl_info(line, startcol, curs_col);
5257 }
5258 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5259 {
5260 return get_cmdline_compl_info(line, curs_col);
5261 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005262 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005263 || thesaurus_func_complete(ctrl_x_mode))
5264 {
5265 if (get_userdefined_compl_info(curs_col) == FAIL)
5266 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005267 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005268 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005269 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005270 {
5271 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5272 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005273 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005274 }
5275 else
5276 {
5277 internal_error("ins_complete()");
5278 return FAIL;
5279 }
5280
5281 return OK;
5282}
5283
5284/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005285 * Continue an interrupted completion mode search in "line".
5286 *
5287 * If this same ctrl_x_mode has been interrupted use the text from
5288 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5289 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5290 * the same line as the cursor then fix it (the line has been split because it
5291 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5292 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005293 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005294 static void
5295ins_compl_continue_search(char_u *line)
5296{
5297 // it is a continued search
5298 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005299 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5300 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005301 {
5302 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5303 {
5304 // line (probably) wrapped, set compl_startpos to the
5305 // first non_blank in the line, if it is not a wordchar
5306 // include it to get a better pattern, but then we don't
5307 // want the "\\<" prefix, check it below
5308 compl_col = (colnr_T)getwhitecols(line);
5309 compl_startpos.col = compl_col;
5310 compl_startpos.lnum = curwin->w_cursor.lnum;
5311 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5312 }
5313 else
5314 {
5315 // S_IPOS was set when we inserted a word that was at the
5316 // beginning of the line, which means that we'll go to SOL
5317 // mode but first we need to redefine compl_startpos
5318 if (compl_cont_status & CONT_S_IPOS)
5319 {
5320 compl_cont_status |= CONT_SOL;
5321 compl_startpos.col = (colnr_T)(skipwhite(
5322 line + compl_length
5323 + compl_startpos.col) - line);
5324 }
5325 compl_col = compl_startpos.col;
5326 }
5327 compl_length = curwin->w_cursor.col - (int)compl_col;
5328 // IObuff is used to add a "word from the next line" would we
5329 // have enough space? just being paranoid
5330#define MIN_SPACE 75
5331 if (compl_length > (IOSIZE - MIN_SPACE))
5332 {
5333 compl_cont_status &= ~CONT_SOL;
5334 compl_length = (IOSIZE - MIN_SPACE);
5335 compl_col = curwin->w_cursor.col - compl_length;
5336 }
5337 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5338 if (compl_length < 1)
5339 compl_cont_status &= CONT_LOCAL;
5340 }
5341 else if (ctrl_x_mode_line_or_eval())
5342 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5343 else
5344 compl_cont_status = 0;
5345}
5346
5347/*
5348 * start insert mode completion
5349 */
5350 static int
5351ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005352{
5353 char_u *line;
5354 int startcol = 0; // column where searched text starts
5355 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005356 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005357 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005358 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005359
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005360 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005361
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005362 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005363 did_si = FALSE;
5364 can_si = FALSE;
5365 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005366 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005367 return FAIL;
5368
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005369 line = ml_get(curwin->w_cursor.lnum);
5370 curs_col = curwin->w_cursor.col;
5371 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005372
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005373 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5374 && compl_cont_mode == ctrl_x_mode)
5375 // this same ctrl-x_mode was interrupted previously. Continue the
5376 // completion.
5377 ins_compl_continue_search(line);
5378 else
5379 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005380
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005381 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005382 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005383 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005384 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005385 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5386 compl_cont_status = 0;
5387 compl_cont_status |= CONT_N_ADDS;
5388 compl_startpos = curwin->w_cursor;
5389 startcol = (int)curs_col;
5390 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005391 }
5392
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005393 // Work out completion pattern and original text -- webb
5394 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5395 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005396 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5397 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005398 // restore did_ai, so that adding comment leader works
5399 did_ai = save_did_ai;
5400 return FAIL;
5401 }
5402 // If "line" was changed while getting completion info get it again.
5403 if (line_invalid)
5404 line = ml_get(curwin->w_cursor.lnum);
5405
glepnir7cfe6932024-09-15 20:06:28 +02005406 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005407 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005408 {
5409 edit_submode_pre = (char_u *)_(" Adding");
5410 if (ctrl_x_mode_line_or_eval())
5411 {
5412 // Insert a new line, keep indentation but ignore 'comments'.
5413 char_u *old = curbuf->b_p_com;
5414
5415 curbuf->b_p_com = (char_u *)"";
5416 compl_startpos.lnum = curwin->w_cursor.lnum;
5417 compl_startpos.col = compl_col;
5418 ins_eol('\r');
5419 curbuf->b_p_com = old;
5420 compl_length = 0;
5421 compl_col = curwin->w_cursor.col;
5422 }
glepnir7cfe6932024-09-15 20:06:28 +02005423 else if (ctrl_x_mode_normal() && in_fuzzy)
5424 {
5425 compl_startpos = curwin->w_cursor;
5426 compl_cont_status &= CONT_S_IPOS;
5427 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005428 }
5429 else
5430 {
5431 edit_submode_pre = NULL;
5432 compl_startpos.col = compl_col;
5433 }
5434
5435 if (compl_cont_status & CONT_LOCAL)
5436 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5437 else
5438 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5439
5440 // If any of the original typed text has been changed we need to fix
5441 // the redo buffer.
5442 ins_compl_fixRedoBufForLeader(NULL);
5443
5444 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005445 VIM_CLEAR_STRING(compl_orig_text);
5446 compl_orig_text.length = (size_t)compl_length;
5447 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005448 if (p_ic)
5449 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005450 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5451 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005452 {
John Marriott5e6ea922024-11-23 14:01:57 +01005453 VIM_CLEAR_STRING(compl_pattern);
5454 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005455 return FAIL;
5456 }
5457
5458 // showmode might reset the internal line pointers, so it must
5459 // be called before line = ml_get(), or when this address is no
5460 // longer needed. -- Acevedo.
5461 edit_submode_extra = (char_u *)_("-- Searching...");
5462 edit_submode_highl = HLF_COUNT;
5463 showmode();
5464 edit_submode_extra = NULL;
5465 out_flush();
5466
5467 return OK;
5468}
5469
5470/*
5471 * display the completion status message
5472 */
5473 static void
5474ins_compl_show_statusmsg(void)
5475{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005476 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005477 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005478 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005479 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005480 ? (char_u *)_("Hit end of paragraph")
5481 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005482 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005483 }
5484
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005485 if (edit_submode_extra == NULL)
5486 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005487 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005488 {
5489 edit_submode_extra = (char_u *)_("Back at original");
5490 edit_submode_highl = HLF_W;
5491 }
5492 else if (compl_cont_status & CONT_S_IPOS)
5493 {
5494 edit_submode_extra = (char_u *)_("Word from other line");
5495 edit_submode_highl = HLF_COUNT;
5496 }
5497 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5498 {
5499 edit_submode_extra = (char_u *)_("The only match");
5500 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005501 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005502 }
5503 else
5504 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005505#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005506 // Update completion sequence number when needed.
5507 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005508 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005509#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005510 // The match should always have a sequence number now, this is
5511 // just a safety check.
5512 if (compl_curr_match->cp_number != -1)
5513 {
5514 // Space for 10 text chars. + 2x10-digit no.s = 31.
5515 // Translations may need more than twice that.
5516 static char_u match_ref[81];
5517
5518 if (compl_matches > 0)
5519 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005520 _("match %d of %d"),
5521 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005522 else
5523 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005524 _("match %d"),
5525 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005526 edit_submode_extra = match_ref;
5527 edit_submode_highl = HLF_R;
5528 if (dollar_vcol >= 0)
5529 curs_columns(FALSE);
5530 }
5531 }
5532 }
5533
5534 // Show a message about what (completion) mode we're in.
5535 if (!compl_opt_suppress_empty)
5536 {
5537 showmode();
5538 if (!shortmess(SHM_COMPLETIONMENU))
5539 {
5540 if (edit_submode_extra != NULL)
5541 {
5542 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005543 {
5544 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005545 msg_attr((char *)edit_submode_extra,
5546 edit_submode_highl < HLF_COUNT
5547 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005548 msg_hist_off = FALSE;
5549 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005550 }
5551 else
5552 msg_clr_cmdline(); // necessary for "noshowmode"
5553 }
5554 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005555}
5556
5557/*
5558 * Do Insert mode completion.
5559 * Called when character "c" was typed, which has a meaning for completion.
5560 * Returns OK if completion was done, FAIL if something failed (out of mem).
5561 */
5562 int
5563ins_complete(int c, int enable_pum)
5564{
5565 int n;
5566 int save_w_wrow;
5567 int save_w_leftcol;
5568 int insert_match;
5569
5570 compl_direction = ins_compl_key2dir(c);
5571 insert_match = ins_compl_use_match(c);
5572
5573 if (!compl_started)
5574 {
5575 if (ins_compl_start() == FAIL)
5576 return FAIL;
5577 }
5578 else if (insert_match && stop_arrow() == FAIL)
5579 return FAIL;
5580
5581 compl_shown_match = compl_curr_match;
5582 compl_shows_dir = compl_direction;
5583
5584 // Find next match (and following matches).
5585 save_w_wrow = curwin->w_wrow;
5586 save_w_leftcol = curwin->w_leftcol;
5587 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5588
5589 // may undisplay the popup menu
5590 ins_compl_upd_pum();
5591
5592 if (n > 1) // all matches have been found
5593 compl_matches = n;
5594 compl_curr_match = compl_shown_match;
5595 compl_direction = compl_shows_dir;
5596
5597 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5598 // mode.
5599 if (got_int && !global_busy)
5600 {
5601 (void)vgetc();
5602 got_int = FALSE;
5603 }
5604
5605 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005606 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005607 {
5608 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5609 // because we couldn't expand anything at first place, but if we used
5610 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5611 // (such as M in M'exico) if not tried already. -- Acevedo
5612 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005613 || compl_status_adding()
5614 || (ctrl_x_mode_not_default()
5615 && !ctrl_x_mode_path_patterns()
5616 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005617 compl_cont_status &= ~CONT_N_ADDS;
5618 }
5619
5620 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5621 compl_cont_status |= CONT_S_IPOS;
5622 else
5623 compl_cont_status &= ~CONT_S_IPOS;
5624
5625 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005626
5627 // Show the popup menu, unless we got interrupted.
5628 if (enable_pum && !compl_interrupted)
5629 show_pum(save_w_wrow, save_w_leftcol);
5630
5631 compl_was_interrupted = compl_interrupted;
5632 compl_interrupted = FALSE;
5633
5634 return OK;
5635}
5636
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005637/*
5638 * Remove (if needed) and show the popup menu
5639 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005640 static void
5641show_pum(int prev_w_wrow, int prev_w_leftcol)
5642{
5643 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005644 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005645 RedrawingDisabled = 0;
5646
5647 // If the cursor moved or the display scrolled we need to remove the pum
5648 // first.
5649 setcursor();
5650 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5651 ins_compl_del_pum();
5652
5653 ins_compl_show_pum();
5654 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005655
5656 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005657}
5658
5659/*
5660 * Looks in the first "len" chars. of "src" for search-metachars.
5661 * If dest is not NULL the chars. are copied there quoting (with
5662 * a backslash) the metachars, and dest would be NUL terminated.
5663 * Returns the length (needed) of dest
5664 */
5665 static unsigned
5666quote_meta(char_u *dest, char_u *src, int len)
5667{
5668 unsigned m = (unsigned)len + 1; // one extra for the NUL
5669
5670 for ( ; --len >= 0; src++)
5671 {
5672 switch (*src)
5673 {
5674 case '.':
5675 case '*':
5676 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005677 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005678 break;
5679 // FALLTHROUGH
5680 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005681 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005682 break;
5683 // FALLTHROUGH
5684 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005685 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005686 break;
5687 // FALLTHROUGH
5688 case '^': // currently it's not needed.
5689 case '$':
5690 m++;
5691 if (dest != NULL)
5692 *dest++ = '\\';
5693 break;
5694 }
5695 if (dest != NULL)
5696 *dest++ = *src;
5697 // Copy remaining bytes of a multibyte character.
5698 if (has_mbyte)
5699 {
5700 int i, mb_len;
5701
5702 mb_len = (*mb_ptr2len)(src) - 1;
5703 if (mb_len > 0 && len >= mb_len)
5704 for (i = 0; i < mb_len; ++i)
5705 {
5706 --len;
5707 ++src;
5708 if (dest != NULL)
5709 *dest++ = *src;
5710 }
5711 }
5712 }
5713 if (dest != NULL)
5714 *dest = NUL;
5715
5716 return m;
5717}
5718
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005719#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005720 void
5721free_insexpand_stuff(void)
5722{
John Marriott5e6ea922024-11-23 14:01:57 +01005723 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005724# ifdef FEAT_EVAL
5725 free_callback(&cfu_cb);
5726 free_callback(&ofu_cb);
5727 free_callback(&tsrfu_cb);
5728# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005729}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005730#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005731
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005732#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005733/*
5734 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5735 * spelled word, if there is one.
5736 */
5737 static void
5738spell_back_to_badword(void)
5739{
5740 pos_T tpos = curwin->w_cursor;
5741
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005742 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005743 if (curwin->w_cursor.col != tpos.col)
5744 start_arrow(&tpos);
5745}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005746#endif