blob: 85b32691df1fb2801d1d4269f11fa5b559cddd67 [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;
glepnir76bdb822025-02-08 19:04:51 +0100175static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100176static colnr_T compl_col = 0; // column where the text starts
177 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100178static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100179static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100180 // completion started
181static int compl_cont_mode = 0;
182static expand_T compl_xp;
183
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000184// List of flags for method of completion.
185static int compl_cont_status = 0;
186# define CONT_ADDING 1 // "normal" or "adding" expansion
187# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
188 // it's set only iff N_ADDS is set
189# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
190# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
191 // if so, word-wise-expansion will set SOL
192# define CONT_SOL 16 // pattern includes start of line, just for
193 // word-wise expansion, not set for ^X^L
194# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
195 // expansion, (eg use complete=.)
196
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100197static int compl_opt_refresh_always = FALSE;
198static int compl_opt_suppress_empty = FALSE;
199
glepnira218cc62024-06-03 19:32:39 +0200200static int compl_selected_item = -1;
201
glepnir8159fb12024-07-17 20:32:54 +0200202static int *compl_fuzzy_scores;
203
glepnir6a38aff2024-12-16 21:56:16 +0100204// "compl_match_array" points the currently displayed list of entries in the
205// popup menu. It is NULL when there is no popup menu.
206static pumitem_T *compl_match_array = NULL;
207static int compl_match_arraysize;
208
glepnir80b66202024-11-27 21:53:53 +0100209static 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 +0100210static void ins_compl_longest_match(compl_T *match);
211static void ins_compl_del_pum(void);
212static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
213static char_u *find_line_end(char_u *ptr);
214static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100215static int ins_compl_need_restart(void);
216static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000217static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100218static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100219static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100220static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
221# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
222static void ins_compl_add_list(list_T *list);
223static void ins_compl_add_dict(dict_T *dict);
224# endif
225static int ins_compl_key2dir(int c);
226static int ins_compl_pum_key(int c);
227static int ins_compl_key2count(int c);
228static void show_pum(int prev_w_wrow, int prev_w_leftcol);
229static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100230static int ins_compl_has_multiple(void);
231static void ins_compl_expand_multiple(char_u *str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100232
233#ifdef FEAT_SPELL
234static void spell_back_to_badword(void);
235static int spell_bad_len = 0; // length of located bad word
236#endif
237
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100238/*
239 * CTRL-X pressed in Insert mode.
240 */
241 void
242ins_ctrl_x(void)
243{
zeertzjqdca29d92021-08-31 19:12:51 +0200244 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100245 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000246 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100247 if (compl_cont_status & CONT_N_ADDS)
248 compl_cont_status |= CONT_INTRPT;
249 else
250 compl_cont_status = 0;
251 // We're not sure which CTRL-X mode it will be yet
252 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
253 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
254 edit_submode_pre = NULL;
255 showmode();
256 }
zeertzjqdca29d92021-08-31 19:12:51 +0200257 else
258 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
259 // CTRL-V look like CTRL-N
260 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100261
LemonBoy2bf52dd2022-04-09 18:17:34 +0100262 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100263}
264
265/*
266 * Functions to check the current CTRL-X mode.
267 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000268int ctrl_x_mode_none(void)
269 { return ctrl_x_mode == 0; }
270int ctrl_x_mode_normal(void)
271 { return ctrl_x_mode == CTRL_X_NORMAL; }
272int ctrl_x_mode_scroll(void)
273 { return ctrl_x_mode == CTRL_X_SCROLL; }
274int ctrl_x_mode_whole_line(void)
275 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
276int ctrl_x_mode_files(void)
277 { return ctrl_x_mode == CTRL_X_FILES; }
278int ctrl_x_mode_tags(void)
279 { return ctrl_x_mode == CTRL_X_TAGS; }
280int ctrl_x_mode_path_patterns(void)
281 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
282int ctrl_x_mode_path_defines(void)
283 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
284int ctrl_x_mode_dictionary(void)
285 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
286int ctrl_x_mode_thesaurus(void)
287 { return ctrl_x_mode == CTRL_X_THESAURUS; }
288int ctrl_x_mode_cmdline(void)
289 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200290 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000291int ctrl_x_mode_function(void)
292 { return ctrl_x_mode == CTRL_X_FUNCTION; }
293int ctrl_x_mode_omni(void)
294 { return ctrl_x_mode == CTRL_X_OMNI; }
295int ctrl_x_mode_spell(void)
296 { return ctrl_x_mode == CTRL_X_SPELL; }
297static int ctrl_x_mode_eval(void)
298 { return ctrl_x_mode == CTRL_X_EVAL; }
299int ctrl_x_mode_line_or_eval(void)
300 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301
302/*
303 * Whether other than default completion has been selected.
304 */
305 int
306ctrl_x_mode_not_default(void)
307{
308 return ctrl_x_mode != CTRL_X_NORMAL;
309}
310
311/*
zeertzjqdca29d92021-08-31 19:12:51 +0200312 * Whether CTRL-X was typed without a following character,
313 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100314 */
315 int
316ctrl_x_mode_not_defined_yet(void)
317{
318 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
319}
320
321/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000322 * Return TRUE if currently in "normal" or "adding" insert completion matches
323 * state
324 */
325 int
326compl_status_adding(void)
327{
328 return compl_cont_status & CONT_ADDING;
329}
330
331/*
332 * Return TRUE if the completion pattern includes start of line, just for
333 * word-wise expansion.
334 */
335 int
336compl_status_sol(void)
337{
338 return compl_cont_status & CONT_SOL;
339}
340
341/*
342 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
343 */
344 int
345compl_status_local(void)
346{
347 return compl_cont_status & CONT_LOCAL;
348}
349
350/*
351 * Clear the completion status flags
352 */
353 void
354compl_status_clear(void)
355{
356 compl_cont_status = 0;
357}
358
359/*
360 * Return TRUE if completion is using the forward direction matches
361 */
362 static int
363compl_dir_forward(void)
364{
365 return compl_direction == FORWARD;
366}
367
368/*
369 * Return TRUE if currently showing forward completion matches
370 */
371 static int
372compl_shows_dir_forward(void)
373{
374 return compl_shows_dir == FORWARD;
375}
376
377/*
378 * Return TRUE if currently showing backward completion matches
379 */
380 static int
381compl_shows_dir_backward(void)
382{
383 return compl_shows_dir == BACKWARD;
384}
385
386/*
387 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100388 */
389 int
390has_compl_option(int dict_opt)
391{
392 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200393#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100394 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200395#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100396 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100397 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
398#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100399 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100400#endif
401 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100402 {
403 ctrl_x_mode = CTRL_X_NORMAL;
404 edit_submode = NULL;
405 msg_attr(dict_opt ? _("'dictionary' option is empty")
406 : _("'thesaurus' option is empty"),
407 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100408 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100409 {
410 vim_beep(BO_COMPL);
411 setcursor();
412 out_flush();
413#ifdef FEAT_EVAL
414 if (!get_vim_var_nr(VV_TESTING))
415#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100416 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100417 }
418 return FALSE;
419 }
420 return TRUE;
421}
422
423/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000424 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100425 * This depends on the current mode.
426 */
427 int
428vim_is_ctrl_x_key(int c)
429{
430 // Always allow ^R - let its results then be checked
431 if (c == Ctrl_R)
432 return TRUE;
433
434 // Accept <PageUp> and <PageDown> if the popup menu is visible.
435 if (ins_compl_pum_key(c))
436 return TRUE;
437
438 switch (ctrl_x_mode)
439 {
440 case 0: // Not in any CTRL-X mode
441 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
442 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200443 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100444 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
445 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
446 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
447 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
448 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200449 || c == Ctrl_S || c == Ctrl_K || c == 's'
450 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100451 case CTRL_X_SCROLL:
452 return (c == Ctrl_Y || c == Ctrl_E);
453 case CTRL_X_WHOLE_LINE:
454 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
455 case CTRL_X_FILES:
456 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
457 case CTRL_X_DICTIONARY:
458 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
459 case CTRL_X_THESAURUS:
460 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
461 case CTRL_X_TAGS:
462 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
463#ifdef FEAT_FIND_ID
464 case CTRL_X_PATH_PATTERNS:
465 return (c == Ctrl_P || c == Ctrl_N);
466 case CTRL_X_PATH_DEFINES:
467 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
468#endif
469 case CTRL_X_CMDLINE:
470 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
471 || c == Ctrl_X);
472#ifdef FEAT_COMPL_FUNC
473 case CTRL_X_FUNCTION:
474 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
475 case CTRL_X_OMNI:
476 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
477#endif
478 case CTRL_X_SPELL:
479 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
480 case CTRL_X_EVAL:
481 return (c == Ctrl_P || c == Ctrl_N);
482 }
483 internal_error("vim_is_ctrl_x_key()");
484 return FALSE;
485}
486
487/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000488 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000489 */
490 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000491match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000492{
493 return match->cp_flags & CP_ORIGINAL_TEXT;
494}
495
496/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000497 * Returns TRUE if "match" is the first match in the completion list.
498 */
499 static int
500is_first_match(compl_T *match)
501{
502 return match == compl_first_match;
503}
504
505/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100506 * Return TRUE when character "c" is part of the item currently being
507 * completed. Used to decide whether to abandon complete mode when the menu
508 * is visible.
509 */
510 int
511ins_compl_accept_char(int c)
512{
513 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
514 // When expanding an identifier only accept identifier chars.
515 return vim_isIDc(c);
516
517 switch (ctrl_x_mode)
518 {
519 case CTRL_X_FILES:
520 // When expanding file name only accept file name chars. But not
521 // path separators, so that "proto/<Tab>" expands files in
522 // "proto", not "proto/" as a whole
523 return vim_isfilec(c) && !vim_ispathsep(c);
524
525 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200526 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100527 case CTRL_X_OMNI:
528 // Command line and Omni completion can work with just about any
529 // printable character, but do stop at white space.
530 return vim_isprintc(c) && !VIM_ISWHITE(c);
531
532 case CTRL_X_WHOLE_LINE:
533 // For while line completion a space can be part of the line.
534 return vim_isprintc(c);
535 }
536 return vim_iswordc(c);
537}
538
539/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000540 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100541 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000542 */
543 static char_u *
544ins_compl_infercase_gettext(
545 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100546 int char_len,
547 int compl_char_len,
548 int min_len,
549 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000550{
551 int *wca; // Wide character array.
552 char_u *p;
553 int i, c;
554 int has_lower = FALSE;
555 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100556 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000557
558 IObuff[0] = NUL;
559
560 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100561 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000562 if (wca == NULL)
563 return IObuff;
564
565 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100566 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100567 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000568 if (has_mbyte)
569 wca[i] = mb_ptr2char_adv(&p);
570 else
571 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100572 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000573
574 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100575 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000576 for (i = 0; i < min_len; ++i)
577 {
glepnir6e199932024-12-14 21:13:27 +0100578 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000579 if (MB_ISLOWER(c))
580 {
581 has_lower = TRUE;
582 if (MB_ISUPPER(wca[i]))
583 {
584 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100585 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000586 wca[i] = MB_TOLOWER(wca[i]);
587 break;
588 }
589 }
590 }
591
592 // Rule 2: No lower case, 2nd consecutive letter converted to
593 // upper case.
594 if (!has_lower)
595 {
John Marriott5e6ea922024-11-23 14:01:57 +0100596 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000597 for (i = 0; i < min_len; ++i)
598 {
glepnir6e199932024-12-14 21:13:27 +0100599 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000600 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
601 {
602 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100603 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000604 wca[i] = MB_TOUPPER(wca[i]);
605 break;
606 }
607 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
608 }
609 }
610
611 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100612 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000613 for (i = 0; i < min_len; ++i)
614 {
glepnir6e199932024-12-14 21:13:27 +0100615 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000616 if (MB_ISLOWER(c))
617 wca[i] = MB_TOLOWER(wca[i]);
618 else if (MB_ISUPPER(c))
619 wca[i] = MB_TOUPPER(wca[i]);
620 }
621
622 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000623 p = IObuff;
624 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100625 ga_init2(&gap, 1, 500);
626 while (i < char_len)
627 {
628 if (gap.ga_data != NULL)
629 {
630 if (ga_grow(&gap, 10) == FAIL)
631 {
632 ga_clear(&gap);
633 return (char_u *)"[failed]";
634 }
635 p = (char_u *)gap.ga_data + gap.ga_len;
636 if (has_mbyte)
637 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
638 else
639 {
640 *p = wca[i++];
641 ++gap.ga_len;
642 }
643 }
644 else if ((p - IObuff) + 6 >= IOSIZE)
645 {
646 // Multi-byte characters can occupy up to five bytes more than
647 // ASCII characters, and we also need one byte for NUL, so when
648 // getting to six bytes from the edge of IObuff switch to using a
649 // growarray. Add the character in the next round.
650 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100651 {
652 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100653 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100654 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100655 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100656 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100657 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100658 }
659 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000660 p += (*mb_char2bytes)(wca[i++], p);
661 else
662 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100663 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000664 vim_free(wca);
665
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100666 if (gap.ga_data != NULL)
667 {
668 *tofree = gap.ga_data;
669 return gap.ga_data;
670 }
671
672 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000673 return IObuff;
674}
675
676/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100677 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
678 * case of the originally typed text is used, and the case of the completed
679 * text is inferred, ie this tries to work out what case you probably wanted
680 * the rest of the word to be in -- webb
681 */
682 int
683ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200684 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100685 int len,
686 int icase,
687 char_u *fname,
688 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200689 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100690{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200691 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100693 int char_len; // count multi-byte characters
694 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100695 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200696 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100697 int res;
698 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100699
700 if (p_ic && curbuf->b_p_inf && len > 0)
701 {
702 // Infer case of completed part.
703
704 // Find actual length of completion.
705 if (has_mbyte)
706 {
707 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100708 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100709 while (*p != NUL)
710 {
711 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100712 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100713 }
714 }
715 else
glepnir6e199932024-12-14 21:13:27 +0100716 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100717 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100718 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719
720 // Find actual length of original text.
721 if (has_mbyte)
722 {
John Marriott5e6ea922024-11-23 14:01:57 +0100723 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100724 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 while (*p != NUL)
726 {
727 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100728 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100729 }
730 }
731 else
glepnir6e199932024-12-14 21:13:27 +0100732 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100733 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100734 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100737 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100738 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100739
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 str = ins_compl_infercase_gettext(str, char_len,
741 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200743 if (cont_s_ipos)
744 flags |= CP_CONT_S_IPOS;
745 if (icase)
746 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200747
glepnir5c66e232024-11-15 19:58:27 +0100748 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100749 vim_free(tofree);
750 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100751}
752
753/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000754 * Add a match to the list of matches. The arguments are:
755 * str - text of the match to add
756 * len - length of "str". If -1, then the length of "str" is
757 * computed.
758 * fname - file name to associate with this match.
759 * cptext - list of strings to use with this match (for abbr, menu, info
760 * and kind)
761 * user_data - user supplied data (any vim type) for this match
762 * cdir - match direction. If 0, use "compl_direction".
763 * flags_arg - match flags (cp_flags)
764 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100765 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000766 * If "cdir" is FORWARD, then the match is added after the current match.
767 * Otherwise, it is added before the current match.
768 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100769 * If the given string is already in the list of completions, then return
770 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
771 * maybe because alloc() returns NULL, then FAIL is returned.
772 */
773 static int
774ins_compl_add(
775 char_u *str,
776 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100778 char_u **cptext, // extra text for popup menu or NULL
779 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200781 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200782 int adup, // accept duplicate match
glepnir80b66202024-11-27 21:53:53 +0100783 int *user_hl) // user abbr/kind hlattr
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784{
785 compl_T *match;
786 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200787 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100788
Bram Moolenaarceb06192021-04-04 15:05:22 +0200789 if (flags & CP_FAST)
790 fast_breakcheck();
791 else
792 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100793 if (got_int)
794 return FAIL;
795 if (len < 0)
796 len = (int)STRLEN(str);
797
798 // If the same match is already present, don't add it.
799 if (compl_first_match != NULL && !adup)
800 {
801 match = compl_first_match;
802 do
803 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000804 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100805 && STRNCMP(match->cp_str.string, str, len) == 0
806 && ((int)match->cp_str.length <= len
807 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100808 return NOTDONE;
809 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000810 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100811 }
812
813 // Remove any popup menu before changing the list of matches.
814 ins_compl_del_pum();
815
816 // Allocate a new match structure.
817 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200818 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 if (match == NULL)
820 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100821 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100822 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100823 {
824 vim_free(match);
825 return FAIL;
826 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100827
John Marriott5e6ea922024-11-23 14:01:57 +0100828 match->cp_str.length = len;
829
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100830 // match-fname is:
831 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200832 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100833 // - NULL otherwise. --Acevedo
834 if (fname != NULL
835 && compl_curr_match != NULL
836 && compl_curr_match->cp_fname != NULL
837 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
838 match->cp_fname = compl_curr_match->cp_fname;
839 else if (fname != NULL)
840 {
841 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200842 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100843 }
844 else
845 match->cp_fname = NULL;
846 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100847 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
848 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100849
850 if (cptext != NULL)
851 {
852 int i;
853
854 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100855 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856 if (cptext[i] != NULL && *cptext[i] != NUL)
857 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100858 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100860#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100861 if (user_data != NULL)
862 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100863#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100864
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000865 // Link the new match structure after (FORWARD) or before (BACKWARD) the
866 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100867 if (compl_first_match == NULL)
868 match->cp_next = match->cp_prev = NULL;
869 else if (dir == FORWARD)
870 {
871 match->cp_next = compl_curr_match->cp_next;
872 match->cp_prev = compl_curr_match;
873 }
874 else // BACKWARD
875 {
876 match->cp_next = compl_curr_match;
877 match->cp_prev = compl_curr_match->cp_prev;
878 }
879 if (match->cp_next)
880 match->cp_next->cp_prev = match;
881 if (match->cp_prev)
882 match->cp_prev->cp_next = match;
883 else // if there's nothing before, it is the first match
884 compl_first_match = match;
885 compl_curr_match = match;
886
887 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 ins_compl_longest_match(match);
890
891 return OK;
892}
893
894/*
895 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200896 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100897 */
898 static int
899ins_compl_equal(compl_T *match, char_u *str, int len)
900{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200901 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200902 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200903 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100904 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
905 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100906}
907
908/*
glepnir6a38aff2024-12-16 21:56:16 +0100909 * when len is -1 mean use whole length of p otherwise part of p
910 */
911 static void
912ins_compl_insert_bytes(char_u *p, int len)
913{
914 if (len == -1)
915 len = (int)STRLEN(p);
916 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +0100917 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +0100918}
919
920/*
zeertzjqd32bf0a2024-12-17 20:55:13 +0100921 * Checks if the column is within the currently inserted completion text
922 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +0100923 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +0100924 */
925 int
glepnir76bdb822025-02-08 19:04:51 +0100926ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +0100927{
glepnir76bdb822025-02-08 19:04:51 +0100928 int start_col;
929 int attr;
930
931 if ((get_cot_flags() & COT_FUZZY)
932 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +0100933 return -1;
934
glepnir76bdb822025-02-08 19:04:51 +0100935 start_col = compl_col + (int)ins_compl_leader_len();
936 if (!ins_compl_has_multiple())
937 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
938
939 // Multiple lines
940 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
941 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
942 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
943 return attr;
glepnir6a38aff2024-12-16 21:56:16 +0100944
945 return -1;
946}
947
948/*
glepnir76bdb822025-02-08 19:04:51 +0100949 * Returns TRUE if the current completion string contains newline characters,
950 * indicating it's a multi-line completion.
951 */
952 static int
953ins_compl_has_multiple(void)
954{
955 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
956}
957
958/*
959 * Returns TRUE if the given line number falls within the range of a multi-line
960 * completion, i.e. between the starting line (compl_lnum) and current cursor
961 * line. Always returns FALSE for single-line completions.
962 */
963 int
964ins_compl_lnum_in_range(linenr_T lnum)
965{
966 if (!ins_compl_has_multiple())
967 return FALSE;
968 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
969}
970
971/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100972 * Reduce the longest common string for match "match".
973 */
974 static void
975ins_compl_longest_match(compl_T *match)
976{
977 char_u *p, *s;
978 int c1, c2;
979 int had_match;
980
John Marriott5e6ea922024-11-23 14:01:57 +0100981 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100982 {
983 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +0100984 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
985 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000986 return;
987
John Marriott5e6ea922024-11-23 14:01:57 +0100988 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000989 had_match = (curwin->w_cursor.col > compl_col);
990 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +0100991 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000992 ins_redraw(FALSE);
993
994 // When the match isn't there (to avoid matching itself) remove it
995 // again after redrawing.
996 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100997 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100998 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000999
1000 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001001 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001002
1003 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001004 p = compl_leader.string;
1005 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001006 while (*p != NUL)
1007 {
1008 if (has_mbyte)
1009 {
1010 c1 = mb_ptr2char(p);
1011 c2 = mb_ptr2char(s);
1012 }
1013 else
1014 {
1015 c1 = *p;
1016 c2 = *s;
1017 }
1018 if ((match->cp_flags & CP_ICASE)
1019 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1020 break;
1021 if (has_mbyte)
1022 {
1023 MB_PTR_ADV(p);
1024 MB_PTR_ADV(s);
1025 }
1026 else
1027 {
1028 ++p;
1029 ++s;
1030 }
1031 }
1032
1033 if (*p != NUL)
1034 {
1035 // Leader was shortened, need to change the inserted text.
1036 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001037 compl_leader.length = (size_t)(p - compl_leader.string);
1038
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001039 had_match = (curwin->w_cursor.col > compl_col);
1040 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01001041 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001042 ins_redraw(FALSE);
1043
1044 // When the match isn't there (to avoid matching itself) remove it
1045 // again after redrawing.
1046 if (!had_match)
1047 ins_compl_delete();
1048 }
1049
1050 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001051}
1052
1053/*
1054 * Add an array of matches to the list of matches.
1055 * Frees matches[].
1056 */
1057 static void
1058ins_compl_add_matches(
1059 int num_matches,
1060 char_u **matches,
1061 int icase)
1062{
1063 int i;
1064 int add_r = OK;
1065 int dir = compl_direction;
1066
1067 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001068 {
1069 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
1070 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL);
1071 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001072 // if dir was BACKWARD then honor it just once
1073 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001074 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001075 FreeWild(num_matches, matches);
1076}
1077
1078/*
1079 * Make the completion list cyclic.
1080 * Return the number of matches (excluding the original).
1081 */
1082 static int
1083ins_compl_make_cyclic(void)
1084{
1085 compl_T *match;
1086 int count = 0;
1087
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001088 if (compl_first_match == NULL)
1089 return 0;
1090
1091 // Find the end of the list.
1092 match = compl_first_match;
1093 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001094 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001095 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001096 match = match->cp_next;
1097 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001098 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001099 match->cp_next = compl_first_match;
1100 compl_first_match->cp_prev = match;
1101
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001102 return count;
1103}
1104
1105/*
1106 * Return whether there currently is a shown match.
1107 */
1108 int
1109ins_compl_has_shown_match(void)
1110{
1111 return compl_shown_match == NULL
1112 || compl_shown_match != compl_shown_match->cp_next;
1113}
1114
1115/*
1116 * Return whether the shown match is long enough.
1117 */
1118 int
1119ins_compl_long_shown_match(void)
1120{
John Marriott5e6ea922024-11-23 14:01:57 +01001121 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001122 > curwin->w_cursor.col - compl_col;
1123}
1124
1125/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001126 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001127 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001128 unsigned int
1129get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001130{
zeertzjq529b9ad2024-06-05 20:27:06 +02001131 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001132}
1133
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134/*
1135 * Update the screen and when there is any scrolling remove the popup menu.
1136 */
1137 static void
1138ins_compl_upd_pum(void)
1139{
1140 int h;
1141
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001142 if (compl_match_array == NULL)
1143 return;
1144
1145 h = curwin->w_cline_height;
1146 // Update the screen later, before drawing the popup menu over it.
1147 pum_call_update_screen();
1148 if (h != curwin->w_cline_height)
1149 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001150}
1151
1152/*
1153 * Remove any popup menu.
1154 */
1155 static void
1156ins_compl_del_pum(void)
1157{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 if (compl_match_array == NULL)
1159 return;
1160
1161 pum_undisplay();
1162 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001163}
1164
1165/*
1166 * Return TRUE if the popup menu should be displayed.
1167 */
1168 int
1169pum_wanted(void)
1170{
1171 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001172 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001173 return FALSE;
1174
1175 // The display looks bad on a B&W display.
1176 if (t_colors < 8
1177#ifdef FEAT_GUI
1178 && !gui.in_use
1179#endif
1180 )
1181 return FALSE;
1182 return TRUE;
1183}
1184
1185/*
1186 * Return TRUE if there are two or more matches to be shown in the popup menu.
1187 * One if 'completopt' contains "menuone".
1188 */
1189 static int
1190pum_enough_matches(void)
1191{
1192 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001193 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001194
1195 // Don't display the popup menu if there are no matches or there is only
1196 // one (ignoring the original text).
1197 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001198 do
1199 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001200 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001201 break;
1202 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001203 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001204
zeertzjq529b9ad2024-06-05 20:27:06 +02001205 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001206 return (i >= 1);
1207 return (i >= 2);
1208}
1209
Bram Moolenaar3075a452021-11-17 15:51:52 +00001210#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001211/*
1212 * Allocate Dict for the completed item.
1213 * { word, abbr, menu, kind, info }
1214 */
1215 static dict_T *
1216ins_compl_dict_alloc(compl_T *match)
1217{
1218 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1219
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001220 if (dict == NULL)
1221 return NULL;
1222
John Marriott5e6ea922024-11-23 14:01:57 +01001223 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001224 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1225 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1226 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1227 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1228 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1229 dict_add_string(dict, "user_data", (char_u *)"");
1230 else
1231 dict_add_tv(dict, "user_data", &match->cp_user_data);
1232
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001233 return dict;
1234}
1235
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001236/*
1237 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1238 * completion menu is changed.
1239 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001240 static void
1241trigger_complete_changed_event(int cur)
1242{
1243 dict_T *v_event;
1244 dict_T *item;
1245 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001246 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001247
1248 if (recursive)
1249 return;
1250
glepnir40891ba2025-02-10 22:18:00 +01001251 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001252 if (item == NULL)
1253 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001254 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001255 dict_add_dict(v_event, "completed_item", item);
1256 pum_set_event_info(v_event);
1257 dict_set_items_ro(v_event);
1258
1259 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001260 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001261 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001262 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001263 recursive = FALSE;
1264
Bram Moolenaar3075a452021-11-17 15:51:52 +00001265 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001266}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001267#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001268
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001269/*
glepnira218cc62024-06-03 19:32:39 +02001270 * pumitem qsort compare func
1271 */
1272 static int
zeertzjq8e567472024-06-14 20:04:42 +02001273ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001274{
1275 const int sa = (*(pumitem_T *)a).pum_score;
1276 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001277 const int ia = (*(pumitem_T *)a).pum_idx;
1278 const int ib = (*(pumitem_T *)b).pum_idx;
1279 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001280}
1281
1282/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001283 * Build a popup menu to show the completion matches.
1284 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1285 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001286 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001287 static int
1288ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001289{
1290 compl_T *compl;
1291 compl_T *shown_compl = NULL;
1292 int did_find_shown_match = FALSE;
1293 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001294 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001295 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001296 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001297 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001298 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001299 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1300 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001301 compl_T *match_head = NULL;
1302 compl_T *match_tail = NULL;
1303 compl_T *match_next = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001304
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001305 // Need to build the popup menu list.
1306 compl_match_arraysize = 0;
1307 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001308
glepnira49c0772024-11-30 10:56:30 +01001309 // If the current match is the original text don't find the first
1310 // match after it, don't highlight anything.
1311 if (match_at_original_text(compl_shown_match))
1312 shown_match_ok = TRUE;
1313
1314 if (compl_leader.string != NULL
1315 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1316 && shown_match_ok == FALSE)
1317 compl_shown_match = compl_no_select ? compl_first_match
1318 : compl_first_match->cp_next;
1319
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001320 do
1321 {
glepnird4088ed2024-12-31 10:55:22 +01001322 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001323 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1324 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001325 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001326 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001327
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001328 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001329 && (compl_leader.string == NULL
1330 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001331 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001332 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001333 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001334 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001335 if (match_head == NULL)
1336 match_head = compl;
1337 else
glepnira49c0772024-11-30 10:56:30 +01001338 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001339 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001340
glepnirf400a0c2025-01-23 19:55:14 +01001341 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001342 {
1343 if (compl == compl_shown_match || did_find_shown_match)
1344 {
1345 // This item is the shown match or this is the
1346 // first displayed item after the shown match.
1347 compl_shown_match = compl;
1348 did_find_shown_match = TRUE;
1349 shown_match_ok = TRUE;
1350 }
1351 else
1352 // Remember this displayed match for when the
1353 // shown match is just below it.
1354 shown_compl = compl;
1355 cur = i;
1356 }
glepnirf400a0c2025-01-23 19:55:14 +01001357 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001358 {
1359 if (i == 0)
1360 shown_compl = compl;
1361 // Update the maximum fuzzy score and the shown match
1362 // if the current item's score is higher
zeertzjqd65aa1b2025-01-25 15:29:03 +01001363 if (fuzzy_sort && compl->cp_score > max_fuzzy_score)
glepnira49c0772024-11-30 10:56:30 +01001364 {
1365 did_find_shown_match = TRUE;
1366 max_fuzzy_score = compl->cp_score;
1367 if (!compl_no_select)
1368 compl_shown_match = compl;
1369 }
zeertzjqd65aa1b2025-01-25 15:29:03 +01001370 else if (!fuzzy_sort && i == 0 && !compl_no_select)
glepnirf400a0c2025-01-23 19:55:14 +01001371 compl_shown_match = shown_compl;
glepnira49c0772024-11-30 10:56:30 +01001372
1373 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1374 {
1375 cur = i;
1376 shown_match_ok = TRUE;
1377 }
1378 }
1379 i++;
glepnir80b66202024-11-27 21:53:53 +01001380 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001381
glepnirf400a0c2025-01-23 19:55:14 +01001382 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001383 {
1384 did_find_shown_match = TRUE;
1385
1386 // When the original text is the shown match don't set
1387 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001388 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001389 shown_match_ok = TRUE;
1390
1391 if (!shown_match_ok && shown_compl != NULL)
1392 {
1393 // The shown match isn't displayed, set it to the
1394 // previously displayed match.
1395 compl_shown_match = shown_compl;
1396 shown_match_ok = TRUE;
1397 }
1398 }
glepnira49c0772024-11-30 10:56:30 +01001399 compl = compl->cp_next;
1400 } while (compl != NULL && !is_first_match(compl));
1401
1402 if (compl_match_arraysize == 0)
1403 return -1;
1404
1405 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1406 if (compl_match_array == NULL)
1407 return -1;
1408
1409 compl = match_head;
1410 i = 0;
1411 while (compl != NULL)
1412 {
glepnir6e199932024-12-14 21:13:27 +01001413 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1414 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001415 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1416 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1417 compl_match_array[i].pum_score = compl->cp_score;
1418 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1419 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001420 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1421 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001422 match_next = compl->cp_match_next;
1423 compl->cp_match_next = NULL;
1424 compl = match_next;
1425 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001426
zeertzjqd65aa1b2025-01-25 15:29:03 +01001427 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001428 {
1429 for (i = 0; i < compl_match_arraysize; i++)
1430 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001431 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001432 qsort(compl_match_array, (size_t)compl_match_arraysize,
1433 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001434 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001435 }
glepnira218cc62024-06-03 19:32:39 +02001436
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001437 if (!shown_match_ok) // no displayed match at all
1438 cur = -1;
1439
1440 return cur;
1441}
1442
1443/*
1444 * Show the popup menu for the list of matches.
1445 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1446 */
1447 void
1448ins_compl_show_pum(void)
1449{
1450 int i;
1451 int cur = -1;
1452 colnr_T col;
1453
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001454 if (!pum_wanted() || !pum_enough_matches())
1455 return;
1456
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001457 // Update the screen later, before drawing the popup menu over it.
1458 pum_call_update_screen();
1459
1460 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001461 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001462 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001463 else
1464 {
1465 // popup menu already exists, only need to find the current item.
1466 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001467 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001468 || compl_match_array[i].pum_text
1469 == compl_shown_match->cp_text[CPT_ABBR])
1470 {
1471 cur = i;
1472 break;
1473 }
1474 }
1475
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001476 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001477 {
1478#ifdef FEAT_EVAL
1479 if (compl_started && has_completechanged())
1480 trigger_complete_changed_event(cur);
1481#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001482 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001483 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001484
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001485 // In Replace mode when a $ is displayed at the end of the line only
1486 // part of the screen would be updated. We do need to redraw here.
1487 dollar_vcol = -1;
1488
1489 // Compute the screen column of the start of the completed text.
1490 // Use the cursor to get all wrapping and other settings right.
1491 col = curwin->w_cursor.col;
1492 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001493 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001494 pum_display(compl_match_array, compl_match_arraysize, cur);
1495 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001496
glepnircbb46b42024-02-03 18:11:13 +01001497 // After adding leader, set the current match to shown match.
1498 if (compl_started && compl_curr_match != compl_shown_match)
1499 compl_curr_match = compl_shown_match;
1500
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001501#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001502 if (has_completechanged())
1503 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001504#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001505}
1506
1507#define DICT_FIRST (1) // use just first element in "dict"
1508#define DICT_EXACT (2) // "dict" is the exact name of a file
1509
1510/*
glepnir40c1c332024-06-11 19:37:04 +02001511 * Get current completion leader
1512 */
1513 char_u *
1514ins_compl_leader(void)
1515{
John Marriott5e6ea922024-11-23 14:01:57 +01001516 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1517}
1518
1519/*
1520 * Get current completion leader length
1521 */
1522 size_t
1523ins_compl_leader_len(void)
1524{
1525 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001526}
1527
1528/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001529 * Add any identifiers that match the given pattern "pat" in the list of
1530 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001531 */
1532 static void
1533ins_compl_dictionaries(
1534 char_u *dict_start,
1535 char_u *pat,
1536 int flags, // DICT_FIRST and/or DICT_EXACT
1537 int thesaurus) // Thesaurus completion
1538{
1539 char_u *dict = dict_start;
1540 char_u *ptr;
1541 char_u *buf;
1542 regmatch_T regmatch;
1543 char_u **files;
1544 int count;
1545 int save_p_scs;
1546 int dir = compl_direction;
1547
1548 if (*dict == NUL)
1549 {
1550#ifdef FEAT_SPELL
1551 // When 'dictionary' is empty and spell checking is enabled use
1552 // "spell".
1553 if (!thesaurus && curwin->w_p_spell)
1554 dict = (char_u *)"spell";
1555 else
1556#endif
1557 return;
1558 }
1559
1560 buf = alloc(LSIZE);
1561 if (buf == NULL)
1562 return;
1563 regmatch.regprog = NULL; // so that we can goto theend
1564
1565 // If 'infercase' is set, don't use 'smartcase' here
1566 save_p_scs = p_scs;
1567 if (curbuf->b_p_inf)
1568 p_scs = FALSE;
1569
1570 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1571 // to only match at the start of a line. Otherwise just match the
1572 // pattern. Also need to double backslashes.
1573 if (ctrl_x_mode_line_or_eval())
1574 {
1575 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1576 size_t len;
1577
1578 if (pat_esc == NULL)
1579 goto theend;
1580 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001581 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001582 if (ptr == NULL)
1583 {
1584 vim_free(pat_esc);
1585 goto theend;
1586 }
1587 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1588 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1589 vim_free(pat_esc);
1590 vim_free(ptr);
1591 }
1592 else
1593 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001594 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001595 if (regmatch.regprog == NULL)
1596 goto theend;
1597 }
1598
1599 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1600 regmatch.rm_ic = ignorecase(pat);
1601 while (*dict != NUL && !got_int && !compl_interrupted)
1602 {
1603 // copy one dictionary file name into buf
1604 if (flags == DICT_EXACT)
1605 {
1606 count = 1;
1607 files = &dict;
1608 }
1609 else
1610 {
1611 // Expand wildcards in the dictionary name, but do not allow
1612 // backticks (for security, the 'dict' option may have been set in
1613 // a modeline).
1614 copy_option_part(&dict, buf, LSIZE, ",");
1615# ifdef FEAT_SPELL
1616 if (!thesaurus && STRCMP(buf, "spell") == 0)
1617 count = -1;
1618 else
1619# endif
1620 if (vim_strchr(buf, '`') != NULL
1621 || expand_wildcards(1, &buf, &count, &files,
1622 EW_FILE|EW_SILENT) != OK)
1623 count = 0;
1624 }
1625
1626# ifdef FEAT_SPELL
1627 if (count == -1)
1628 {
1629 // Complete from active spelling. Skip "\<" in the pattern, we
1630 // don't use it as a RE.
1631 if (pat[0] == '\\' && pat[1] == '<')
1632 ptr = pat + 2;
1633 else
1634 ptr = pat;
1635 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1636 }
1637 else
1638# endif
1639 if (count > 0) // avoid warning for using "files" uninit
1640 {
1641 ins_compl_files(count, files, thesaurus, flags,
1642 &regmatch, buf, &dir);
1643 if (flags != DICT_EXACT)
1644 FreeWild(count, files);
1645 }
1646 if (flags != 0)
1647 break;
1648 }
1649
1650theend:
1651 p_scs = save_p_scs;
1652 vim_regfree(regmatch.regprog);
1653 vim_free(buf);
1654}
1655
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001656/*
1657 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1658 * skipping the word at 'skip_word'. Returns OK on success.
1659 */
1660 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001661thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001662 char_u *fname,
1663 char_u **buf_arg,
1664 int dir,
1665 char_u *skip_word)
1666{
1667 int status = OK;
1668 char_u *ptr;
1669 char_u *wstart;
1670
1671 // Add the other matches on the line
1672 ptr = *buf_arg;
1673 while (!got_int)
1674 {
1675 // Find start of the next word. Skip white
1676 // space and punctuation.
1677 ptr = find_word_start(ptr);
1678 if (*ptr == NUL || *ptr == NL)
1679 break;
1680 wstart = ptr;
1681
1682 // Find end of the word.
1683 if (has_mbyte)
1684 // Japanese words may have characters in
1685 // different classes, only separate words
1686 // with single-byte non-word characters.
1687 while (*ptr != NUL)
1688 {
1689 int l = (*mb_ptr2len)(ptr);
1690
1691 if (l < 2 && !vim_iswordc(*ptr))
1692 break;
1693 ptr += l;
1694 }
1695 else
1696 ptr = find_word_end(ptr);
1697
1698 // Add the word. Skip the regexp match.
1699 if (wstart != skip_word)
1700 {
1701 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1702 fname, dir, FALSE);
1703 if (status == FAIL)
1704 break;
1705 }
1706 }
1707
1708 *buf_arg = ptr;
1709 return status;
1710}
1711
1712/*
1713 * Process "count" dictionary/thesaurus "files" and add the text matching
1714 * "regmatch".
1715 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001716 static void
1717ins_compl_files(
1718 int count,
1719 char_u **files,
1720 int thesaurus,
1721 int flags,
1722 regmatch_T *regmatch,
1723 char_u *buf,
1724 int *dir)
1725{
1726 char_u *ptr;
1727 int i;
1728 FILE *fp;
1729 int add_r;
1730
1731 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1732 {
1733 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001734 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001735 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001736 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001737 vim_snprintf((char *)IObuff, IOSIZE,
1738 _("Scanning dictionary: %s"), (char *)files[i]);
1739 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1740 }
1741
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001742 if (fp == NULL)
1743 continue;
1744
1745 // Read dictionary file line by line.
1746 // Check each line for a match.
1747 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001748 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001749 ptr = buf;
1750 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001751 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001752 ptr = regmatch->startp[0];
glepnir6e199932024-12-14 21:13:27 +01001753 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1754 : find_word_end(ptr);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001755 add_r = ins_compl_add_infercase(regmatch->startp[0],
1756 (int)(ptr - regmatch->startp[0]),
1757 p_ic, files[i], *dir, FALSE);
1758 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001759 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001760 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001761 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001762 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001763 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001764 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001765 if (add_r == OK)
1766 // if dir was BACKWARD then honor it just once
1767 *dir = FORWARD;
1768 else if (add_r == FAIL)
1769 break;
1770 // avoid expensive call to vim_regexec() when at end
1771 // of line
1772 if (*ptr == '\n' || got_int)
1773 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001774 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001775 line_breakcheck();
1776 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001777 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001778 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001779 }
1780}
1781
1782/*
1783 * Find the start of the next word.
1784 * Returns a pointer to the first char of the word. Also stops at a NUL.
1785 */
1786 char_u *
1787find_word_start(char_u *ptr)
1788{
1789 if (has_mbyte)
1790 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1791 ptr += (*mb_ptr2len)(ptr);
1792 else
1793 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1794 ++ptr;
1795 return ptr;
1796}
1797
1798/*
1799 * Find the end of the word. Assumes it starts inside a word.
1800 * Returns a pointer to just after the word.
1801 */
1802 char_u *
1803find_word_end(char_u *ptr)
1804{
1805 int start_class;
1806
1807 if (has_mbyte)
1808 {
1809 start_class = mb_get_class(ptr);
1810 if (start_class > 1)
1811 while (*ptr != NUL)
1812 {
1813 ptr += (*mb_ptr2len)(ptr);
1814 if (mb_get_class(ptr) != start_class)
1815 break;
1816 }
1817 }
1818 else
1819 while (vim_iswordc(*ptr))
1820 ++ptr;
1821 return ptr;
1822}
1823
1824/*
1825 * Find the end of the line, omitting CR and NL at the end.
1826 * Returns a pointer to just after the line.
1827 */
1828 static char_u *
1829find_line_end(char_u *ptr)
1830{
1831 char_u *s;
1832
1833 s = ptr + STRLEN(ptr);
1834 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1835 --s;
1836 return s;
1837}
1838
1839/*
1840 * Free the list of completions
1841 */
1842 static void
1843ins_compl_free(void)
1844{
1845 compl_T *match;
1846 int i;
1847
John Marriott5e6ea922024-11-23 14:01:57 +01001848 VIM_CLEAR_STRING(compl_pattern);
1849 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001850
1851 if (compl_first_match == NULL)
1852 return;
1853
1854 ins_compl_del_pum();
1855 pum_clear();
1856
1857 compl_curr_match = compl_first_match;
1858 do
1859 {
1860 match = compl_curr_match;
1861 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001862 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001863 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001864 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001865 vim_free(match->cp_fname);
1866 for (i = 0; i < CPT_COUNT; ++i)
1867 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001868#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001869 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001870#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001871 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001872 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001873 compl_first_match = compl_curr_match = NULL;
1874 compl_shown_match = NULL;
1875 compl_old_match = NULL;
1876}
1877
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001878/*
1879 * Reset/clear the completion state.
1880 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001881 void
1882ins_compl_clear(void)
1883{
1884 compl_cont_status = 0;
1885 compl_started = FALSE;
1886 compl_matches = 0;
glepnir6a38aff2024-12-16 21:56:16 +01001887 compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001888 VIM_CLEAR_STRING(compl_pattern);
1889 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001890 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001891 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001892 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001893#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001894 // clear v:completed_item
1895 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001896#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001897}
1898
1899/*
1900 * Return TRUE when Insert completion is active.
1901 */
1902 int
1903ins_compl_active(void)
1904{
1905 return compl_started;
1906}
1907
1908/*
glepnir8d0bb6d2024-12-24 09:44:35 +01001909 * Return True when wp is the actual completion window
1910 */
1911 int
1912ins_compl_win_active(win_T *wp UNUSED)
1913{
1914 return ins_compl_active()
1915#if defined(FEAT_QUICKFIX)
1916 && (!wp->w_p_pvw
1917# ifdef FEAT_PROP_POPUP
1918 && !(wp->w_popup_flags & POPF_INFO)
1919# endif
1920 )
1921#endif
1922 ;
1923}
1924
1925/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001926 * Selected one of the matches. When FALSE the match was edited or using the
1927 * longest common string.
1928 */
1929 int
1930ins_compl_used_match(void)
1931{
1932 return compl_used_match;
1933}
1934
1935/*
1936 * Initialize get longest common string.
1937 */
1938 void
1939ins_compl_init_get_longest(void)
1940{
1941 compl_get_longest = FALSE;
1942}
1943
1944/*
1945 * Returns TRUE when insert completion is interrupted.
1946 */
1947 int
1948ins_compl_interrupted(void)
1949{
1950 return compl_interrupted;
1951}
1952
1953/*
1954 * Returns TRUE if the <Enter> key selects a match in the completion popup
1955 * menu.
1956 */
1957 int
1958ins_compl_enter_selects(void)
1959{
1960 return compl_enter_selects;
1961}
1962
1963/*
1964 * Return the column where the text starts that is being completed
1965 */
1966 colnr_T
1967ins_compl_col(void)
1968{
1969 return compl_col;
1970}
1971
1972/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001973 * Return the length in bytes of the text being completed
1974 */
1975 int
1976ins_compl_len(void)
1977{
1978 return compl_length;
1979}
1980
1981/*
glepniredd4ac32025-01-29 18:53:51 +01001982 * Return TRUE when preinsert is set otherwise FALSE.
1983 */
1984 static int
1985ins_compl_has_preinsert(void)
1986{
1987 return (get_cot_flags() & (COT_PREINSERT | COT_FUZZY)) == COT_PREINSERT;
1988}
1989
1990/*
1991 * Returns TRUE if the pre-insert effect is valid and the cursor is within
1992 * the `compl_ins_end_col` range.
1993 */
1994 int
1995ins_compl_preinsert_effect(void)
1996{
1997 if (!ins_compl_has_preinsert())
1998 return FALSE;
1999
2000 return curwin->w_cursor.col < compl_ins_end_col;
2001}
2002
2003/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002004 * Delete one character before the cursor and show the subset of the matches
2005 * that match the word that is now before the cursor.
2006 * Returns the character to be used, NUL if the work is done and another char
2007 * to be got from the user.
2008 */
2009 int
2010ins_compl_bs(void)
2011{
2012 char_u *line;
2013 char_u *p;
2014
glepniredd4ac32025-01-29 18:53:51 +01002015 if (ins_compl_preinsert_effect())
2016 ins_compl_delete();
2017
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002018 line = ml_get_curline();
2019 p = line + curwin->w_cursor.col;
2020 MB_PTR_BACK(line, p);
2021
2022 // Stop completion when the whole word was deleted. For Omni completion
2023 // allow the word to be deleted, we won't match everything.
2024 // Respect the 'backspace' option.
2025 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002026 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2027 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002028 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2029 - compl_length < 0))
2030 return K_BS;
2031
2032 // Deleted more than what was used to find matches or didn't finish
2033 // finding all matches: need to look for matches all over again.
2034 if (curwin->w_cursor.col <= compl_col + compl_length
2035 || ins_compl_need_restart())
2036 ins_compl_restart();
2037
John Marriott5e6ea922024-11-23 14:01:57 +01002038 VIM_CLEAR_STRING(compl_leader);
2039 compl_leader.length = (size_t)((p - line) - compl_col);
2040 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2041 if (compl_leader.string == NULL)
2042 {
2043 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002044 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002045 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002046
2047 ins_compl_new_leader();
2048 if (compl_shown_match != NULL)
2049 // Make sure current match is not a hidden item.
2050 compl_curr_match = compl_shown_match;
2051 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002052}
2053
2054/*
2055 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2056 * be called.
2057 */
2058 static int
2059ins_compl_need_restart(void)
2060{
2061 // Return TRUE if we didn't complete finding matches or when the
2062 // 'completefunc' returned "always" in the "refresh" dictionary item.
2063 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002064 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002065 && compl_opt_refresh_always);
2066}
2067
2068/*
2069 * Called after changing "compl_leader".
2070 * Show the popup menu with a different set of matches.
2071 * May also search for matches again if the previous search was interrupted.
2072 */
2073 static void
2074ins_compl_new_leader(void)
2075{
2076 ins_compl_del_pum();
2077 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002078 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002079 compl_used_match = FALSE;
2080
2081 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01002082 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002083 else
2084 {
2085#ifdef FEAT_SPELL
2086 spell_bad_len = 0; // need to redetect bad word
2087#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002088 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002089 // the popup menu display the changed text before the cursor. Set
2090 // "compl_restarting" to avoid that the first match is inserted.
2091 pum_call_update_screen();
2092#ifdef FEAT_GUI
2093 if (gui.in_use)
2094 {
2095 // Show the cursor after the match, not after the redrawn text.
2096 setcursor();
2097 out_flush_cursor(FALSE, FALSE);
2098 }
2099#endif
2100 compl_restarting = TRUE;
2101 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2102 compl_cont_status = 0;
2103 compl_restarting = FALSE;
2104 }
2105
2106 compl_enter_selects = !compl_used_match;
2107
2108 // Show the popup menu with a different set of matches.
2109 ins_compl_show_pum();
2110
2111 // Don't let Enter select the original text when there is no popup menu.
2112 if (compl_match_array == NULL)
2113 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002114 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2115 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002116}
2117
2118/*
2119 * Return the length of the completion, from the completion start column to
2120 * the cursor column. Making sure it never goes below zero.
2121 */
2122 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002123get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002124{
2125 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002126 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002127}
2128
2129/*
2130 * Append one character to the match leader. May reduce the number of
2131 * matches.
2132 */
2133 void
2134ins_compl_addleader(int c)
2135{
2136 int cc;
2137
glepniredd4ac32025-01-29 18:53:51 +01002138 if (ins_compl_preinsert_effect())
2139 ins_compl_delete();
2140
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002141 if (stop_arrow() == FAIL)
2142 return;
2143 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2144 {
2145 char_u buf[MB_MAXBYTES + 1];
2146
2147 (*mb_char2bytes)(c, buf);
2148 buf[cc] = NUL;
2149 ins_char_bytes(buf, cc);
2150 if (compl_opt_refresh_always)
2151 AppendToRedobuff(buf);
2152 }
2153 else
2154 {
2155 ins_char(c);
2156 if (compl_opt_refresh_always)
2157 AppendCharToRedobuff(c);
2158 }
2159
2160 // If we didn't complete finding matches we must search again.
2161 if (ins_compl_need_restart())
2162 ins_compl_restart();
2163
2164 // When 'always' is set, don't reset compl_leader. While completing,
2165 // cursor doesn't point original position, changing compl_leader would
2166 // break redo.
2167 if (!compl_opt_refresh_always)
2168 {
John Marriott5e6ea922024-11-23 14:01:57 +01002169 VIM_CLEAR_STRING(compl_leader);
2170 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2171 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2172 compl_leader.length);
2173 if (compl_leader.string == NULL)
2174 {
2175 compl_leader.length = 0;
2176 return;
2177 }
2178
2179 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002180 }
2181}
2182
2183/*
2184 * Setup for finding completions again without leaving CTRL-X mode. Used when
2185 * BS or a key was typed while still searching for matches.
2186 */
2187 static void
2188ins_compl_restart(void)
2189{
2190 ins_compl_free();
2191 compl_started = FALSE;
2192 compl_matches = 0;
2193 compl_cont_status = 0;
2194 compl_cont_mode = 0;
2195}
2196
2197/*
2198 * Set the first match, the original text.
2199 */
2200 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002201ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002202{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002203 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002204 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2205 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002206 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002207 {
John Marriott5e6ea922024-11-23 14:01:57 +01002208 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002209 if (p != NULL)
2210 {
John Marriott5e6ea922024-11-23 14:01:57 +01002211 VIM_CLEAR_STRING(compl_first_match->cp_str);
2212 compl_first_match->cp_str.string = p;
2213 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002214 }
2215 }
2216 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002217 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002218 {
John Marriott5e6ea922024-11-23 14:01:57 +01002219 char_u *p = vim_strnsave(str, len);
2220 if (p != NULL)
2221 {
2222 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2223 compl_first_match->cp_prev->cp_str.string = p;
2224 compl_first_match->cp_prev->cp_str.length = len;
2225 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002226 }
2227}
2228
2229/*
2230 * Append one character to the match leader. May reduce the number of
2231 * matches.
2232 */
2233 void
2234ins_compl_addfrommatch(void)
2235{
2236 char_u *p;
2237 int len = (int)curwin->w_cursor.col - (int)compl_col;
2238 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002239
John Marriott5e6ea922024-11-23 14:01:57 +01002240 p = compl_shown_match->cp_str.string;
2241 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002242 {
John Marriott5e6ea922024-11-23 14:01:57 +01002243 size_t plen;
2244 compl_T *cp;
2245
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002246 // When still at the original match use the first entry that matches
2247 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002248 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002249 return;
2250
2251 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002252 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002253 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002254 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002255 {
John Marriott5e6ea922024-11-23 14:01:57 +01002256 if (compl_leader.string == NULL
2257 || ins_compl_equal(cp, compl_leader.string,
2258 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002259 {
John Marriott5e6ea922024-11-23 14:01:57 +01002260 p = cp->cp_str.string;
2261 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002262 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002263 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002264 }
John Marriott5e6ea922024-11-23 14:01:57 +01002265 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002266 return;
2267 }
2268 p += len;
2269 c = PTR2CHAR(p);
2270 ins_compl_addleader(c);
2271}
2272
2273/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002274 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002275 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2276 * compl_cont_mode and compl_cont_status.
2277 * Returns TRUE when the character is not to be inserted.
2278 */
2279 static int
2280set_ctrl_x_mode(int c)
2281{
2282 int retval = FALSE;
2283
2284 switch (c)
2285 {
2286 case Ctrl_E:
2287 case Ctrl_Y:
2288 // scroll the window one line up or down
2289 ctrl_x_mode = CTRL_X_SCROLL;
2290 if (!(State & REPLACE_FLAG))
2291 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2292 else
2293 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2294 edit_submode_pre = NULL;
2295 showmode();
2296 break;
2297 case Ctrl_L:
2298 // complete whole line
2299 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2300 break;
2301 case Ctrl_F:
2302 // complete filenames
2303 ctrl_x_mode = CTRL_X_FILES;
2304 break;
2305 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002306 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002307 ctrl_x_mode = CTRL_X_DICTIONARY;
2308 break;
2309 case Ctrl_R:
2310 // Register insertion without exiting CTRL-X mode
2311 // Simply allow ^R to happen without affecting ^X mode
2312 break;
2313 case Ctrl_T:
2314 // complete words from a thesaurus
2315 ctrl_x_mode = CTRL_X_THESAURUS;
2316 break;
2317#ifdef FEAT_COMPL_FUNC
2318 case Ctrl_U:
2319 // user defined completion
2320 ctrl_x_mode = CTRL_X_FUNCTION;
2321 break;
2322 case Ctrl_O:
2323 // omni completion
2324 ctrl_x_mode = CTRL_X_OMNI;
2325 break;
2326#endif
2327 case 's':
2328 case Ctrl_S:
2329 // complete spelling suggestions
2330 ctrl_x_mode = CTRL_X_SPELL;
2331#ifdef FEAT_SPELL
2332 ++emsg_off; // Avoid getting the E756 error twice.
2333 spell_back_to_badword();
2334 --emsg_off;
2335#endif
2336 break;
2337 case Ctrl_RSB:
2338 // complete tag names
2339 ctrl_x_mode = CTRL_X_TAGS;
2340 break;
2341#ifdef FEAT_FIND_ID
2342 case Ctrl_I:
2343 case K_S_TAB:
2344 // complete keywords from included files
2345 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2346 break;
2347 case Ctrl_D:
2348 // complete definitions from included files
2349 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2350 break;
2351#endif
2352 case Ctrl_V:
2353 case Ctrl_Q:
2354 // complete vim commands
2355 ctrl_x_mode = CTRL_X_CMDLINE;
2356 break;
2357 case Ctrl_Z:
2358 // stop completion
2359 ctrl_x_mode = CTRL_X_NORMAL;
2360 edit_submode = NULL;
2361 showmode();
2362 retval = TRUE;
2363 break;
2364 case Ctrl_P:
2365 case Ctrl_N:
2366 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2367 // just started ^X mode, or there were enough ^X's to cancel
2368 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2369 // do normal expansion when interrupting a different mode (say
2370 // ^X^F^X^P or ^P^X^X^P, see below)
2371 // nothing changes if interrupting mode 0, (eg, the flag
2372 // doesn't change when going to ADDING mode -- Acevedo
2373 if (!(compl_cont_status & CONT_INTRPT))
2374 compl_cont_status |= CONT_LOCAL;
2375 else if (compl_cont_mode != 0)
2376 compl_cont_status &= ~CONT_LOCAL;
2377 // FALLTHROUGH
2378 default:
2379 // If we have typed at least 2 ^X's... for modes != 0, we set
2380 // compl_cont_status = 0 (eg, as if we had just started ^X
2381 // mode).
2382 // For mode 0, we set "compl_cont_mode" to an impossible
2383 // value, in both cases ^X^X can be used to restart the same
2384 // mode (avoiding ADDING mode).
2385 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2386 // 'complete' and local ^P expansions respectively.
2387 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2388 // mode -- Acevedo
2389 if (c == Ctrl_X)
2390 {
2391 if (compl_cont_mode != 0)
2392 compl_cont_status = 0;
2393 else
2394 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2395 }
2396 ctrl_x_mode = CTRL_X_NORMAL;
2397 edit_submode = NULL;
2398 showmode();
2399 break;
2400 }
2401
2402 return retval;
2403}
2404
2405/*
glepnir1c5a1202024-12-04 20:27:34 +01002406 * Trigger CompleteDone event and adds relevant information to v:event
2407 */
2408 static void
2409trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2410{
2411#if defined(FEAT_EVAL)
2412 save_v_event_T save_v_event;
2413 dict_T *v_event = get_v_event(&save_v_event);
2414 char_u *mode_str = NULL;
2415
2416 mode = mode & ~CTRL_X_WANT_IDENT;
2417 if (ctrl_x_mode_names[mode])
2418 mode_str = (char_u *)ctrl_x_mode_names[mode];
2419
2420 (void)dict_add_string(v_event, "complete_word",
2421 word == NULL ? (char_u *)"" : word);
2422 (void)dict_add_string(v_event, "complete_type",
2423 mode_str != NULL ? mode_str : (char_u *)"");
2424
2425 dict_set_items_ro(v_event);
2426#endif
2427 ins_apply_autocmds(EVENT_COMPLETEDONE);
2428
2429#if defined(FEAT_EVAL)
2430 restore_v_event(v_event, &save_v_event);
2431#endif
2432}
2433
2434/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002435 * Stop insert completion mode
2436 */
2437 static int
2438ins_compl_stop(int c, int prev_mode, int retval)
2439{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002440 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002441 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002442
2443 // Get here when we have finished typing a sequence of ^N and
2444 // ^P or other completion characters in CTRL-X mode. Free up
2445 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002446 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002447 {
glepnir40891ba2025-02-10 22:18:00 +01002448 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002449
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002450 // If any of the original typed text has been changed, eg when
2451 // ignorecase is set, we must add back-spaces to the redo
2452 // buffer. We add as few as necessary to delete just the part
2453 // of the original text that has changed.
2454 // When using the longest match, edited the match or used
2455 // CTRL-E then don't use the current match.
2456 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002457 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002458 ins_compl_fixRedoBufForLeader(ptr);
2459 }
2460
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002461 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002462
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002463 // When completing whole lines: fix indent for 'cindent'.
2464 // Otherwise, break line if it's too long.
2465 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2466 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002467 // re-indent the current line
2468 if (want_cindent)
2469 {
2470 do_c_expr_indent();
2471 want_cindent = FALSE; // don't do it again
2472 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002473 }
2474 else
2475 {
2476 int prev_col = curwin->w_cursor.col;
2477
2478 // put the cursor on the last char, for 'tw' formatting
2479 if (prev_col > 0)
2480 dec_cursor();
2481 // only format when something was inserted
2482 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2483 insertchar(NUL, 0, -1);
2484 if (prev_col > 0
2485 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2486 inc_cursor();
2487 }
2488
2489 // If the popup menu is displayed pressing CTRL-Y means accepting
2490 // the selection without inserting anything. When
2491 // compl_enter_selects is set the Enter key does the same.
2492 if ((c == Ctrl_Y || (compl_enter_selects
2493 && (c == CAR || c == K_KENTER || c == NL)))
2494 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002495 {
2496 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002497 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002498 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002499
2500 // CTRL-E means completion is Ended, go back to the typed text.
2501 // but only do this, if the Popup is still visible
2502 if (c == Ctrl_E)
2503 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002504 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002505 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002506
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002507 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002508 if (compl_leader.string != NULL)
2509 {
2510 p = compl_leader.string;
2511 plen = compl_leader.length;
2512 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002513 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002514 {
2515 p = compl_orig_text.string;
2516 plen = compl_orig_text.length;
2517 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002518 if (p != NULL)
2519 {
2520 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002521
John Marriott5e6ea922024-11-23 14:01:57 +01002522 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002523 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002524 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002525 retval = TRUE;
2526 }
2527
glepnir001c26c2025-02-02 09:36:22 +01002528 if ((c == Ctrl_W || c == Ctrl_U) && ins_compl_preinsert_effect())
2529 ins_compl_delete();
2530
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002531 auto_format(FALSE, TRUE);
2532
2533 // Trigger the CompleteDonePre event to give scripts a chance to
2534 // act upon the completion before clearing the info, and restore
2535 // ctrl_x_mode, so that complete_info() can be used.
2536 ctrl_x_mode = prev_mode;
2537 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2538
2539 ins_compl_free();
2540 compl_started = FALSE;
2541 compl_matches = 0;
2542 if (!shortmess(SHM_COMPLETIONMENU))
2543 msg_clr_cmdline(); // necessary for "noshowmode"
2544 ctrl_x_mode = CTRL_X_NORMAL;
2545 compl_enter_selects = FALSE;
2546 if (edit_submode != NULL)
2547 {
2548 edit_submode = NULL;
2549 showmode();
2550 }
2551
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002552 if (c == Ctrl_C && cmdwin_type != 0)
2553 // Avoid the popup menu remains displayed when leaving the
2554 // command line window.
2555 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002556 // Indent now if a key was typed that is in 'cinkeys'.
2557 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2558 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002559 // Trigger the CompleteDone event to give scripts a chance to act
2560 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002561 trigger_complete_done_event(prev_mode, word);
2562 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002563
2564 return retval;
2565}
2566
2567/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002568 * Prepare for Insert mode completion, or stop it.
2569 * Called just after typing a character in Insert mode.
2570 * Returns TRUE when the character is not to be inserted;
2571 */
2572 int
2573ins_compl_prep(int c)
2574{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002575 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002576 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002577
2578 // Forget any previous 'special' messages if this is actually
2579 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2580 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2581 edit_submode_extra = NULL;
2582
zeertzjq440d4cb2023-03-02 17:51:32 +00002583 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002584 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002585 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002586 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002587 return retval;
2588
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002589#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002590 // Ignore mouse events in a popup window
2591 if (is_mouse_key(c))
2592 {
2593 // Ignore drag and release events, the position does not need to be in
2594 // the popup and it may have just closed.
2595 if (c == K_LEFTRELEASE
2596 || c == K_LEFTRELEASE_NM
2597 || c == K_MIDDLERELEASE
2598 || c == K_RIGHTRELEASE
2599 || c == K_X1RELEASE
2600 || c == K_X2RELEASE
2601 || c == K_LEFTDRAG
2602 || c == K_MIDDLEDRAG
2603 || c == K_RIGHTDRAG
2604 || c == K_X1DRAG
2605 || c == K_X2DRAG)
2606 return retval;
2607 if (popup_visible)
2608 {
2609 int row = mouse_row;
2610 int col = mouse_col;
2611 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2612
2613 if (wp != NULL && WIN_IS_POPUP(wp))
2614 return retval;
2615 }
2616 }
2617#endif
2618
zeertzjqdca29d92021-08-31 19:12:51 +02002619 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2620 {
2621 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2622 || !vim_is_ctrl_x_key(c))
2623 {
2624 // Not starting another completion mode.
2625 ctrl_x_mode = CTRL_X_CMDLINE;
2626
2627 // CTRL-X CTRL-Z should stop completion without inserting anything
2628 if (c == Ctrl_Z)
2629 retval = TRUE;
2630 }
2631 else
2632 {
2633 ctrl_x_mode = CTRL_X_CMDLINE;
2634
2635 // Other CTRL-X keys first stop completion, then start another
2636 // completion mode.
2637 ins_compl_prep(' ');
2638 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2639 }
2640 }
2641
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002642 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002643 if (ctrl_x_mode_not_defined_yet()
2644 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002645 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002646 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002647 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002648 }
2649
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002650 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002651 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2652 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002653 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002654 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002655 {
2656 // We're already in CTRL-X mode, do we stay in it?
2657 if (!vim_is_ctrl_x_key(c))
2658 {
glepnir40891ba2025-02-10 22:18:00 +01002659 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002660 edit_submode = NULL;
2661 }
2662 showmode();
2663 }
2664
2665 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2666 {
2667 // Show error message from attempted keyword completion (probably
2668 // 'Pattern not found') until another key is hit, then go back to
2669 // showing what mode we are in.
2670 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002671 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002672 && c != Ctrl_R && !ins_compl_pum_key(c))
2673 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002674 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002675 }
2676 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2677 // Trigger the CompleteDone event to give scripts a chance to act
2678 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002679 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002680
LemonBoy2bf52dd2022-04-09 18:17:34 +01002681 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002682
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002683 // reset continue_* if we left expansion-mode, if we stay they'll be
2684 // (re)set properly in ins_complete()
2685 if (!vim_is_ctrl_x_key(c))
2686 {
2687 compl_cont_status = 0;
2688 compl_cont_mode = 0;
2689 }
2690
2691 return retval;
2692}
2693
2694/*
2695 * Fix the redo buffer for the completion leader replacing some of the typed
2696 * text. This inserts backspaces and appends the changed text.
2697 * "ptr" is the known leader text or NUL.
2698 */
2699 static void
2700ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2701{
John Marriott5e6ea922024-11-23 14:01:57 +01002702 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002703 char_u *p;
2704 char_u *ptr = ptr_arg;
2705
2706 if (ptr == NULL)
2707 {
John Marriott5e6ea922024-11-23 14:01:57 +01002708 if (compl_leader.string != NULL)
2709 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002710 else
2711 return; // nothing to do
2712 }
John Marriott5e6ea922024-11-23 14:01:57 +01002713 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002714 {
John Marriott5e6ea922024-11-23 14:01:57 +01002715 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002716 // Find length of common prefix between original text and new completion
2717 while (p[len] != NUL && p[len] == ptr[len])
2718 len++;
2719 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002720 if (len > 0)
2721 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002722 // Add backspace characters for each remaining character in
2723 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002724 for (p += len; *p != NUL; MB_PTR_ADV(p))
2725 AppendCharToRedobuff(K_BS);
2726 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002727 if (ptr != NULL)
2728 AppendToRedobuffLit(ptr + len, -1);
2729}
2730
2731/*
2732 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2733 * (depending on flag) starting from buf and looking for a non-scanned
2734 * buffer (other than curbuf). curbuf is special, if it is called with
2735 * buf=curbuf then it has to be the first call for a given flag/expansion.
2736 *
2737 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2738 */
2739 static buf_T *
2740ins_compl_next_buf(buf_T *buf, int flag)
2741{
2742 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01002743 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002744
2745 if (flag == 'w') // just windows
2746 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002747 if (buf == curbuf || !win_valid(wp))
2748 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002749 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01002750
2751 while (TRUE)
2752 {
2753 // Move to next window (wrap to first window if at the end)
2754 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
2755 // Break if we're back at start or found an unscanned buffer
2756 if (wp == curwin || !wp->w_buffer->b_scanned)
2757 break;
2758 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002759 buf = wp->w_buffer;
2760 }
2761 else
glepnir40891ba2025-02-10 22:18:00 +01002762 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002763 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2764 // (unlisted buffers)
2765 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01002766 while (TRUE)
2767 {
2768 // Move to next buffer (wrap to first buffer if at the end)
2769 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
2770 // Break if we're back at start buffer
2771 if (buf == curbuf)
2772 break;
2773
2774 // Check buffer conditions based on flag
2775 if (flag == 'U')
2776 skip_buffer = buf->b_p_bl;
2777 else
2778 skip_buffer = !buf->b_p_bl ||
2779 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
2780
2781 // Break if we found a buffer that matches our criteria
2782 if (!skip_buffer && !buf->b_scanned)
2783 break;
2784 }
2785 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002786 return buf;
2787}
2788
2789#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002790
2791# ifdef FEAT_EVAL
2792static callback_T cfu_cb; // 'completefunc' callback function
2793static callback_T ofu_cb; // 'omnifunc' callback function
2794static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2795# endif
2796
2797/*
2798 * Copy a global callback function to a buffer local callback.
2799 */
2800 static void
2801copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2802{
2803 free_callback(bufcb);
2804 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2805 copy_callback(bufcb, globcb);
2806}
2807
2808/*
2809 * Parse the 'completefunc' option value and set the callback function.
2810 * Invoked when the 'completefunc' option is set. The option value can be a
2811 * name of a function (string), or function(<name>) or funcref(<name>) or a
2812 * lambda expression.
2813 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002814 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002815did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002816{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002817 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2818 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002819
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002820 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002821
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002822 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002823}
2824
2825/*
2826 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002827 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002828 */
2829 void
2830set_buflocal_cfu_callback(buf_T *buf UNUSED)
2831{
2832# ifdef FEAT_EVAL
2833 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2834# endif
2835}
2836
2837/*
2838 * Parse the 'omnifunc' option value and set the callback function.
2839 * Invoked when the 'omnifunc' option is set. The option value can be a
2840 * name of a function (string), or function(<name>) or funcref(<name>) or a
2841 * lambda expression.
2842 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002843 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002844did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002845{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002846 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2847 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002848
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002849 set_buflocal_ofu_callback(curbuf);
2850 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002851}
2852
2853/*
2854 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002855 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002856 */
2857 void
2858set_buflocal_ofu_callback(buf_T *buf UNUSED)
2859{
2860# ifdef FEAT_EVAL
2861 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2862# endif
2863}
2864
2865/*
2866 * Parse the 'thesaurusfunc' option value and set the callback function.
2867 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2868 * name of a function (string), or function(<name>) or funcref(<name>) or a
2869 * lambda expression.
2870 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002871 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002872did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002873{
2874 int retval;
2875
zeertzjq6eda2692024-11-03 09:23:33 +01002876 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002877 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002878 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2879 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002880 else
2881 {
2882 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002883 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002884 // when using :set, free the local callback
2885 if (!(args->os_flags & OPT_GLOBAL))
2886 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002887 }
2888
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002889 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002890}
2891
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002892/*
2893 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002894 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002895 */
2896 int
2897set_ref_in_insexpand_funcs(int copyID)
2898{
2899 int abort = FALSE;
2900
2901 abort = set_ref_in_callback(&cfu_cb, copyID);
2902 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2903 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2904
2905 return abort;
2906}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002907
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002908/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002909 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002910 */
2911 static char_u *
2912get_complete_funcname(int type)
2913{
2914 switch (type)
2915 {
2916 case CTRL_X_FUNCTION:
2917 return curbuf->b_p_cfu;
2918 case CTRL_X_OMNI:
2919 return curbuf->b_p_ofu;
2920 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002921 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002922 default:
2923 return (char_u *)"";
2924 }
2925}
2926
2927/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002928 * Get the callback to use for insert mode completion.
2929 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002930 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002931get_insert_callback(int type)
2932{
2933 if (type == CTRL_X_FUNCTION)
2934 return &curbuf->b_cfu_cb;
2935 if (type == CTRL_X_OMNI)
2936 return &curbuf->b_ofu_cb;
2937 // CTRL_X_THESAURUS
2938 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2939}
2940
2941/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002942 * Execute user defined complete function 'completefunc', 'omnifunc' or
2943 * 'thesaurusfunc', and get matches in "matches".
2944 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002945 */
2946 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002947expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002948{
2949 list_T *matchlist = NULL;
2950 dict_T *matchdict = NULL;
2951 typval_T args[3];
2952 char_u *funcname;
2953 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002954 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002955 typval_T rettv;
2956 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002957 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002958
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002959 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002960 if (*funcname == NUL)
2961 return;
2962
2963 // Call 'completefunc' to obtain the list of matches.
2964 args[0].v_type = VAR_NUMBER;
2965 args[0].vval.v_number = 0;
2966 args[1].v_type = VAR_STRING;
2967 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2968 args[2].v_type = VAR_UNKNOWN;
2969
2970 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002971 // Lock the text to avoid weird things from happening. Also disallow
2972 // switching to another window, it should not be needed and may end up in
2973 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002974 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002975
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002976 cb = get_insert_callback(type);
2977 retval = call_callback(cb, 0, &rettv, 2, args);
2978
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002979 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002980 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002981 {
2982 switch (rettv.v_type)
2983 {
2984 case VAR_LIST:
2985 matchlist = rettv.vval.v_list;
2986 break;
2987 case VAR_DICT:
2988 matchdict = rettv.vval.v_dict;
2989 break;
2990 case VAR_SPECIAL:
2991 if (rettv.vval.v_number == VVAL_NONE)
2992 compl_opt_suppress_empty = TRUE;
2993 // FALLTHROUGH
2994 default:
2995 // TODO: Give error message?
2996 clear_tv(&rettv);
2997 break;
2998 }
2999 }
zeertzjqcfe45652022-05-27 17:26:55 +01003000 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003001
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003002 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003003 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003004 validate_cursor();
3005 if (!EQUAL_POS(curwin->w_cursor, pos))
3006 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003007 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003008 goto theend;
3009 }
3010
3011 if (matchlist != NULL)
3012 ins_compl_add_list(matchlist);
3013 else if (matchdict != NULL)
3014 ins_compl_add_dict(matchdict);
3015
3016theend:
3017 // Restore State, it might have been changed.
3018 State = save_State;
3019
3020 if (matchdict != NULL)
3021 dict_unref(matchdict);
3022 if (matchlist != NULL)
3023 list_unref(matchlist);
3024}
3025#endif // FEAT_COMPL_FUNC
3026
3027#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003028
3029 static inline int
3030get_user_highlight_attr(char_u *hlname)
3031{
3032 if (hlname != NULL && *hlname != NUL)
3033 return syn_name2attr(hlname);
3034 return -1;
3035}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003036/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003037 * Add a match to the list of matches from a typeval_T.
3038 * If the given string is already in the list of completions, then return
3039 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3040 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003041 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003042 */
3043 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003044ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003045{
3046 char_u *word;
3047 int dup = FALSE;
3048 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003049 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003050 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003051 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003052 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003053 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003054 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003055 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003056
Bram Moolenaar08928322020-01-04 14:32:48 +01003057 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003058 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3059 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003060 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3061 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3062 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3063 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3064 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003065
glepnir0fe17f82024-10-08 22:26:44 +02003066 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003067 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003068
3069 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003070 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003071
Bram Moolenaard61efa52022-07-23 09:52:04 +01003072 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3073 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3074 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003075 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003076 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3077 dup = dict_get_number(tv->vval.v_dict, "dup");
3078 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3079 empty = dict_get_number(tv->vval.v_dict, "empty");
3080 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3081 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003082 flags |= CP_EQUAL;
3083 }
3084 else
3085 {
3086 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003087 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003088 }
3089 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003090 {
3091 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003092 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003093 }
glepnir508e7852024-07-25 21:39:08 +02003094 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01003095 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003096 if (status != OK)
3097 clear_tv(&user_data);
3098 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003099}
3100
3101/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003102 * Add completions from a list.
3103 */
3104 static void
3105ins_compl_add_list(list_T *list)
3106{
3107 listitem_T *li;
3108 int dir = compl_direction;
3109
3110 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003111 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003112 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003113 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003114 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003115 // if dir was BACKWARD then honor it just once
3116 dir = FORWARD;
3117 else if (did_emsg)
3118 break;
3119 }
3120}
3121
3122/*
3123 * Add completions from a dict.
3124 */
3125 static void
3126ins_compl_add_dict(dict_T *dict)
3127{
3128 dictitem_T *di_refresh;
3129 dictitem_T *di_words;
3130
3131 // Check for optional "refresh" item.
3132 compl_opt_refresh_always = FALSE;
3133 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3134 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3135 {
3136 char_u *v = di_refresh->di_tv.vval.v_string;
3137
3138 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3139 compl_opt_refresh_always = TRUE;
3140 }
3141
3142 // Add completions from a "words" list.
3143 di_words = dict_find(dict, (char_u *)"words", 5);
3144 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3145 ins_compl_add_list(di_words->di_tv.vval.v_list);
3146}
3147
3148/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003149 * Start completion for the complete() function.
3150 * "startcol" is where the matched text starts (1 is first column).
3151 * "list" is the list of matches.
3152 */
3153 static void
3154set_completion(colnr_T startcol, list_T *list)
3155{
3156 int save_w_wrow = curwin->w_wrow;
3157 int save_w_leftcol = curwin->w_leftcol;
3158 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003159 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003160 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3161 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3162 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003163
3164 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003165 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003166 ins_compl_prep(' ');
3167 ins_compl_clear();
3168 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003169 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003170
3171 compl_direction = FORWARD;
3172 if (startcol > curwin->w_cursor.col)
3173 startcol = curwin->w_cursor.col;
3174 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003175 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003176 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3177 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003178 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3179 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003180 if (p_ic)
3181 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003182 if (compl_orig_text.string == NULL)
3183 {
3184 compl_orig_text.length = 0;
3185 return;
3186 }
3187 compl_orig_text.length = (size_t)compl_length;
3188 if (ins_compl_add(compl_orig_text.string,
3189 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3190 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003191 return;
3192
3193 ctrl_x_mode = CTRL_X_EVAL;
3194
3195 ins_compl_add_list(list);
3196 compl_matches = ins_compl_make_cyclic();
3197 compl_started = TRUE;
3198 compl_used_match = TRUE;
3199 compl_cont_status = 0;
3200
3201 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003202 int no_select = compl_no_select || compl_longest;
3203 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003204 {
3205 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003206 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003207 // Down/Up has no real effect.
3208 ins_complete(K_UP, FALSE);
3209 }
3210 else
3211 ins_complete(Ctrl_N, FALSE);
3212 compl_enter_selects = compl_no_insert;
3213
3214 // Lazily show the popup menu, unless we got interrupted.
3215 if (!compl_interrupted)
3216 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003217 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003218 out_flush();
3219}
3220
3221/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003222 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003223 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003224 void
3225f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003226{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003227 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003228
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003229 if (in_vim9script()
3230 && (check_for_number_arg(argvars, 0) == FAIL
3231 || check_for_list_arg(argvars, 1) == FAIL))
3232 return;
3233
Bram Moolenaar24959102022-05-07 20:01:16 +01003234 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003235 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003236 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003237 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003238 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003239
3240 // Check for undo allowed here, because if something was already inserted
3241 // the line was already saved for undo and this check isn't done.
3242 if (!undo_allowed())
3243 return;
3244
Bram Moolenaard83392a2022-09-01 12:22:46 +01003245 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003246 {
3247 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3248 if (startcol > 0)
3249 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003250 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003251}
3252
3253/*
3254 * "complete_add()" function
3255 */
3256 void
3257f_complete_add(typval_T *argvars, typval_T *rettv)
3258{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003259 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003260 return;
3261
Bram Moolenaar440cf092021-04-03 20:13:30 +02003262 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003263}
3264
3265/*
3266 * "complete_check()" function
3267 */
3268 void
3269f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3270{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003271 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003272 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003273
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003274 ins_compl_check_keys(0, TRUE);
3275 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003276
3277 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003278}
3279
3280/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003281 * Return Insert completion mode name string
3282 */
3283 static char_u *
3284ins_compl_mode(void)
3285{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003286 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003287 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3288
3289 return (char_u *)"";
3290}
3291
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003292/*
3293 * Assign the sequence number to all the completion matches which don't have
3294 * one assigned yet.
3295 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003296 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003297ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003298{
3299 int number = 0;
3300 compl_T *match;
3301
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003302 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003303 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003304 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003305 // This should normally succeed already at the first loop
3306 // cycle, so it's fast!
3307 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003308 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003309 if (match->cp_number != -1)
3310 {
3311 number = match->cp_number;
3312 break;
3313 }
3314 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003315 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003316 for (match = match->cp_next;
3317 match != NULL && match->cp_number == -1;
3318 match = match->cp_next)
3319 match->cp_number = ++number;
3320 }
3321 else // BACKWARD
3322 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003323 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003324 // number. This should normally succeed already at the
3325 // first loop cycle, so it's fast!
3326 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003327 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003328 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003329 if (match->cp_number != -1)
3330 {
3331 number = match->cp_number;
3332 break;
3333 }
glepnir40891ba2025-02-10 22:18:00 +01003334 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003335 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003336 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003337 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003338 for (match = match->cp_prev; match
3339 && match->cp_number == -1;
3340 match = match->cp_prev)
3341 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003342 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003343 }
3344}
3345
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003346/*
glepnir037b0282025-01-16 14:37:44 +01003347 * Fill the dict of complete_info
3348 */
3349 static void
3350fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3351{
3352 dict_add_string(di, "word", match->cp_str.string);
3353 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3354 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3355 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3356 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3357 if (add_match)
3358 dict_add_bool(di, "match", match->cp_in_match_array);
3359 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3360 // Add an empty string for backwards compatibility
3361 dict_add_string(di, "user_data", (char_u *)"");
3362 else
3363 dict_add_tv(di, "user_data", &match->cp_user_data);
3364}
3365
3366/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003367 * Get complete information
3368 */
3369 static void
3370get_complete_info(list_T *what_list, dict_T *retdict)
3371{
3372 int ret = OK;
3373 listitem_T *item;
3374#define CI_WHAT_MODE 0x01
3375#define CI_WHAT_PUM_VISIBLE 0x02
3376#define CI_WHAT_ITEMS 0x04
3377#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003378#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003379#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003380#define CI_WHAT_ALL 0xff
3381 int what_flag;
3382
3383 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003384 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003385 else
3386 {
3387 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003388 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003389 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003390 {
3391 char_u *what = tv_get_string(&item->li_tv);
3392
3393 if (STRCMP(what, "mode") == 0)
3394 what_flag |= CI_WHAT_MODE;
3395 else if (STRCMP(what, "pum_visible") == 0)
3396 what_flag |= CI_WHAT_PUM_VISIBLE;
3397 else if (STRCMP(what, "items") == 0)
3398 what_flag |= CI_WHAT_ITEMS;
3399 else if (STRCMP(what, "selected") == 0)
3400 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003401 else if (STRCMP(what, "completed") == 0)
3402 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003403 else if (STRCMP(what, "matches") == 0)
3404 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003405 }
3406 }
3407
3408 if (ret == OK && (what_flag & CI_WHAT_MODE))
3409 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3410
3411 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3412 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3413
glepnir037b0282025-01-16 14:37:44 +01003414 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3415 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003416 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003417 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003418 dict_T *di;
3419 compl_T *match;
3420 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003421 int has_items = what_flag & CI_WHAT_ITEMS;
3422 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003423 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003424
glepnird4088ed2024-12-31 10:55:22 +01003425 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003426 {
3427 li = list_alloc();
3428 if (li == NULL)
3429 return;
glepnird4088ed2024-12-31 10:55:22 +01003430 ret = dict_add_list(retdict, (has_matches && !has_items)
3431 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003432 }
3433 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3434 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3435 ins_compl_update_sequence_numbers();
3436 if (ret == OK && compl_first_match != NULL)
3437 {
3438 int list_idx = 0;
3439 match = compl_first_match;
3440 do
3441 {
3442 if (!match_at_original_text(match))
3443 {
glepnird4088ed2024-12-31 10:55:22 +01003444 if (has_items
3445 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003446 {
3447 di = dict_alloc();
3448 if (di == NULL)
3449 return;
3450 ret = list_append_dict(li, di);
3451 if (ret != OK)
3452 return;
glepnir037b0282025-01-16 14:37:44 +01003453 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003454 }
glepnird4088ed2024-12-31 10:55:22 +01003455 if (compl_curr_match != NULL
3456 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003457 selected_idx = list_idx;
3458 list_idx += 1;
3459 }
3460 match = match->cp_next;
3461 }
3462 while (match != NULL && !is_first_match(match));
3463 }
3464 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3465 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003466
glepnir037b0282025-01-16 14:37:44 +01003467 if (ret == OK && selected_idx != -1 && has_completed)
3468 {
3469 di = dict_alloc();
3470 if (di == NULL)
3471 return;
3472 fill_complete_info_dict(di, compl_curr_match, FALSE);
3473 ret = dict_add_dict(retdict, "completed", di);
3474 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003475 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003476}
3477
3478/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003479 * "complete_info()" function
3480 */
3481 void
3482f_complete_info(typval_T *argvars, typval_T *rettv)
3483{
3484 list_T *what_list = NULL;
3485
Bram Moolenaar93a10962022-06-16 11:42:09 +01003486 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003487 return;
3488
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003489 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3490 return;
3491
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003492 if (argvars[0].v_type != VAR_UNKNOWN)
3493 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003494 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003495 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003496 what_list = argvars[0].vval.v_list;
3497 }
3498 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003499}
3500#endif
3501
3502/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003503 * Returns TRUE when using a user-defined function for thesaurus completion.
3504 */
3505 static int
3506thesaurus_func_complete(int type UNUSED)
3507{
3508#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003509 return type == CTRL_X_THESAURUS
3510 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003511#else
3512 return FALSE;
3513#endif
3514}
3515
3516/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003517 * Return value of process_next_cpt_value()
3518 */
3519enum
3520{
3521 INS_COMPL_CPT_OK = 1,
3522 INS_COMPL_CPT_CONT,
3523 INS_COMPL_CPT_END
3524};
3525
3526/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003527 * state information used for getting the next set of insert completion
3528 * matches.
3529 */
3530typedef struct
3531{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003532 char_u *e_cpt_copy; // copy of 'complete'
3533 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003534 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003535 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003536 pos_T prev_match_pos; // previous match position
3537 int set_match_pos; // save first_match_pos/last_match_pos
3538 pos_T first_match_pos; // first match position
3539 pos_T last_match_pos; // last match position
3540 int found_all; // found all matches of a certain type.
3541 char_u *dict; // dictionary file to search
3542 int dict_f; // "dict" is an exact file name or not
3543} ins_compl_next_state_T;
3544
3545/*
3546 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003547 *
3548 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003549 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003550 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003551 * st->found_all - all matches of this type are found
3552 * st->ins_buf - search for completions in this buffer
3553 * st->first_match_pos - position of the first completion match
3554 * st->last_match_pos - position of the last completion match
3555 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003556 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003557 * st->dict - name of the dictionary or thesaurus file to search
3558 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003559 *
3560 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003561 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3562 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003563 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003564 */
3565 static int
3566process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003567 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003568 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003569 pos_T *start_match_pos,
3570 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003571{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003572 int compl_type = -1;
3573 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003574
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003575 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003576
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003577 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3578 st->e_cpt++;
3579
3580 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003581 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003582 st->ins_buf = curbuf;
3583 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003584 // Move the cursor back one character so that ^N can match the
3585 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003586 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003587 {
3588 // Move the cursor to after the last character in the
3589 // buffer, so that word at start of buffer is found
3590 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003591 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003592 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003593 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003594 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003595 compl_type = 0;
3596
3597 // Remember the first match so that the loop stops when we
3598 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003599 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003600 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003601 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003602 && (st->ins_buf = ins_compl_next_buf(
3603 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003604 {
3605 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003606 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003607 {
3608 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003609 st->first_match_pos.col = st->last_match_pos.col = 0;
3610 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3611 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003612 compl_type = 0;
3613 }
3614 else // unloaded buffer, scan like dictionary
3615 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003616 st->found_all = TRUE;
3617 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003618 {
3619 status = INS_COMPL_CPT_CONT;
3620 goto done;
3621 }
3622 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003623 st->dict = st->ins_buf->b_fname;
3624 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003625 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003626 if (!shortmess(SHM_COMPLETIONSCAN))
3627 {
3628 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3629 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3630 st->ins_buf->b_fname == NULL
3631 ? buf_spname(st->ins_buf)
3632 : st->ins_buf->b_sfname == NULL
3633 ? st->ins_buf->b_fname
3634 : st->ins_buf->b_sfname);
3635 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3636 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003637 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003638 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003639 status = INS_COMPL_CPT_END;
3640 else
3641 {
3642 if (ctrl_x_mode_line_or_eval())
3643 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003644 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003645 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003646 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003647 compl_type = CTRL_X_DICTIONARY;
3648 else
3649 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003650 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003651 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003652 st->dict = st->e_cpt;
3653 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003654 }
3655 }
3656#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003657 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003658 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003659 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003660 compl_type = CTRL_X_PATH_DEFINES;
3661#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003662 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003663 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003664 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003665 if (!shortmess(SHM_COMPLETIONSCAN))
3666 {
3667 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3668 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3669 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3670 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003671 }
3672 else
3673 compl_type = -1;
3674
3675 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003676 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003677
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003678 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003679 if (compl_type == -1)
3680 status = INS_COMPL_CPT_CONT;
3681 }
3682
3683done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003684 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003685 return status;
3686}
3687
3688#ifdef FEAT_FIND_ID
3689/*
3690 * Get the next set of identifiers or defines matching "compl_pattern" in
3691 * included files.
3692 */
3693 static void
3694get_next_include_file_completion(int compl_type)
3695{
John Marriott5e6ea922024-11-23 14:01:57 +01003696 find_pattern_in_path(compl_pattern.string, compl_direction,
3697 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003698 (compl_type == CTRL_X_PATH_DEFINES
3699 && !(compl_cont_status & CONT_SOL))
3700 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003701 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003702}
3703#endif
3704
3705/*
3706 * Get the next set of words matching "compl_pattern" in dictionary or
3707 * thesaurus files.
3708 */
3709 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003710get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003711{
3712#ifdef FEAT_COMPL_FUNC
3713 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003714 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003715 else
3716#endif
3717 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003718 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003719 : (compl_type == CTRL_X_THESAURUS
3720 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3721 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003722 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003723 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003724 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003725}
3726
3727/*
3728 * Get the next set of tag names matching "compl_pattern".
3729 */
3730 static void
3731get_next_tag_completion(void)
3732{
3733 int save_p_ic;
3734 char_u **matches;
3735 int num_matches;
3736
3737 // set p_ic according to p_ic, p_scs and pat for find_tags().
3738 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003739 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003740
3741 // Find up to TAG_MANY matches. Avoids that an enormous number
3742 // of matches is found when compl_pattern is empty
3743 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003744 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003745 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003746 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003747 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3748 ins_compl_add_matches(num_matches, matches, p_ic);
3749 g_tag_at_cursor = FALSE;
3750 p_ic = save_p_ic;
3751}
3752
3753/*
glepnir8159fb12024-07-17 20:32:54 +02003754 * Compare function for qsort
3755 */
3756static int compare_scores(const void *a, const void *b)
3757{
3758 int idx_a = *(const int *)a;
3759 int idx_b = *(const int *)b;
3760 int score_a = compl_fuzzy_scores[idx_a];
3761 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003762 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3763 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003764}
3765
3766/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003767 * Get the next set of filename matching "compl_pattern".
3768 */
3769 static void
3770get_next_filename_completion(void)
3771{
3772 char_u **matches;
3773 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003774 char_u *ptr;
3775 garray_T fuzzy_indices;
3776 int i;
3777 int score;
3778 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003779 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003780 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3781 char_u **sorted_matches;
3782 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003783 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003784
glepnirb9de1a02024-08-02 19:14:38 +02003785#ifdef BACKSLASH_IN_FILENAME
3786 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3787 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3788#else
3789 char pathsep = PATHSEP;
3790#endif
3791
glepnir8159fb12024-07-17 20:32:54 +02003792 if (in_fuzzy)
3793 {
glepnirb9de1a02024-08-02 19:14:38 +02003794#ifdef BACKSLASH_IN_FILENAME
3795 if (curbuf->b_p_csl[0] == 's')
3796 {
John Marriott5e6ea922024-11-23 14:01:57 +01003797 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003798 {
3799 if (leader[i] == '\\')
3800 leader[i] = '/';
3801 }
3802 }
3803 else if (curbuf->b_p_csl[0] == 'b')
3804 {
John Marriott5e6ea922024-11-23 14:01:57 +01003805 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003806 {
3807 if (leader[i] == '/')
3808 leader[i] = '\\';
3809 }
3810 }
3811#endif
3812 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003813 if (last_sep == NULL)
3814 {
3815 // No path separator or separator is the last character,
3816 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003817 VIM_CLEAR_STRING(compl_pattern);
3818 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3819 if (compl_pattern.string == NULL)
3820 return;
3821 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003822 }
3823 else if (*(last_sep + 1) == '\0')
3824 in_fuzzy = FALSE;
3825 else
3826 {
3827 // Split leader into path and file parts
3828 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003829 char_u *path_with_wildcard;
3830
3831 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003832 if (path_with_wildcard != NULL)
3833 {
John Marriott5e6ea922024-11-23 14:01:57 +01003834 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3835 VIM_CLEAR_STRING(compl_pattern);
3836 compl_pattern.string = path_with_wildcard;
3837 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003838
3839 // Move leader to the file part
3840 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003841 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003842 }
3843 }
glepnir8159fb12024-07-17 20:32:54 +02003844 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003845
John Marriott5e6ea922024-11-23 14:01:57 +01003846 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003847 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3848 return;
3849
3850 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003851 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003852#ifdef BACKSLASH_IN_FILENAME
3853 if (curbuf->b_p_csl[0] != NUL)
3854 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003855 for (i = 0; i < num_matches; ++i)
3856 {
glepnir8159fb12024-07-17 20:32:54 +02003857 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003858 while (*ptr != NUL)
3859 {
3860 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3861 *ptr = '/';
3862 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3863 *ptr = '\\';
3864 ptr += (*mb_ptr2len)(ptr);
3865 }
3866 }
3867 }
3868#endif
glepnir8159fb12024-07-17 20:32:54 +02003869
3870 if (in_fuzzy)
3871 {
3872 ga_init2(&fuzzy_indices, sizeof(int), 10);
3873 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3874
3875 for (i = 0; i < num_matches; i++)
3876 {
3877 ptr = matches[i];
3878 score = fuzzy_match_str(ptr, leader);
3879 if (score > 0)
3880 {
3881 if (ga_grow(&fuzzy_indices, 1) == OK)
3882 {
3883 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3884 compl_fuzzy_scores[i] = score;
3885 fuzzy_indices.ga_len++;
3886 }
3887 }
3888 }
3889
Christian Brabandt220474d2024-07-20 13:26:44 +02003890 // prevent qsort from deref NULL pointer
3891 if (fuzzy_indices.ga_len > 0)
3892 {
3893 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3894 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003895
Christian Brabandt220474d2024-07-20 13:26:44 +02003896 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3897 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3898 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003899
Christian Brabandt220474d2024-07-20 13:26:44 +02003900 FreeWild(num_matches, matches);
3901 matches = sorted_matches;
3902 num_matches = fuzzy_indices.ga_len;
3903 }
glepnir6b6280c2024-07-27 16:25:45 +02003904 else if (leader_len > 0)
3905 {
3906 FreeWild(num_matches, matches);
3907 num_matches = 0;
3908 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003909
glepnir8159fb12024-07-17 20:32:54 +02003910 vim_free(compl_fuzzy_scores);
3911 ga_clear(&fuzzy_indices);
3912 }
3913
glepnir6b6280c2024-07-27 16:25:45 +02003914 if (num_matches > 0)
3915 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003916}
3917
3918/*
3919 * Get the next set of command-line completions matching "compl_pattern".
3920 */
3921 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003922get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003923{
3924 char_u **matches;
3925 int num_matches;
3926
John Marriott5e6ea922024-11-23 14:01:57 +01003927 if (expand_cmdline(&compl_xp, compl_pattern.string,
3928 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003929 ins_compl_add_matches(num_matches, matches, FALSE);
3930}
3931
3932/*
3933 * Get the next set of spell suggestions matching "compl_pattern".
3934 */
3935 static void
3936get_next_spell_completion(linenr_T lnum UNUSED)
3937{
3938#ifdef FEAT_SPELL
3939 char_u **matches;
3940 int num_matches;
3941
John Marriott5e6ea922024-11-23 14:01:57 +01003942 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003943 if (num_matches > 0)
3944 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003945 else
3946 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003947#endif
3948}
3949
3950/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003951 * Return the next word or line from buffer "ins_buf" at position
3952 * "cur_match_pos" for completion. The length of the match is set in "len".
3953 */
3954 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003955ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003956 buf_T *ins_buf, // buffer being scanned
3957 pos_T *cur_match_pos, // current match position
3958 int *match_len,
3959 int *cont_s_ipos) // next ^X<> will set initial_pos
3960{
3961 char_u *ptr;
3962 int len;
3963
3964 *match_len = 0;
3965 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3966 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003967 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003968 if (ctrl_x_mode_line_or_eval())
3969 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003970 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003971 {
3972 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3973 return NULL;
3974 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003975 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003976 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003977 {
3978 char_u *tmp_ptr = ptr;
3979
3980 ptr = skipwhite(tmp_ptr);
3981 len -= (int)(ptr - tmp_ptr);
3982 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003983 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003984 }
3985 else
3986 {
3987 char_u *tmp_ptr = ptr;
3988
John Marriott5e6ea922024-11-23 14:01:57 +01003989 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003990 {
3991 tmp_ptr += compl_length;
3992 // Skip if already inside a word.
3993 if (vim_iswordp(tmp_ptr))
3994 return NULL;
3995 // Find start of next word.
3996 tmp_ptr = find_word_start(tmp_ptr);
3997 }
3998 // Find end of this word.
3999 tmp_ptr = find_word_end(tmp_ptr);
4000 len = (int)(tmp_ptr - ptr);
4001
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004002 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004003 {
4004 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4005 {
4006 // Try next line, if any. the new word will be
4007 // "join" as if the normal command "J" was used.
4008 // IOSIZE is always greater than
4009 // compl_length, so the next STRNCPY always
4010 // works -- Acevedo
4011 STRNCPY(IObuff, ptr, len);
4012 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4013 tmp_ptr = ptr = skipwhite(ptr);
4014 // Find start of next word.
4015 tmp_ptr = find_word_start(tmp_ptr);
4016 // Find end of next word.
4017 tmp_ptr = find_word_end(tmp_ptr);
4018 if (tmp_ptr > ptr)
4019 {
4020 if (*ptr != ')' && IObuff[len - 1] != TAB)
4021 {
4022 if (IObuff[len - 1] != ' ')
4023 IObuff[len++] = ' ';
4024 // IObuf =~ "\k.* ", thus len >= 2
4025 if (p_js
4026 && (IObuff[len - 2] == '.'
4027 || (vim_strchr(p_cpo, CPO_JOINSP)
4028 == NULL
4029 && (IObuff[len - 2] == '?'
4030 || IObuff[len - 2] == '!'))))
4031 IObuff[len++] = ' ';
4032 }
4033 // copy as much as possible of the new word
4034 if (tmp_ptr - ptr >= IOSIZE - len)
4035 tmp_ptr = ptr + IOSIZE - len - 1;
4036 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4037 len += (int)(tmp_ptr - ptr);
4038 *cont_s_ipos = TRUE;
4039 }
4040 IObuff[len] = NUL;
4041 ptr = IObuff;
4042 }
4043 if (len == compl_length)
4044 return NULL;
4045 }
4046 }
4047
4048 *match_len = len;
4049 return ptr;
4050}
4051
4052/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004053 * Get the next set of words matching "compl_pattern" for default completion(s)
4054 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004055 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4056 * position "st->start_pos" in the "compl_direction" direction. If
4057 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4058 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004059 * Returns OK if a new next match is found, otherwise returns FAIL.
4060 */
4061 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004062get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004063{
4064 int found_new_match = FAIL;
4065 int save_p_scs;
4066 int save_p_ws;
4067 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004068 char_u *ptr = NULL;
4069 int len = 0;
4070 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
4071 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004072
4073 // If 'infercase' is set, don't use 'smartcase' here
4074 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004075 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004076 p_scs = FALSE;
4077
4078 // Buffers other than curbuf are scanned from the beginning or the
4079 // end but never from the middle, thus setting nowrapscan in this
4080 // buffer is a good idea, on the other hand, we always set
4081 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4082 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004083 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004084 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004085 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004086 p_ws = TRUE;
4087 looped_around = FALSE;
4088 for (;;)
4089 {
4090 int cont_s_ipos = FALSE;
4091
4092 ++msg_silent; // Don't want messages for wrapscan.
4093
4094 // ctrl_x_mode_line_or_eval() || word-wise search that
4095 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02004096 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004097 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01004098 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02004099 else if (in_fuzzy)
4100 found_new_match = search_for_fuzzy_match(st->ins_buf,
4101 st->cur_match_pos, leader, compl_direction,
4102 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004103 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004104 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004105 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004106 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004107 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004108 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004109 {
4110 // set "compl_started" even on fail
4111 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004112 st->first_match_pos = *st->cur_match_pos;
4113 st->last_match_pos = *st->cur_match_pos;
4114 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004115 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004116 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4117 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004118 {
4119 found_new_match = FAIL;
4120 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004121 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004122 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4123 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4124 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004125 {
4126 if (looped_around)
4127 found_new_match = FAIL;
4128 else
4129 looped_around = TRUE;
4130 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004131 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004132 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4133 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4134 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004135 {
4136 if (looped_around)
4137 found_new_match = FAIL;
4138 else
4139 looped_around = TRUE;
4140 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004141 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004142 if (found_new_match == FAIL)
4143 break;
4144
4145 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004146 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004147 && start_pos->lnum == st->cur_match_pos->lnum
4148 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004149 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004150
glepnir8159fb12024-07-17 20:32:54 +02004151 if (!in_fuzzy)
4152 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4153 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004154 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004155 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004156
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004157 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004158 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004159 0, cont_s_ipos) != NOTDONE)
4160 {
4161 found_new_match = OK;
4162 break;
4163 }
4164 }
4165 p_scs = save_p_scs;
4166 p_ws = save_p_ws;
4167
4168 return found_new_match;
4169}
4170
4171/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004172 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004173 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004174 */
4175 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004176get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004177{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004178 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004179
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004180 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004181 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004182 case -1:
4183 break;
4184#ifdef FEAT_FIND_ID
4185 case CTRL_X_PATH_PATTERNS:
4186 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004187 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004188 break;
4189#endif
4190
4191 case CTRL_X_DICTIONARY:
4192 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004193 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4194 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004195 break;
4196
4197 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004198 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004199 break;
4200
4201 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004202 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004203 break;
4204
4205 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004206 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004207 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004208 break;
4209
4210#ifdef FEAT_COMPL_FUNC
4211 case CTRL_X_FUNCTION:
4212 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004213 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004214 break;
4215#endif
4216
4217 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004218 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004219 break;
4220
4221 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004222 found_new_match = get_next_default_completion(st, ini);
4223 if (found_new_match == FAIL && st->ins_buf == curbuf)
4224 st->found_all = TRUE;
4225 }
4226
4227 // check if compl_curr_match has changed, (e.g. other type of
4228 // expansion added something)
4229 if (type != 0 && compl_curr_match != compl_old_match)
4230 found_new_match = OK;
4231
4232 return found_new_match;
4233}
4234
4235/*
4236 * Get the next expansion(s), using "compl_pattern".
4237 * The search starts at position "ini" in curbuf and in the direction
4238 * compl_direction.
4239 * When "compl_started" is FALSE start at that position, otherwise continue
4240 * where we stopped searching before.
4241 * This may return before finding all the matches.
4242 * Return the total number of matches or -1 if still unknown -- Acevedo
4243 */
4244 static int
4245ins_compl_get_exp(pos_T *ini)
4246{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004247 static ins_compl_next_state_T st;
4248 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004249 int i;
4250 int found_new_match;
4251 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004252 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004253
4254 if (!compl_started)
4255 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004256 buf_T *buf;
4257
4258 FOR_ALL_BUFFERS(buf)
4259 buf->b_scanned = 0;
4260 if (!st_cleared)
4261 {
4262 CLEAR_FIELD(st);
4263 st_cleared = TRUE;
4264 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004265 st.found_all = FALSE;
4266 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004267 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004268 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004269 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4270 ? (char_u *)"." : curbuf->b_p_cpt);
4271 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004272 st.last_match_pos = st.first_match_pos = *ini;
4273 }
4274 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4275 st.ins_buf = curbuf; // In case the buffer was wiped out.
4276
4277 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004278 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004279 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004280
4281 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4282 for (;;)
4283 {
4284 found_new_match = FAIL;
4285 st.set_match_pos = FALSE;
4286
4287 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4288 // or if found_all says this entry is done. For ^X^L only use the
4289 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004290 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004291 && (!compl_started || st.found_all))
4292 {
glepnir8159fb12024-07-17 20:32:54 +02004293 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004294
4295 if (status == INS_COMPL_CPT_END)
4296 break;
4297 if (status == INS_COMPL_CPT_CONT)
4298 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004299 }
4300
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004301 // If complete() was called then compl_pattern has been reset. The
4302 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004303 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004304 break;
4305
4306 // get the next set of completion matches
4307 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004308
4309 // break the loop for specialized modes (use 'complete' just for the
4310 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4311 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004312 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4313 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004314 {
4315 if (got_int)
4316 break;
4317 // Fill the popup menu as soon as possible.
4318 if (type != -1)
4319 ins_compl_check_keys(0, FALSE);
4320
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004321 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004322 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4323 break;
4324 compl_started = TRUE;
4325 }
4326 else
4327 {
4328 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004329 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004330 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004331
4332 compl_started = FALSE;
4333 }
4334 }
4335 compl_started = TRUE;
4336
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004337 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004338 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004339 found_new_match = FAIL;
4340
4341 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004342 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004343 && !ctrl_x_mode_line_or_eval()))
4344 i = ins_compl_make_cyclic();
4345
4346 if (compl_old_match != NULL)
4347 {
4348 // If several matches were added (FORWARD) or the search failed and has
4349 // just been made cyclic then we have to move compl_curr_match to the
4350 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004351 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004352 : compl_old_match->cp_prev;
4353 if (compl_curr_match == NULL)
4354 compl_curr_match = compl_old_match;
4355 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004356 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004357
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004358 return i;
4359}
4360
4361/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004362 * Update "compl_shown_match" to the actually shown match, it may differ when
4363 * "compl_leader" is used to omit some of the matches.
4364 */
4365 static void
4366ins_compl_update_shown_match(void)
4367{
4368 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004369 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004370 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004371 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004372 compl_shown_match = compl_shown_match->cp_next;
4373
4374 // If we didn't find it searching forward, and compl_shows_dir is
4375 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004376 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004377 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004378 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004379 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004380 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004381 {
4382 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004383 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004384 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004385 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004386 compl_shown_match = compl_shown_match->cp_prev;
4387 }
4388}
4389
4390/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004391 * Delete the old text being completed.
4392 */
4393 void
4394ins_compl_delete(void)
4395{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004396 // In insert mode: Delete the typed part.
4397 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004398 int col = compl_col + (compl_status_adding() ? compl_length : 0);
glepnir76bdb822025-02-08 19:04:51 +01004399 char_u *remaining = NULL;
4400 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004401 int has_preinsert = ins_compl_preinsert_effect();
4402 if (has_preinsert)
4403 {
glepnirbfb4eea2025-01-31 15:28:29 +01004404 col += ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004405 curwin->w_cursor.col = compl_ins_end_col;
4406 }
4407
glepnir76bdb822025-02-08 19:04:51 +01004408 if (curwin->w_cursor.lnum > compl_lnum)
4409 {
4410 if (curwin->w_cursor.col < ml_get_curline_len())
4411 {
4412 char_u *line = ml_get_curline();
4413 remaining = vim_strnsave(line + curwin->w_cursor.col,
4414 (size_t)STRLEN(line + curwin->w_cursor.col));
4415 if (remaining == NULL)
4416 return;
4417 }
4418 while (curwin->w_cursor.lnum > compl_lnum)
4419 {
4420 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4421 {
4422 if (remaining)
4423 VIM_CLEAR(remaining);
4424 return;
4425 }
4426 curwin->w_cursor.lnum--;
4427 }
4428 // move cursor to end of line
4429 curwin->w_cursor.col = ml_get_curline_len();
4430 }
4431
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004432 if ((int)curwin->w_cursor.col > col)
4433 {
4434 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004435 {
4436 if (remaining)
4437 VIM_CLEAR(remaining);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004438 return;
glepnire3647c82025-02-10 21:16:32 +01004439 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004440 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004441 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004442 }
4443
glepnir76bdb822025-02-08 19:04:51 +01004444 if (remaining != NULL)
4445 {
4446 orig_col = curwin->w_cursor.col;
4447 ins_str(remaining);
4448 curwin->w_cursor.col = orig_col;
4449 vim_free(remaining);
4450 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004451 // TODO: is this sufficient for redrawing? Redrawing everything causes
4452 // flicker, thus we can't do that.
4453 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004454#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004455 // clear v:completed_item
4456 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004457#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004458}
4459
4460/*
glepnir76bdb822025-02-08 19:04:51 +01004461 * Insert a completion string that contains newlines.
4462 * The string is split and inserted line by line.
4463 */
4464 static void
4465ins_compl_expand_multiple(char_u *str)
4466{
4467 char_u *start = str;
4468 char_u *curr = str;
4469
4470 while (*curr != NUL)
4471 {
4472 if (*curr == '\n')
4473 {
4474 // Insert the text chunk before newline
4475 if (curr > start)
4476 ins_char_bytes(start, (int)(curr - start));
4477
4478 // Handle newline
4479 open_line(FORWARD, OPENLINE_KEEPTRAIL, FALSE, NULL);
4480 start = curr + 1;
4481 }
4482 curr++;
4483 }
4484
4485 // Handle remaining text after last newline (if any)
4486 if (curr > start)
4487 ins_char_bytes(start, (int)(curr - start));
4488
4489 compl_ins_end_col = curwin->w_cursor.col;
4490}
4491
4492/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004493 * Insert the new text being completed.
4494 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004495 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4496 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004497 */
4498 void
glepniredd4ac32025-01-29 18:53:51 +01004499ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004500{
glepnir76bdb822025-02-08 19:04:51 +01004501 int compl_len = get_compl_len();
4502 int preinsert = ins_compl_has_preinsert();
4503 char_u *cp_str = compl_shown_match->cp_str.string;
4504 size_t cp_str_len = compl_shown_match->cp_str.length;
4505 size_t leader_len = ins_compl_leader_len();
4506 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004507
4508 // Make sure we don't go over the end of the string, this can happen with
4509 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004510 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004511 {
glepnir76bdb822025-02-08 19:04:51 +01004512 if (has_multiple)
4513 ins_compl_expand_multiple(cp_str + compl_len);
4514 else
4515 {
4516 ins_compl_insert_bytes(cp_str + compl_len, -1);
4517 if (preinsert && move_cursor)
4518 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4519 }
glepniredd4ac32025-01-29 18:53:51 +01004520 }
4521 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004522 compl_used_match = FALSE;
4523 else
4524 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004525#ifdef FEAT_EVAL
4526 {
4527 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4528
4529 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4530 }
4531#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004532 if (!in_compl_func)
4533 compl_curr_match = compl_shown_match;
4534}
4535
4536/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004537 * show the file name for the completion match (if any). Truncate the file
4538 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004539 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004540 static void
4541ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004542{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004543 char *lead = _("match in file");
4544 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4545 char_u *s;
4546 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004547
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004548 if (space <= 0)
4549 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004550
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004551 // We need the tail that fits. With double-byte encoding going
4552 // back from the end is very slow, thus go from the start and keep
4553 // the text that fits in "space" between "s" and "e".
4554 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004555 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004556 space -= ptr2cells(e);
4557 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004558 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004559 space += ptr2cells(s);
4560 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004561 }
4562 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004563 msg_hist_off = TRUE;
4564 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4565 s > compl_shown_match->cp_fname ? "<" : "", s);
4566 msg((char *)IObuff);
4567 msg_hist_off = FALSE;
4568 redraw_cmdline = FALSE; // don't overwrite!
4569}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004570
glepnirdca57fb2024-06-04 22:01:21 +02004571/*
zeertzjq551d8c32024-06-05 19:53:32 +02004572 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004573 */
glepnira218cc62024-06-03 19:32:39 +02004574 static compl_T *
4575find_comp_when_fuzzy(void)
4576{
4577 int score;
4578 char_u* str;
4579 int target_idx = -1;
4580 int is_forward = compl_shows_dir_forward();
4581 int is_backward = compl_shows_dir_backward();
4582 compl_T *comp = NULL;
4583
glepnir43eef882024-06-19 20:20:48 +02004584 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004585 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004586 return compl_first_match != compl_shown_match ? compl_first_match :
4587 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004588
4589 if (is_forward)
4590 target_idx = compl_selected_item + 1;
4591 else if (is_backward)
4592 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004593 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004594
4595 score = compl_match_array[target_idx].pum_score;
4596 str = compl_match_array[target_idx].pum_text;
4597
4598 comp = compl_first_match;
4599 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004600 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004601 return comp;
4602 comp = comp->cp_next;
4603 } while (comp != NULL && !is_first_match(comp));
4604
4605 return NULL;
4606}
4607
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004608/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004609 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004610 * times. The number of matches found is returned in 'num_matches'.
4611 *
4612 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4613 * get more completions. If it is FALSE, then do nothing when there are no more
4614 * completions in the given direction.
4615 *
4616 * If "advance" is TRUE, then completion will move to the first match.
4617 * Otherwise, the original text will be shown.
4618 *
4619 * Returns OK on success and -1 if the number of matches are unknown.
4620 */
4621 static int
4622find_next_completion_match(
4623 int allow_get_expansion,
4624 int todo, // repeat completion this many times
4625 int advance,
4626 int *num_matches)
4627{
4628 int found_end = FALSE;
4629 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004630 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004631 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4632 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004633
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004634 while (--todo >= 0)
4635 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004636 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004637 {
glepniraced8c22024-06-15 15:13:05 +02004638 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4639 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004640 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004641 && (is_first_match(compl_shown_match->cp_next)
4642 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004643 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004644 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004645 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004646 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004647 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004648 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4649 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004650 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004651 }
4652 else
4653 {
4654 if (!allow_get_expansion)
4655 {
4656 if (advance)
4657 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004658 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004659 compl_pending -= todo + 1;
4660 else
4661 compl_pending += todo + 1;
4662 }
4663 return -1;
4664 }
4665
4666 if (!compl_no_select && advance)
4667 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004668 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004669 --compl_pending;
4670 else
4671 ++compl_pending;
4672 }
4673
4674 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004675 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004676
4677 // handle any pending completions
4678 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004679 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004680 {
4681 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4682 {
4683 compl_shown_match = compl_shown_match->cp_next;
4684 --compl_pending;
4685 }
4686 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4687 {
4688 compl_shown_match = compl_shown_match->cp_prev;
4689 ++compl_pending;
4690 }
4691 else
4692 break;
4693 }
4694 found_end = FALSE;
4695 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004696 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004697 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004698 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004699 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004700 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004701 ++todo;
4702 else
4703 // Remember a matching item.
4704 found_compl = compl_shown_match;
4705
4706 // Stop at the end of the list when we found a usable match.
4707 if (found_end)
4708 {
4709 if (found_compl != NULL)
4710 {
4711 compl_shown_match = found_compl;
4712 break;
4713 }
4714 todo = 1; // use first usable match after wrapping around
4715 }
4716 }
4717
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004718 return OK;
4719}
4720
4721/*
4722 * Fill in the next completion in the current direction.
4723 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4724 * get more completions. If it is FALSE, then we just do nothing when there
4725 * are no more completions in a given direction. The latter case is used when
4726 * we are still in the middle of finding completions, to allow browsing
4727 * through the ones found so far.
4728 * Return the total number of matches, or -1 if still unknown -- webb.
4729 *
4730 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4731 * compl_shown_match here.
4732 *
4733 * Note that this function may be called recursively once only. First with
4734 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4735 * calls this function with "allow_get_expansion" FALSE.
4736 */
4737 static int
4738ins_compl_next(
4739 int allow_get_expansion,
4740 int count, // repeat completion this many times; should
4741 // be at least 1
4742 int insert_match, // Insert the newly selected match
4743 int in_compl_func) // called from complete_check()
4744{
4745 int num_matches = -1;
4746 int todo = count;
4747 int advance;
4748 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004749 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004750 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004751 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4752 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01004753 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004754
4755 // When user complete function return -1 for findstart which is next
4756 // time of 'always', compl_shown_match become NULL.
4757 if (compl_shown_match == NULL)
4758 return -1;
4759
John Marriott5e6ea922024-11-23 14:01:57 +01004760 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004761 && !match_at_original_text(compl_shown_match)
4762 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004763 // Update "compl_shown_match" to the actually shown match
4764 ins_compl_update_shown_match();
4765
4766 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004767 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004768 // Delete old text to be replaced
4769 ins_compl_delete();
4770
4771 // When finding the longest common text we stick at the original text,
4772 // don't let CTRL-N or CTRL-P move to the first match.
4773 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4774
4775 // When restarting the search don't insert the first match either.
4776 if (compl_restarting)
4777 {
4778 advance = FALSE;
4779 compl_restarting = FALSE;
4780 }
4781
4782 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4783 // around.
4784 if (find_next_completion_match(allow_get_expansion, todo, advance,
4785 &num_matches) == -1)
4786 return -1;
4787
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004788 if (curbuf != orig_curbuf)
4789 {
4790 // In case some completion function switched buffer, don't want to
4791 // insert the completion elsewhere.
4792 return -1;
4793 }
4794
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004795 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01004796 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004797 {
glepnir6a38aff2024-12-16 21:56:16 +01004798 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004799 compl_used_match = FALSE;
4800 }
4801 else if (insert_match)
4802 {
4803 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01004804 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004805 else
glepnir6a38aff2024-12-16 21:56:16 +01004806 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004807 }
4808 else
4809 compl_used_match = FALSE;
4810
4811 if (!allow_get_expansion)
4812 {
4813 // may undisplay the popup menu first
4814 ins_compl_upd_pum();
4815
4816 if (pum_enough_matches())
4817 // Will display the popup menu, don't redraw yet to avoid flicker.
4818 pum_call_update_screen();
4819 else
4820 // Not showing the popup menu yet, redraw to show the user what was
4821 // inserted.
4822 update_screen(0);
4823
4824 // display the updated popup menu
4825 ins_compl_show_pum();
4826#ifdef FEAT_GUI
4827 if (gui.in_use)
4828 {
4829 // Show the cursor after the match, not after the redrawn text.
4830 setcursor();
4831 out_flush_cursor(FALSE, FALSE);
4832 }
4833#endif
4834
4835 // Delete old text to be replaced, since we're still searching and
4836 // don't want to match ourselves!
4837 ins_compl_delete();
4838 }
4839
4840 // Enter will select a match when the match wasn't inserted and the popup
4841 // menu is visible.
4842 if (compl_no_insert && !started)
4843 compl_enter_selects = TRUE;
4844 else
4845 compl_enter_selects = !insert_match && compl_match_array != NULL;
4846
4847 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004848 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004849 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004850
4851 return num_matches;
4852}
4853
4854/*
4855 * Call this while finding completions, to check whether the user has hit a key
4856 * that should change the currently displayed completion, or exit completion
4857 * mode. Also, when compl_pending is not zero, show a completion as soon as
4858 * possible. -- webb
4859 * "frequency" specifies out of how many calls we actually check.
4860 * "in_compl_func" is TRUE when called from complete_check(), don't set
4861 * compl_curr_match.
4862 */
4863 void
4864ins_compl_check_keys(int frequency, int in_compl_func)
4865{
4866 static int count = 0;
4867 int c;
4868
4869 // Don't check when reading keys from a script, :normal or feedkeys().
4870 // That would break the test scripts. But do check for keys when called
4871 // from complete_check().
4872 if (!in_compl_func && (using_script() || ex_normal_busy))
4873 return;
4874
4875 // Only do this at regular intervals
4876 if (++count < frequency)
4877 return;
4878 count = 0;
4879
4880 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4881 // can't do its work correctly.
4882 c = vpeekc_any();
4883 if (c != NUL)
4884 {
4885 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4886 {
4887 c = safe_vgetc(); // Eat the character
4888 compl_shows_dir = ins_compl_key2dir(c);
4889 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4890 c != K_UP && c != K_DOWN, in_compl_func);
4891 }
4892 else
4893 {
4894 // Need to get the character to have KeyTyped set. We'll put it
4895 // back with vungetc() below. But skip K_IGNORE.
4896 c = safe_vgetc();
4897 if (c != K_IGNORE)
4898 {
4899 // Don't interrupt completion when the character wasn't typed,
4900 // e.g., when doing @q to replay keys.
4901 if (c != Ctrl_R && KeyTyped)
4902 compl_interrupted = TRUE;
4903
4904 vungetc(c);
4905 }
4906 }
4907 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004908 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004909 {
4910 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4911
4912 compl_pending = 0;
4913 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4914 }
4915}
4916
4917/*
4918 * Decide the direction of Insert mode complete from the key typed.
4919 * Returns BACKWARD or FORWARD.
4920 */
4921 static int
4922ins_compl_key2dir(int c)
4923{
4924 if (c == Ctrl_P || c == Ctrl_L
4925 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4926 return BACKWARD;
4927 return FORWARD;
4928}
4929
4930/*
4931 * Return TRUE for keys that are used for completion only when the popup menu
4932 * is visible.
4933 */
4934 static int
4935ins_compl_pum_key(int c)
4936{
4937 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4938 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4939 || c == K_UP || c == K_DOWN);
4940}
4941
4942/*
4943 * Decide the number of completions to move forward.
4944 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4945 */
4946 static int
4947ins_compl_key2count(int c)
4948{
4949 int h;
4950
4951 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4952 {
4953 h = pum_get_height();
4954 if (h > 3)
4955 h -= 2; // keep some context
4956 return h;
4957 }
4958 return 1;
4959}
4960
4961/*
4962 * Return TRUE if completion with "c" should insert the match, FALSE if only
4963 * to change the currently selected completion.
4964 */
4965 static int
4966ins_compl_use_match(int c)
4967{
4968 switch (c)
4969 {
4970 case K_UP:
4971 case K_DOWN:
4972 case K_PAGEDOWN:
4973 case K_KPAGEDOWN:
4974 case K_S_DOWN:
4975 case K_PAGEUP:
4976 case K_KPAGEUP:
4977 case K_S_UP:
4978 return FALSE;
4979 }
4980 return TRUE;
4981}
4982
4983/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004984 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4985 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004986 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004987 * Uses the global variables: compl_cont_status and ctrl_x_mode
4988 */
4989 static int
4990get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4991{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004992 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004993 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004994 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004995 {
4996 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4997 ;
4998 compl_col += ++startcol;
4999 compl_length = curs_col - startcol;
5000 }
5001 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005002 {
John Marriott5e6ea922024-11-23 14:01:57 +01005003 compl_pattern.string = str_foldcase(line + compl_col,
5004 compl_length, NULL, 0);
5005 if (compl_pattern.string == NULL)
5006 {
5007 compl_pattern.length = 0;
5008 return FAIL;
5009 }
5010 compl_pattern.length = STRLEN(compl_pattern.string);
5011 }
5012 else
5013 {
5014 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5015 if (compl_pattern.string == NULL)
5016 {
5017 compl_pattern.length = 0;
5018 return FAIL;
5019 }
5020 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005021 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005022 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005023 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005024 {
5025 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005026 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005027 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005028
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005029 if (!vim_iswordp(line + compl_col)
5030 || (compl_col > 0
5031 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005032 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005033 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005034 prefixlen = 0;
5035 }
John Marriott5e6ea922024-11-23 14:01:57 +01005036
5037 // we need up to 2 extra chars for the prefix
5038 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5039 compl_pattern.string = alloc(n);
5040 if (compl_pattern.string == NULL)
5041 {
5042 compl_pattern.length = 0;
5043 return FAIL;
5044 }
5045 STRCPY((char *)compl_pattern.string, prefix);
5046 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005047 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005048 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005049 }
5050 else if (--startcol < 0
5051 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5052 {
John Marriott5e6ea922024-11-23 14:01:57 +01005053 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5054
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005055 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005056 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5057 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005058 {
John Marriott5e6ea922024-11-23 14:01:57 +01005059 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005060 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005061 }
John Marriott5e6ea922024-11-23 14:01:57 +01005062 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005063 compl_col += curs_col;
5064 compl_length = 0;
5065 }
5066 else
5067 {
5068 // Search the point of change class of multibyte character
5069 // or not a word single byte character backward.
5070 if (has_mbyte)
5071 {
5072 int base_class;
5073 int head_off;
5074
5075 startcol -= (*mb_head_off)(line, line + startcol);
5076 base_class = mb_get_class(line + startcol);
5077 while (--startcol >= 0)
5078 {
5079 head_off = (*mb_head_off)(line, line + startcol);
5080 if (base_class != mb_get_class(line + startcol
5081 - head_off))
5082 break;
5083 startcol -= head_off;
5084 }
5085 }
5086 else
5087 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5088 ;
5089 compl_col += ++startcol;
5090 compl_length = (int)curs_col - startcol;
5091 if (compl_length == 1)
5092 {
5093 // Only match word with at least two chars -- webb
5094 // there's no need to call quote_meta,
5095 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005096 compl_pattern.string = alloc(7);
5097 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005098 {
John Marriott5e6ea922024-11-23 14:01:57 +01005099 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005100 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005101 }
John Marriott5e6ea922024-11-23 14:01:57 +01005102 STRCPY((char *)compl_pattern.string, "\\<");
5103 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5104 STRCAT((char *)compl_pattern.string, "\\k");
5105 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005106 }
5107 else
5108 {
John Marriott5e6ea922024-11-23 14:01:57 +01005109 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5110
5111 compl_pattern.string = alloc(n);
5112 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005113 {
John Marriott5e6ea922024-11-23 14:01:57 +01005114 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005115 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005116 }
John Marriott5e6ea922024-11-23 14:01:57 +01005117 STRCPY((char *)compl_pattern.string, "\\<");
5118 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005119 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005120 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005121 }
5122 }
5123
5124 return OK;
5125}
5126
5127/*
5128 * Get the pattern, column and length for whole line completion or for the
5129 * complete() function.
5130 * Sets the global variables: compl_col, compl_length and compl_pattern.
5131 */
5132 static int
5133get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5134{
5135 compl_col = (colnr_T)getwhitecols(line);
5136 compl_length = (int)curs_col - (int)compl_col;
5137 if (compl_length < 0) // cursor in indent: empty pattern
5138 compl_length = 0;
5139 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005140 {
John Marriott5e6ea922024-11-23 14:01:57 +01005141 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5142 NULL, 0);
5143 if (compl_pattern.string == NULL)
5144 {
5145 compl_pattern.length = 0;
5146 return FAIL;
5147 }
5148 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005149 }
John Marriott5e6ea922024-11-23 14:01:57 +01005150 else
5151 {
5152 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5153 if (compl_pattern.string == NULL)
5154 {
5155 compl_pattern.length = 0;
5156 return FAIL;
5157 }
5158 compl_pattern.length = (size_t)compl_length;
5159 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005160
5161 return OK;
5162}
5163
5164/*
5165 * Get the pattern, column and length for filename completion.
5166 * Sets the global variables: compl_col, compl_length and compl_pattern.
5167 */
5168 static int
5169get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5170{
5171 // Go back to just before the first filename character.
5172 if (startcol > 0)
5173 {
5174 char_u *p = line + startcol;
5175
5176 MB_PTR_BACK(line, p);
5177 while (p > line && vim_isfilec(PTR2CHAR(p)))
5178 MB_PTR_BACK(line, p);
5179 if (p == line && vim_isfilec(PTR2CHAR(p)))
5180 startcol = 0;
5181 else
5182 startcol = (int)(p - line) + 1;
5183 }
5184
5185 compl_col += startcol;
5186 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005187 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5188 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005189 {
John Marriott5e6ea922024-11-23 14:01:57 +01005190 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005191 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005192 }
5193
John Marriott5e6ea922024-11-23 14:01:57 +01005194 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005195
5196 return OK;
5197}
5198
5199/*
5200 * Get the pattern, column and length for command-line completion.
5201 * Sets the global variables: compl_col, compl_length and compl_pattern.
5202 */
5203 static int
5204get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5205{
John Marriott5e6ea922024-11-23 14:01:57 +01005206 compl_pattern.string = vim_strnsave(line, curs_col);
5207 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005208 {
John Marriott5e6ea922024-11-23 14:01:57 +01005209 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005210 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005211 }
John Marriott5e6ea922024-11-23 14:01:57 +01005212 compl_pattern.length = curs_col;
5213 set_cmd_context(&compl_xp, compl_pattern.string,
5214 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005215 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5216 || compl_xp.xp_context == EXPAND_NOTHING)
5217 // No completion possible, use an empty pattern to get a
5218 // "pattern not found" message.
5219 compl_col = curs_col;
5220 else
John Marriott5e6ea922024-11-23 14:01:57 +01005221 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005222 compl_length = curs_col - compl_col;
5223
5224 return OK;
5225}
5226
5227/*
5228 * Get the pattern, column and length for user defined completion ('omnifunc',
5229 * 'completefunc' and 'thesaurusfunc')
5230 * Sets the global variables: compl_col, compl_length and compl_pattern.
5231 * Uses the global variable: spell_bad_len
5232 */
5233 static int
5234get_userdefined_compl_info(colnr_T curs_col UNUSED)
5235{
5236 int ret = FAIL;
5237
5238#ifdef FEAT_COMPL_FUNC
5239 // Call user defined function 'completefunc' with "a:findstart"
5240 // set to 1 to obtain the length of text to use for completion.
5241 char_u *line;
5242 typval_T args[3];
5243 int col;
5244 char_u *funcname;
5245 pos_T pos;
5246 int save_State = State;
5247 callback_T *cb;
5248
5249 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5250 // length as a string
5251 funcname = get_complete_funcname(ctrl_x_mode);
5252 if (*funcname == NUL)
5253 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005254 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005255 ? "completefunc" : "omnifunc");
5256 return FAIL;
5257 }
5258
5259 args[0].v_type = VAR_NUMBER;
5260 args[0].vval.v_number = 1;
5261 args[1].v_type = VAR_STRING;
5262 args[1].vval.v_string = (char_u *)"";
5263 args[2].v_type = VAR_UNKNOWN;
5264 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005265 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005266 cb = get_insert_callback(ctrl_x_mode);
5267 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005268 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005269
5270 State = save_State;
5271 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005272 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005273 validate_cursor();
5274 if (!EQUAL_POS(curwin->w_cursor, pos))
5275 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005276 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005277 return FAIL;
5278 }
5279
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005280 // Return value -2 means the user complete function wants to cancel the
5281 // complete without an error, do the same if the function did not execute
5282 // successfully.
5283 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005284 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005285 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005286 if (col == -3)
5287 {
5288 ctrl_x_mode = CTRL_X_NORMAL;
5289 edit_submode = NULL;
5290 if (!shortmess(SHM_COMPLETIONMENU))
5291 msg_clr_cmdline();
5292 return FAIL;
5293 }
5294
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005295 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005296 // completion.
5297 compl_opt_refresh_always = FALSE;
5298 compl_opt_suppress_empty = FALSE;
5299
5300 if (col < 0)
5301 col = curs_col;
5302 compl_col = col;
5303 if (compl_col > curs_col)
5304 compl_col = curs_col;
5305
5306 // Setup variables for completion. Need to obtain "line" again,
5307 // it may have become invalid.
5308 line = ml_get(curwin->w_cursor.lnum);
5309 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005310 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5311 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005312 {
John Marriott5e6ea922024-11-23 14:01:57 +01005313 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005314 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005315 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005316
John Marriott5e6ea922024-11-23 14:01:57 +01005317 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005318 ret = OK;
5319#endif
5320
5321 return ret;
5322}
5323
5324/*
5325 * Get the pattern, column and length for spell completion.
5326 * Sets the global variables: compl_col, compl_length and compl_pattern.
5327 * Uses the global variable: spell_bad_len
5328 */
5329 static int
5330get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5331{
5332 int ret = FAIL;
5333#ifdef FEAT_SPELL
5334 char_u *line;
5335
5336 if (spell_bad_len > 0)
5337 compl_col = curs_col - spell_bad_len;
5338 else
5339 compl_col = spell_word_start(startcol);
5340 if (compl_col >= (colnr_T)startcol)
5341 {
5342 compl_length = 0;
5343 compl_col = curs_col;
5344 }
5345 else
5346 {
5347 spell_expand_check_cap(compl_col);
5348 compl_length = (int)curs_col - compl_col;
5349 }
5350 // Need to obtain "line" again, it may have become invalid.
5351 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005352 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5353 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005354 {
John Marriott5e6ea922024-11-23 14:01:57 +01005355 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005356 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005357 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005358
John Marriott5e6ea922024-11-23 14:01:57 +01005359 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005360 ret = OK;
5361#endif
5362
5363 return ret;
5364}
5365
5366/*
5367 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005368 * "startcol" - start column number of the completion pattern/text
5369 * "cur_col" - current cursor column
5370 * On return, "line_invalid" is set to TRUE, if the current line may have
5371 * become invalid and needs to be fetched again.
5372 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005373 */
5374 static int
5375compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5376{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005377 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005378 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5379 && !thesaurus_func_complete(ctrl_x_mode)))
5380 {
5381 return get_normal_compl_info(line, startcol, curs_col);
5382 }
5383 else if (ctrl_x_mode_line_or_eval())
5384 {
5385 return get_wholeline_compl_info(line, curs_col);
5386 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005387 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005388 {
5389 return get_filename_compl_info(line, startcol, curs_col);
5390 }
5391 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5392 {
5393 return get_cmdline_compl_info(line, curs_col);
5394 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005395 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005396 || thesaurus_func_complete(ctrl_x_mode))
5397 {
5398 if (get_userdefined_compl_info(curs_col) == FAIL)
5399 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005400 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005401 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005402 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005403 {
5404 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5405 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005406 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005407 }
5408 else
5409 {
5410 internal_error("ins_complete()");
5411 return FAIL;
5412 }
5413
5414 return OK;
5415}
5416
5417/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005418 * Continue an interrupted completion mode search in "line".
5419 *
5420 * If this same ctrl_x_mode has been interrupted use the text from
5421 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5422 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5423 * the same line as the cursor then fix it (the line has been split because it
5424 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5425 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005426 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005427 static void
5428ins_compl_continue_search(char_u *line)
5429{
5430 // it is a continued search
5431 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005432 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5433 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005434 {
5435 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5436 {
5437 // line (probably) wrapped, set compl_startpos to the
5438 // first non_blank in the line, if it is not a wordchar
5439 // include it to get a better pattern, but then we don't
5440 // want the "\\<" prefix, check it below
5441 compl_col = (colnr_T)getwhitecols(line);
5442 compl_startpos.col = compl_col;
5443 compl_startpos.lnum = curwin->w_cursor.lnum;
5444 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5445 }
5446 else
5447 {
5448 // S_IPOS was set when we inserted a word that was at the
5449 // beginning of the line, which means that we'll go to SOL
5450 // mode but first we need to redefine compl_startpos
5451 if (compl_cont_status & CONT_S_IPOS)
5452 {
5453 compl_cont_status |= CONT_SOL;
5454 compl_startpos.col = (colnr_T)(skipwhite(
5455 line + compl_length
5456 + compl_startpos.col) - line);
5457 }
5458 compl_col = compl_startpos.col;
5459 }
5460 compl_length = curwin->w_cursor.col - (int)compl_col;
5461 // IObuff is used to add a "word from the next line" would we
5462 // have enough space? just being paranoid
5463#define MIN_SPACE 75
5464 if (compl_length > (IOSIZE - MIN_SPACE))
5465 {
5466 compl_cont_status &= ~CONT_SOL;
5467 compl_length = (IOSIZE - MIN_SPACE);
5468 compl_col = curwin->w_cursor.col - compl_length;
5469 }
5470 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5471 if (compl_length < 1)
5472 compl_cont_status &= CONT_LOCAL;
5473 }
5474 else if (ctrl_x_mode_line_or_eval())
5475 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5476 else
5477 compl_cont_status = 0;
5478}
5479
5480/*
5481 * start insert mode completion
5482 */
5483 static int
5484ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005485{
5486 char_u *line;
5487 int startcol = 0; // column where searched text starts
5488 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005489 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005491 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005492
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005493 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005494
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005495 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005496 did_si = FALSE;
5497 can_si = FALSE;
5498 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005499 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005500 return FAIL;
5501
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005502 line = ml_get(curwin->w_cursor.lnum);
5503 curs_col = curwin->w_cursor.col;
5504 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005505 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005506
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005507 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5508 && compl_cont_mode == ctrl_x_mode)
5509 // this same ctrl-x_mode was interrupted previously. Continue the
5510 // completion.
5511 ins_compl_continue_search(line);
5512 else
5513 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005514
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005515 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005516 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005517 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005518 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005519 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5520 compl_cont_status = 0;
5521 compl_cont_status |= CONT_N_ADDS;
5522 compl_startpos = curwin->w_cursor;
5523 startcol = (int)curs_col;
5524 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005525 }
5526
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005527 // Work out completion pattern and original text -- webb
5528 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5529 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005530 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5531 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005532 // restore did_ai, so that adding comment leader works
5533 did_ai = save_did_ai;
5534 return FAIL;
5535 }
5536 // If "line" was changed while getting completion info get it again.
5537 if (line_invalid)
5538 line = ml_get(curwin->w_cursor.lnum);
5539
glepnir7cfe6932024-09-15 20:06:28 +02005540 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005541 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005542 {
5543 edit_submode_pre = (char_u *)_(" Adding");
5544 if (ctrl_x_mode_line_or_eval())
5545 {
5546 // Insert a new line, keep indentation but ignore 'comments'.
5547 char_u *old = curbuf->b_p_com;
5548
5549 curbuf->b_p_com = (char_u *)"";
5550 compl_startpos.lnum = curwin->w_cursor.lnum;
5551 compl_startpos.col = compl_col;
5552 ins_eol('\r');
5553 curbuf->b_p_com = old;
5554 compl_length = 0;
5555 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01005556 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005557 }
glepnir7cfe6932024-09-15 20:06:28 +02005558 else if (ctrl_x_mode_normal() && in_fuzzy)
5559 {
5560 compl_startpos = curwin->w_cursor;
5561 compl_cont_status &= CONT_S_IPOS;
5562 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005563 }
5564 else
5565 {
5566 edit_submode_pre = NULL;
5567 compl_startpos.col = compl_col;
5568 }
5569
5570 if (compl_cont_status & CONT_LOCAL)
5571 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5572 else
5573 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5574
5575 // If any of the original typed text has been changed we need to fix
5576 // the redo buffer.
5577 ins_compl_fixRedoBufForLeader(NULL);
5578
5579 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005580 VIM_CLEAR_STRING(compl_orig_text);
5581 compl_orig_text.length = (size_t)compl_length;
5582 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005583 if (p_ic)
5584 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005585 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5586 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005587 {
John Marriott5e6ea922024-11-23 14:01:57 +01005588 VIM_CLEAR_STRING(compl_pattern);
5589 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005590 return FAIL;
5591 }
5592
5593 // showmode might reset the internal line pointers, so it must
5594 // be called before line = ml_get(), or when this address is no
5595 // longer needed. -- Acevedo.
5596 edit_submode_extra = (char_u *)_("-- Searching...");
5597 edit_submode_highl = HLF_COUNT;
5598 showmode();
5599 edit_submode_extra = NULL;
5600 out_flush();
5601
5602 return OK;
5603}
5604
5605/*
5606 * display the completion status message
5607 */
5608 static void
5609ins_compl_show_statusmsg(void)
5610{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005611 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005612 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005613 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005614 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005615 ? (char_u *)_("Hit end of paragraph")
5616 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005617 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005618 }
5619
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005620 if (edit_submode_extra == NULL)
5621 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005622 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005623 {
5624 edit_submode_extra = (char_u *)_("Back at original");
5625 edit_submode_highl = HLF_W;
5626 }
5627 else if (compl_cont_status & CONT_S_IPOS)
5628 {
5629 edit_submode_extra = (char_u *)_("Word from other line");
5630 edit_submode_highl = HLF_COUNT;
5631 }
5632 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5633 {
5634 edit_submode_extra = (char_u *)_("The only match");
5635 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005636 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005637 }
5638 else
5639 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005640#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005641 // Update completion sequence number when needed.
5642 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005643 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005644#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005645 // The match should always have a sequence number now, this is
5646 // just a safety check.
5647 if (compl_curr_match->cp_number != -1)
5648 {
5649 // Space for 10 text chars. + 2x10-digit no.s = 31.
5650 // Translations may need more than twice that.
5651 static char_u match_ref[81];
5652
5653 if (compl_matches > 0)
5654 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005655 _("match %d of %d"),
5656 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005657 else
5658 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005659 _("match %d"),
5660 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005661 edit_submode_extra = match_ref;
5662 edit_submode_highl = HLF_R;
5663 if (dollar_vcol >= 0)
5664 curs_columns(FALSE);
5665 }
5666 }
5667 }
5668
5669 // Show a message about what (completion) mode we're in.
5670 if (!compl_opt_suppress_empty)
5671 {
5672 showmode();
5673 if (!shortmess(SHM_COMPLETIONMENU))
5674 {
5675 if (edit_submode_extra != NULL)
5676 {
5677 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005678 {
5679 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005680 msg_attr((char *)edit_submode_extra,
5681 edit_submode_highl < HLF_COUNT
5682 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005683 msg_hist_off = FALSE;
5684 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005685 }
5686 else
5687 msg_clr_cmdline(); // necessary for "noshowmode"
5688 }
5689 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005690}
5691
5692/*
5693 * Do Insert mode completion.
5694 * Called when character "c" was typed, which has a meaning for completion.
5695 * Returns OK if completion was done, FAIL if something failed (out of mem).
5696 */
5697 int
5698ins_complete(int c, int enable_pum)
5699{
5700 int n;
5701 int save_w_wrow;
5702 int save_w_leftcol;
5703 int insert_match;
5704
5705 compl_direction = ins_compl_key2dir(c);
5706 insert_match = ins_compl_use_match(c);
5707
5708 if (!compl_started)
5709 {
5710 if (ins_compl_start() == FAIL)
5711 return FAIL;
5712 }
5713 else if (insert_match && stop_arrow() == FAIL)
5714 return FAIL;
5715
5716 compl_shown_match = compl_curr_match;
5717 compl_shows_dir = compl_direction;
5718
5719 // Find next match (and following matches).
5720 save_w_wrow = curwin->w_wrow;
5721 save_w_leftcol = curwin->w_leftcol;
5722 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5723
5724 // may undisplay the popup menu
5725 ins_compl_upd_pum();
5726
5727 if (n > 1) // all matches have been found
5728 compl_matches = n;
5729 compl_curr_match = compl_shown_match;
5730 compl_direction = compl_shows_dir;
5731
5732 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5733 // mode.
5734 if (got_int && !global_busy)
5735 {
5736 (void)vgetc();
5737 got_int = FALSE;
5738 }
5739
5740 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005741 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005742 {
5743 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5744 // because we couldn't expand anything at first place, but if we used
5745 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5746 // (such as M in M'exico) if not tried already. -- Acevedo
5747 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005748 || compl_status_adding()
5749 || (ctrl_x_mode_not_default()
5750 && !ctrl_x_mode_path_patterns()
5751 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005752 compl_cont_status &= ~CONT_N_ADDS;
5753 }
5754
5755 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5756 compl_cont_status |= CONT_S_IPOS;
5757 else
5758 compl_cont_status &= ~CONT_S_IPOS;
5759
5760 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005761
5762 // Show the popup menu, unless we got interrupted.
5763 if (enable_pum && !compl_interrupted)
5764 show_pum(save_w_wrow, save_w_leftcol);
5765
5766 compl_was_interrupted = compl_interrupted;
5767 compl_interrupted = FALSE;
5768
5769 return OK;
5770}
5771
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005772/*
5773 * Remove (if needed) and show the popup menu
5774 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005775 static void
5776show_pum(int prev_w_wrow, int prev_w_leftcol)
5777{
5778 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005779 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005780 RedrawingDisabled = 0;
5781
5782 // If the cursor moved or the display scrolled we need to remove the pum
5783 // first.
5784 setcursor();
5785 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5786 ins_compl_del_pum();
5787
5788 ins_compl_show_pum();
5789 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005790
5791 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005792}
5793
5794/*
5795 * Looks in the first "len" chars. of "src" for search-metachars.
5796 * If dest is not NULL the chars. are copied there quoting (with
5797 * a backslash) the metachars, and dest would be NUL terminated.
5798 * Returns the length (needed) of dest
5799 */
5800 static unsigned
5801quote_meta(char_u *dest, char_u *src, int len)
5802{
5803 unsigned m = (unsigned)len + 1; // one extra for the NUL
5804
5805 for ( ; --len >= 0; src++)
5806 {
5807 switch (*src)
5808 {
5809 case '.':
5810 case '*':
5811 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005812 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005813 break;
5814 // FALLTHROUGH
5815 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005816 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005817 break;
5818 // FALLTHROUGH
5819 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005820 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005821 break;
5822 // FALLTHROUGH
5823 case '^': // currently it's not needed.
5824 case '$':
5825 m++;
5826 if (dest != NULL)
5827 *dest++ = '\\';
5828 break;
5829 }
5830 if (dest != NULL)
5831 *dest++ = *src;
5832 // Copy remaining bytes of a multibyte character.
5833 if (has_mbyte)
5834 {
5835 int i, mb_len;
5836
5837 mb_len = (*mb_ptr2len)(src) - 1;
5838 if (mb_len > 0 && len >= mb_len)
5839 for (i = 0; i < mb_len; ++i)
5840 {
5841 --len;
5842 ++src;
5843 if (dest != NULL)
5844 *dest++ = *src;
5845 }
5846 }
5847 }
5848 if (dest != NULL)
5849 *dest = NUL;
5850
5851 return m;
5852}
5853
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005854#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005855 void
5856free_insexpand_stuff(void)
5857{
John Marriott5e6ea922024-11-23 14:01:57 +01005858 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005859# ifdef FEAT_EVAL
5860 free_callback(&cfu_cb);
5861 free_callback(&ofu_cb);
5862 free_callback(&tsrfu_cb);
5863# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005864}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005865#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005866
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005867#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005868/*
5869 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5870 * spelled word, if there is one.
5871 */
5872 static void
5873spell_back_to_badword(void)
5874{
5875 pos_T tpos = curwin->w_cursor;
5876
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005877 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005878 if (curwin->w_cursor.col != tpos.col)
5879 start_arrow(&tpos);
5880}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005881#endif