blob: a0f552e9542bc18016eec0a80251aaa6279810e8 [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;
821 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200822 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100823 match->cp_number = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100824 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100825 {
826 vim_free(match);
827 return FAIL;
828 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829
John Marriott5e6ea922024-11-23 14:01:57 +0100830 match->cp_str.length = len;
831
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100832 // match-fname is:
833 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200834 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100835 // - NULL otherwise. --Acevedo
836 if (fname != NULL
837 && compl_curr_match != NULL
838 && compl_curr_match->cp_fname != NULL
839 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
840 match->cp_fname = compl_curr_match->cp_fname;
841 else if (fname != NULL)
842 {
843 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200844 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100845 }
846 else
847 match->cp_fname = NULL;
848 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100849 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
850 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100851
852 if (cptext != NULL)
853 {
854 int i;
855
856 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100857 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100858 if (cptext[i] != NULL && *cptext[i] != NUL)
859 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100860 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100861 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100862#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100863 if (user_data != NULL)
864 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100865#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100866
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000867 // Link the new match structure after (FORWARD) or before (BACKWARD) the
868 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100869 if (compl_first_match == NULL)
870 match->cp_next = match->cp_prev = NULL;
871 else if (dir == FORWARD)
872 {
873 match->cp_next = compl_curr_match->cp_next;
874 match->cp_prev = compl_curr_match;
875 }
876 else // BACKWARD
877 {
878 match->cp_next = compl_curr_match;
879 match->cp_prev = compl_curr_match->cp_prev;
880 }
881 if (match->cp_next)
882 match->cp_next->cp_prev = match;
883 if (match->cp_prev)
884 match->cp_prev->cp_next = match;
885 else // if there's nothing before, it is the first match
886 compl_first_match = match;
887 compl_curr_match = match;
888
889 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200890 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100891 ins_compl_longest_match(match);
892
893 return OK;
894}
895
896/*
897 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200898 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100899 */
900 static int
901ins_compl_equal(compl_T *match, char_u *str, int len)
902{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200903 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200904 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200905 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100906 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
907 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100908}
909
910/*
glepnir6a38aff2024-12-16 21:56:16 +0100911 * when len is -1 mean use whole length of p otherwise part of p
912 */
913 static void
914ins_compl_insert_bytes(char_u *p, int len)
915{
916 if (len == -1)
917 len = (int)STRLEN(p);
918 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +0100919 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +0100920}
921
922/*
zeertzjqd32bf0a2024-12-17 20:55:13 +0100923 * Checks if the column is within the currently inserted completion text
924 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +0100925 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +0100926 */
927 int
glepnir76bdb822025-02-08 19:04:51 +0100928ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +0100929{
glepnir76bdb822025-02-08 19:04:51 +0100930 int start_col;
931 int attr;
932
933 if ((get_cot_flags() & COT_FUZZY)
934 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +0100935 return -1;
936
glepnir76bdb822025-02-08 19:04:51 +0100937 start_col = compl_col + (int)ins_compl_leader_len();
938 if (!ins_compl_has_multiple())
939 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
940
941 // Multiple lines
942 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
943 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
944 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
945 return attr;
glepnir6a38aff2024-12-16 21:56:16 +0100946
947 return -1;
948}
949
950/*
glepnir76bdb822025-02-08 19:04:51 +0100951 * Returns TRUE if the current completion string contains newline characters,
952 * indicating it's a multi-line completion.
953 */
954 static int
955ins_compl_has_multiple(void)
956{
957 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
958}
959
960/*
961 * Returns TRUE if the given line number falls within the range of a multi-line
962 * completion, i.e. between the starting line (compl_lnum) and current cursor
963 * line. Always returns FALSE for single-line completions.
964 */
965 int
966ins_compl_lnum_in_range(linenr_T lnum)
967{
968 if (!ins_compl_has_multiple())
969 return FALSE;
970 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
971}
972
973/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100974 * Reduce the longest common string for match "match".
975 */
976 static void
977ins_compl_longest_match(compl_T *match)
978{
979 char_u *p, *s;
980 int c1, c2;
981 int had_match;
982
John Marriott5e6ea922024-11-23 14:01:57 +0100983 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100984 {
985 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +0100986 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
987 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000988 return;
989
John Marriott5e6ea922024-11-23 14:01:57 +0100990 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000991 had_match = (curwin->w_cursor.col > compl_col);
992 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +0100993 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000994 ins_redraw(FALSE);
995
996 // When the match isn't there (to avoid matching itself) remove it
997 // again after redrawing.
998 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100999 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001000 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001001
1002 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001003 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001004
1005 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001006 p = compl_leader.string;
1007 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001008 while (*p != NUL)
1009 {
1010 if (has_mbyte)
1011 {
1012 c1 = mb_ptr2char(p);
1013 c2 = mb_ptr2char(s);
1014 }
1015 else
1016 {
1017 c1 = *p;
1018 c2 = *s;
1019 }
1020 if ((match->cp_flags & CP_ICASE)
1021 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1022 break;
1023 if (has_mbyte)
1024 {
1025 MB_PTR_ADV(p);
1026 MB_PTR_ADV(s);
1027 }
1028 else
1029 {
1030 ++p;
1031 ++s;
1032 }
1033 }
1034
1035 if (*p != NUL)
1036 {
1037 // Leader was shortened, need to change the inserted text.
1038 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001039 compl_leader.length = (size_t)(p - compl_leader.string);
1040
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001041 had_match = (curwin->w_cursor.col > compl_col);
1042 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01001043 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001044 ins_redraw(FALSE);
1045
1046 // When the match isn't there (to avoid matching itself) remove it
1047 // again after redrawing.
1048 if (!had_match)
1049 ins_compl_delete();
1050 }
1051
1052 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001053}
1054
1055/*
1056 * Add an array of matches to the list of matches.
1057 * Frees matches[].
1058 */
1059 static void
1060ins_compl_add_matches(
1061 int num_matches,
1062 char_u **matches,
1063 int icase)
1064{
1065 int i;
1066 int add_r = OK;
1067 int dir = compl_direction;
1068
1069 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001070 {
1071 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
1072 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL);
1073 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001074 // if dir was BACKWARD then honor it just once
1075 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001076 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001077 FreeWild(num_matches, matches);
1078}
1079
1080/*
1081 * Make the completion list cyclic.
1082 * Return the number of matches (excluding the original).
1083 */
1084 static int
1085ins_compl_make_cyclic(void)
1086{
1087 compl_T *match;
1088 int count = 0;
1089
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001090 if (compl_first_match == NULL)
1091 return 0;
1092
1093 // Find the end of the list.
1094 match = compl_first_match;
1095 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001096 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001097 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001098 match = match->cp_next;
1099 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001100 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001101 match->cp_next = compl_first_match;
1102 compl_first_match->cp_prev = match;
1103
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001104 return count;
1105}
1106
1107/*
1108 * Return whether there currently is a shown match.
1109 */
1110 int
1111ins_compl_has_shown_match(void)
1112{
1113 return compl_shown_match == NULL
1114 || compl_shown_match != compl_shown_match->cp_next;
1115}
1116
1117/*
1118 * Return whether the shown match is long enough.
1119 */
1120 int
1121ins_compl_long_shown_match(void)
1122{
John Marriott5e6ea922024-11-23 14:01:57 +01001123 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001124 > curwin->w_cursor.col - compl_col;
1125}
1126
1127/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001128 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001129 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001130 unsigned int
1131get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001132{
zeertzjq529b9ad2024-06-05 20:27:06 +02001133 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134}
1135
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001136/*
1137 * Update the screen and when there is any scrolling remove the popup menu.
1138 */
1139 static void
1140ins_compl_upd_pum(void)
1141{
1142 int h;
1143
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001144 if (compl_match_array == NULL)
1145 return;
1146
1147 h = curwin->w_cline_height;
1148 // Update the screen later, before drawing the popup menu over it.
1149 pum_call_update_screen();
1150 if (h != curwin->w_cline_height)
1151 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001152}
1153
1154/*
1155 * Remove any popup menu.
1156 */
1157 static void
1158ins_compl_del_pum(void)
1159{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001160 if (compl_match_array == NULL)
1161 return;
1162
1163 pum_undisplay();
1164 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001165}
1166
1167/*
1168 * Return TRUE if the popup menu should be displayed.
1169 */
1170 int
1171pum_wanted(void)
1172{
1173 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001174 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 return FALSE;
1176
1177 // The display looks bad on a B&W display.
1178 if (t_colors < 8
1179#ifdef FEAT_GUI
1180 && !gui.in_use
1181#endif
1182 )
1183 return FALSE;
1184 return TRUE;
1185}
1186
1187/*
1188 * Return TRUE if there are two or more matches to be shown in the popup menu.
1189 * One if 'completopt' contains "menuone".
1190 */
1191 static int
1192pum_enough_matches(void)
1193{
1194 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001195 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001196
1197 // Don't display the popup menu if there are no matches or there is only
1198 // one (ignoring the original text).
1199 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001200 do
1201 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001202 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001203 break;
1204 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001205 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001206
zeertzjq529b9ad2024-06-05 20:27:06 +02001207 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001208 return (i >= 1);
1209 return (i >= 2);
1210}
1211
Bram Moolenaar3075a452021-11-17 15:51:52 +00001212#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001213/*
1214 * Allocate Dict for the completed item.
1215 * { word, abbr, menu, kind, info }
1216 */
1217 static dict_T *
1218ins_compl_dict_alloc(compl_T *match)
1219{
1220 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1221
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001222 if (dict == NULL)
1223 return NULL;
1224
John Marriott5e6ea922024-11-23 14:01:57 +01001225 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001226 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1227 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1228 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1229 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1230 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1231 dict_add_string(dict, "user_data", (char_u *)"");
1232 else
1233 dict_add_tv(dict, "user_data", &match->cp_user_data);
1234
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001235 return dict;
1236}
1237
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001238/*
1239 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1240 * completion menu is changed.
1241 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001242 static void
1243trigger_complete_changed_event(int cur)
1244{
1245 dict_T *v_event;
1246 dict_T *item;
1247 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001248 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001249
1250 if (recursive)
1251 return;
1252
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001253 if (cur < 0)
1254 item = dict_alloc();
1255 else
1256 item = ins_compl_dict_alloc(compl_curr_match);
1257 if (item == NULL)
1258 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001259 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001260 dict_add_dict(v_event, "completed_item", item);
1261 pum_set_event_info(v_event);
1262 dict_set_items_ro(v_event);
1263
1264 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001265 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001266 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001267 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001268 recursive = FALSE;
1269
Bram Moolenaar3075a452021-11-17 15:51:52 +00001270 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001271}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001272#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001273
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001274/*
glepnira218cc62024-06-03 19:32:39 +02001275 * pumitem qsort compare func
1276 */
1277 static int
zeertzjq8e567472024-06-14 20:04:42 +02001278ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001279{
1280 const int sa = (*(pumitem_T *)a).pum_score;
1281 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001282 const int ia = (*(pumitem_T *)a).pum_idx;
1283 const int ib = (*(pumitem_T *)b).pum_idx;
1284 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001285}
1286
1287/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001288 * Build a popup menu to show the completion matches.
1289 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1290 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001291 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001292 static int
1293ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001294{
1295 compl_T *compl;
1296 compl_T *shown_compl = NULL;
1297 int did_find_shown_match = FALSE;
1298 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001299 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001300 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001301 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001302 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001303 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001304 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1305 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001306 compl_T *match_head = NULL;
1307 compl_T *match_tail = NULL;
1308 compl_T *match_next = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001309
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001310 // Need to build the popup menu list.
1311 compl_match_arraysize = 0;
1312 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001313
glepnira49c0772024-11-30 10:56:30 +01001314 // If the current match is the original text don't find the first
1315 // match after it, don't highlight anything.
1316 if (match_at_original_text(compl_shown_match))
1317 shown_match_ok = TRUE;
1318
1319 if (compl_leader.string != NULL
1320 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1321 && shown_match_ok == FALSE)
1322 compl_shown_match = compl_no_select ? compl_first_match
1323 : compl_first_match->cp_next;
1324
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001325 do
1326 {
glepnird4088ed2024-12-31 10:55:22 +01001327 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001328 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1329 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001330 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001331 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001332
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001333 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001334 && (compl_leader.string == NULL
1335 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001336 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001337 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001338 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001339 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001340 if (match_head == NULL)
1341 match_head = compl;
1342 else
glepnira49c0772024-11-30 10:56:30 +01001343 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001344 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001345
glepnirf400a0c2025-01-23 19:55:14 +01001346 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001347 {
1348 if (compl == compl_shown_match || did_find_shown_match)
1349 {
1350 // This item is the shown match or this is the
1351 // first displayed item after the shown match.
1352 compl_shown_match = compl;
1353 did_find_shown_match = TRUE;
1354 shown_match_ok = TRUE;
1355 }
1356 else
1357 // Remember this displayed match for when the
1358 // shown match is just below it.
1359 shown_compl = compl;
1360 cur = i;
1361 }
glepnirf400a0c2025-01-23 19:55:14 +01001362 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001363 {
1364 if (i == 0)
1365 shown_compl = compl;
1366 // Update the maximum fuzzy score and the shown match
1367 // if the current item's score is higher
zeertzjqd65aa1b2025-01-25 15:29:03 +01001368 if (fuzzy_sort && compl->cp_score > max_fuzzy_score)
glepnira49c0772024-11-30 10:56:30 +01001369 {
1370 did_find_shown_match = TRUE;
1371 max_fuzzy_score = compl->cp_score;
1372 if (!compl_no_select)
1373 compl_shown_match = compl;
1374 }
zeertzjqd65aa1b2025-01-25 15:29:03 +01001375 else if (!fuzzy_sort && i == 0 && !compl_no_select)
glepnirf400a0c2025-01-23 19:55:14 +01001376 compl_shown_match = shown_compl;
glepnira49c0772024-11-30 10:56:30 +01001377
1378 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1379 {
1380 cur = i;
1381 shown_match_ok = TRUE;
1382 }
1383 }
1384 i++;
glepnir80b66202024-11-27 21:53:53 +01001385 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001386
glepnirf400a0c2025-01-23 19:55:14 +01001387 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001388 {
1389 did_find_shown_match = TRUE;
1390
1391 // When the original text is the shown match don't set
1392 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001393 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001394 shown_match_ok = TRUE;
1395
1396 if (!shown_match_ok && shown_compl != NULL)
1397 {
1398 // The shown match isn't displayed, set it to the
1399 // previously displayed match.
1400 compl_shown_match = shown_compl;
1401 shown_match_ok = TRUE;
1402 }
1403 }
glepnira49c0772024-11-30 10:56:30 +01001404 compl = compl->cp_next;
1405 } while (compl != NULL && !is_first_match(compl));
1406
1407 if (compl_match_arraysize == 0)
1408 return -1;
1409
1410 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1411 if (compl_match_array == NULL)
1412 return -1;
1413
1414 compl = match_head;
1415 i = 0;
1416 while (compl != NULL)
1417 {
glepnir6e199932024-12-14 21:13:27 +01001418 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1419 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001420 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1421 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1422 compl_match_array[i].pum_score = compl->cp_score;
1423 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1424 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001425 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1426 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001427 match_next = compl->cp_match_next;
1428 compl->cp_match_next = NULL;
1429 compl = match_next;
1430 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001431
zeertzjqd65aa1b2025-01-25 15:29:03 +01001432 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001433 {
1434 for (i = 0; i < compl_match_arraysize; i++)
1435 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001436 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001437 qsort(compl_match_array, (size_t)compl_match_arraysize,
1438 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001439 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001440 }
glepnira218cc62024-06-03 19:32:39 +02001441
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001442 if (!shown_match_ok) // no displayed match at all
1443 cur = -1;
1444
1445 return cur;
1446}
1447
1448/*
1449 * Show the popup menu for the list of matches.
1450 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1451 */
1452 void
1453ins_compl_show_pum(void)
1454{
1455 int i;
1456 int cur = -1;
1457 colnr_T col;
1458
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001459 if (!pum_wanted() || !pum_enough_matches())
1460 return;
1461
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001462 // Update the screen later, before drawing the popup menu over it.
1463 pum_call_update_screen();
1464
1465 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001466 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001467 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001468 else
1469 {
1470 // popup menu already exists, only need to find the current item.
1471 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001472 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001473 || compl_match_array[i].pum_text
1474 == compl_shown_match->cp_text[CPT_ABBR])
1475 {
1476 cur = i;
1477 break;
1478 }
1479 }
1480
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001481 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001482 {
1483#ifdef FEAT_EVAL
1484 if (compl_started && has_completechanged())
1485 trigger_complete_changed_event(cur);
1486#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001487 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001488 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001489
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001490 // In Replace mode when a $ is displayed at the end of the line only
1491 // part of the screen would be updated. We do need to redraw here.
1492 dollar_vcol = -1;
1493
1494 // Compute the screen column of the start of the completed text.
1495 // Use the cursor to get all wrapping and other settings right.
1496 col = curwin->w_cursor.col;
1497 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001498 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001499 pum_display(compl_match_array, compl_match_arraysize, cur);
1500 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001501
glepnircbb46b42024-02-03 18:11:13 +01001502 // After adding leader, set the current match to shown match.
1503 if (compl_started && compl_curr_match != compl_shown_match)
1504 compl_curr_match = compl_shown_match;
1505
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001506#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001507 if (has_completechanged())
1508 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001509#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001510}
1511
1512#define DICT_FIRST (1) // use just first element in "dict"
1513#define DICT_EXACT (2) // "dict" is the exact name of a file
1514
1515/*
glepnir40c1c332024-06-11 19:37:04 +02001516 * Get current completion leader
1517 */
1518 char_u *
1519ins_compl_leader(void)
1520{
John Marriott5e6ea922024-11-23 14:01:57 +01001521 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1522}
1523
1524/*
1525 * Get current completion leader length
1526 */
1527 size_t
1528ins_compl_leader_len(void)
1529{
1530 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001531}
1532
1533/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001534 * Add any identifiers that match the given pattern "pat" in the list of
1535 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001536 */
1537 static void
1538ins_compl_dictionaries(
1539 char_u *dict_start,
1540 char_u *pat,
1541 int flags, // DICT_FIRST and/or DICT_EXACT
1542 int thesaurus) // Thesaurus completion
1543{
1544 char_u *dict = dict_start;
1545 char_u *ptr;
1546 char_u *buf;
1547 regmatch_T regmatch;
1548 char_u **files;
1549 int count;
1550 int save_p_scs;
1551 int dir = compl_direction;
1552
1553 if (*dict == NUL)
1554 {
1555#ifdef FEAT_SPELL
1556 // When 'dictionary' is empty and spell checking is enabled use
1557 // "spell".
1558 if (!thesaurus && curwin->w_p_spell)
1559 dict = (char_u *)"spell";
1560 else
1561#endif
1562 return;
1563 }
1564
1565 buf = alloc(LSIZE);
1566 if (buf == NULL)
1567 return;
1568 regmatch.regprog = NULL; // so that we can goto theend
1569
1570 // If 'infercase' is set, don't use 'smartcase' here
1571 save_p_scs = p_scs;
1572 if (curbuf->b_p_inf)
1573 p_scs = FALSE;
1574
1575 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1576 // to only match at the start of a line. Otherwise just match the
1577 // pattern. Also need to double backslashes.
1578 if (ctrl_x_mode_line_or_eval())
1579 {
1580 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1581 size_t len;
1582
1583 if (pat_esc == NULL)
1584 goto theend;
1585 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001586 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001587 if (ptr == NULL)
1588 {
1589 vim_free(pat_esc);
1590 goto theend;
1591 }
1592 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1593 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1594 vim_free(pat_esc);
1595 vim_free(ptr);
1596 }
1597 else
1598 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001599 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001600 if (regmatch.regprog == NULL)
1601 goto theend;
1602 }
1603
1604 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1605 regmatch.rm_ic = ignorecase(pat);
1606 while (*dict != NUL && !got_int && !compl_interrupted)
1607 {
1608 // copy one dictionary file name into buf
1609 if (flags == DICT_EXACT)
1610 {
1611 count = 1;
1612 files = &dict;
1613 }
1614 else
1615 {
1616 // Expand wildcards in the dictionary name, but do not allow
1617 // backticks (for security, the 'dict' option may have been set in
1618 // a modeline).
1619 copy_option_part(&dict, buf, LSIZE, ",");
1620# ifdef FEAT_SPELL
1621 if (!thesaurus && STRCMP(buf, "spell") == 0)
1622 count = -1;
1623 else
1624# endif
1625 if (vim_strchr(buf, '`') != NULL
1626 || expand_wildcards(1, &buf, &count, &files,
1627 EW_FILE|EW_SILENT) != OK)
1628 count = 0;
1629 }
1630
1631# ifdef FEAT_SPELL
1632 if (count == -1)
1633 {
1634 // Complete from active spelling. Skip "\<" in the pattern, we
1635 // don't use it as a RE.
1636 if (pat[0] == '\\' && pat[1] == '<')
1637 ptr = pat + 2;
1638 else
1639 ptr = pat;
1640 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1641 }
1642 else
1643# endif
1644 if (count > 0) // avoid warning for using "files" uninit
1645 {
1646 ins_compl_files(count, files, thesaurus, flags,
1647 &regmatch, buf, &dir);
1648 if (flags != DICT_EXACT)
1649 FreeWild(count, files);
1650 }
1651 if (flags != 0)
1652 break;
1653 }
1654
1655theend:
1656 p_scs = save_p_scs;
1657 vim_regfree(regmatch.regprog);
1658 vim_free(buf);
1659}
1660
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001661/*
1662 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1663 * skipping the word at 'skip_word'. Returns OK on success.
1664 */
1665 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001666thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001667 char_u *fname,
1668 char_u **buf_arg,
1669 int dir,
1670 char_u *skip_word)
1671{
1672 int status = OK;
1673 char_u *ptr;
1674 char_u *wstart;
1675
1676 // Add the other matches on the line
1677 ptr = *buf_arg;
1678 while (!got_int)
1679 {
1680 // Find start of the next word. Skip white
1681 // space and punctuation.
1682 ptr = find_word_start(ptr);
1683 if (*ptr == NUL || *ptr == NL)
1684 break;
1685 wstart = ptr;
1686
1687 // Find end of the word.
1688 if (has_mbyte)
1689 // Japanese words may have characters in
1690 // different classes, only separate words
1691 // with single-byte non-word characters.
1692 while (*ptr != NUL)
1693 {
1694 int l = (*mb_ptr2len)(ptr);
1695
1696 if (l < 2 && !vim_iswordc(*ptr))
1697 break;
1698 ptr += l;
1699 }
1700 else
1701 ptr = find_word_end(ptr);
1702
1703 // Add the word. Skip the regexp match.
1704 if (wstart != skip_word)
1705 {
1706 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1707 fname, dir, FALSE);
1708 if (status == FAIL)
1709 break;
1710 }
1711 }
1712
1713 *buf_arg = ptr;
1714 return status;
1715}
1716
1717/*
1718 * Process "count" dictionary/thesaurus "files" and add the text matching
1719 * "regmatch".
1720 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001721 static void
1722ins_compl_files(
1723 int count,
1724 char_u **files,
1725 int thesaurus,
1726 int flags,
1727 regmatch_T *regmatch,
1728 char_u *buf,
1729 int *dir)
1730{
1731 char_u *ptr;
1732 int i;
1733 FILE *fp;
1734 int add_r;
1735
1736 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1737 {
1738 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001739 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001740 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001741 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001742 vim_snprintf((char *)IObuff, IOSIZE,
1743 _("Scanning dictionary: %s"), (char *)files[i]);
1744 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1745 }
1746
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001747 if (fp == NULL)
1748 continue;
1749
1750 // Read dictionary file line by line.
1751 // Check each line for a match.
1752 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001753 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001754 ptr = buf;
1755 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001756 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001757 ptr = regmatch->startp[0];
glepnir6e199932024-12-14 21:13:27 +01001758 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1759 : find_word_end(ptr);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001760 add_r = ins_compl_add_infercase(regmatch->startp[0],
1761 (int)(ptr - regmatch->startp[0]),
1762 p_ic, files[i], *dir, FALSE);
1763 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001764 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001765 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001766 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001767 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001768 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001769 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001770 if (add_r == OK)
1771 // if dir was BACKWARD then honor it just once
1772 *dir = FORWARD;
1773 else if (add_r == FAIL)
1774 break;
1775 // avoid expensive call to vim_regexec() when at end
1776 // of line
1777 if (*ptr == '\n' || got_int)
1778 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001779 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001780 line_breakcheck();
1781 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001782 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001783 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001784 }
1785}
1786
1787/*
1788 * Find the start of the next word.
1789 * Returns a pointer to the first char of the word. Also stops at a NUL.
1790 */
1791 char_u *
1792find_word_start(char_u *ptr)
1793{
1794 if (has_mbyte)
1795 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1796 ptr += (*mb_ptr2len)(ptr);
1797 else
1798 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1799 ++ptr;
1800 return ptr;
1801}
1802
1803/*
1804 * Find the end of the word. Assumes it starts inside a word.
1805 * Returns a pointer to just after the word.
1806 */
1807 char_u *
1808find_word_end(char_u *ptr)
1809{
1810 int start_class;
1811
1812 if (has_mbyte)
1813 {
1814 start_class = mb_get_class(ptr);
1815 if (start_class > 1)
1816 while (*ptr != NUL)
1817 {
1818 ptr += (*mb_ptr2len)(ptr);
1819 if (mb_get_class(ptr) != start_class)
1820 break;
1821 }
1822 }
1823 else
1824 while (vim_iswordc(*ptr))
1825 ++ptr;
1826 return ptr;
1827}
1828
1829/*
1830 * Find the end of the line, omitting CR and NL at the end.
1831 * Returns a pointer to just after the line.
1832 */
1833 static char_u *
1834find_line_end(char_u *ptr)
1835{
1836 char_u *s;
1837
1838 s = ptr + STRLEN(ptr);
1839 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1840 --s;
1841 return s;
1842}
1843
1844/*
1845 * Free the list of completions
1846 */
1847 static void
1848ins_compl_free(void)
1849{
1850 compl_T *match;
1851 int i;
1852
John Marriott5e6ea922024-11-23 14:01:57 +01001853 VIM_CLEAR_STRING(compl_pattern);
1854 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001855
1856 if (compl_first_match == NULL)
1857 return;
1858
1859 ins_compl_del_pum();
1860 pum_clear();
1861
1862 compl_curr_match = compl_first_match;
1863 do
1864 {
1865 match = compl_curr_match;
1866 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001867 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001868 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001869 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001870 vim_free(match->cp_fname);
1871 for (i = 0; i < CPT_COUNT; ++i)
1872 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001873#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001874 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001875#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001876 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001877 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001878 compl_first_match = compl_curr_match = NULL;
1879 compl_shown_match = NULL;
1880 compl_old_match = NULL;
1881}
1882
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001883/*
1884 * Reset/clear the completion state.
1885 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001886 void
1887ins_compl_clear(void)
1888{
1889 compl_cont_status = 0;
1890 compl_started = FALSE;
1891 compl_matches = 0;
glepnir6a38aff2024-12-16 21:56:16 +01001892 compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001893 VIM_CLEAR_STRING(compl_pattern);
1894 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001895 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001896 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001897 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001898#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001899 // clear v:completed_item
1900 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001901#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001902}
1903
1904/*
1905 * Return TRUE when Insert completion is active.
1906 */
1907 int
1908ins_compl_active(void)
1909{
1910 return compl_started;
1911}
1912
1913/*
glepnir8d0bb6d2024-12-24 09:44:35 +01001914 * Return True when wp is the actual completion window
1915 */
1916 int
1917ins_compl_win_active(win_T *wp UNUSED)
1918{
1919 return ins_compl_active()
1920#if defined(FEAT_QUICKFIX)
1921 && (!wp->w_p_pvw
1922# ifdef FEAT_PROP_POPUP
1923 && !(wp->w_popup_flags & POPF_INFO)
1924# endif
1925 )
1926#endif
1927 ;
1928}
1929
1930/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001931 * Selected one of the matches. When FALSE the match was edited or using the
1932 * longest common string.
1933 */
1934 int
1935ins_compl_used_match(void)
1936{
1937 return compl_used_match;
1938}
1939
1940/*
1941 * Initialize get longest common string.
1942 */
1943 void
1944ins_compl_init_get_longest(void)
1945{
1946 compl_get_longest = FALSE;
1947}
1948
1949/*
1950 * Returns TRUE when insert completion is interrupted.
1951 */
1952 int
1953ins_compl_interrupted(void)
1954{
1955 return compl_interrupted;
1956}
1957
1958/*
1959 * Returns TRUE if the <Enter> key selects a match in the completion popup
1960 * menu.
1961 */
1962 int
1963ins_compl_enter_selects(void)
1964{
1965 return compl_enter_selects;
1966}
1967
1968/*
1969 * Return the column where the text starts that is being completed
1970 */
1971 colnr_T
1972ins_compl_col(void)
1973{
1974 return compl_col;
1975}
1976
1977/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001978 * Return the length in bytes of the text being completed
1979 */
1980 int
1981ins_compl_len(void)
1982{
1983 return compl_length;
1984}
1985
1986/*
glepniredd4ac32025-01-29 18:53:51 +01001987 * Return TRUE when preinsert is set otherwise FALSE.
1988 */
1989 static int
1990ins_compl_has_preinsert(void)
1991{
1992 return (get_cot_flags() & (COT_PREINSERT | COT_FUZZY)) == COT_PREINSERT;
1993}
1994
1995/*
1996 * Returns TRUE if the pre-insert effect is valid and the cursor is within
1997 * the `compl_ins_end_col` range.
1998 */
1999 int
2000ins_compl_preinsert_effect(void)
2001{
2002 if (!ins_compl_has_preinsert())
2003 return FALSE;
2004
2005 return curwin->w_cursor.col < compl_ins_end_col;
2006}
2007
2008/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002009 * Delete one character before the cursor and show the subset of the matches
2010 * that match the word that is now before the cursor.
2011 * Returns the character to be used, NUL if the work is done and another char
2012 * to be got from the user.
2013 */
2014 int
2015ins_compl_bs(void)
2016{
2017 char_u *line;
2018 char_u *p;
2019
glepniredd4ac32025-01-29 18:53:51 +01002020 if (ins_compl_preinsert_effect())
2021 ins_compl_delete();
2022
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002023 line = ml_get_curline();
2024 p = line + curwin->w_cursor.col;
2025 MB_PTR_BACK(line, p);
2026
2027 // Stop completion when the whole word was deleted. For Omni completion
2028 // allow the word to be deleted, we won't match everything.
2029 // Respect the 'backspace' option.
2030 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002031 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2032 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002033 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2034 - compl_length < 0))
2035 return K_BS;
2036
2037 // Deleted more than what was used to find matches or didn't finish
2038 // finding all matches: need to look for matches all over again.
2039 if (curwin->w_cursor.col <= compl_col + compl_length
2040 || ins_compl_need_restart())
2041 ins_compl_restart();
2042
John Marriott5e6ea922024-11-23 14:01:57 +01002043 VIM_CLEAR_STRING(compl_leader);
2044 compl_leader.length = (size_t)((p - line) - compl_col);
2045 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2046 if (compl_leader.string == NULL)
2047 {
2048 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002049 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002050 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002051
2052 ins_compl_new_leader();
2053 if (compl_shown_match != NULL)
2054 // Make sure current match is not a hidden item.
2055 compl_curr_match = compl_shown_match;
2056 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002057}
2058
2059/*
2060 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2061 * be called.
2062 */
2063 static int
2064ins_compl_need_restart(void)
2065{
2066 // Return TRUE if we didn't complete finding matches or when the
2067 // 'completefunc' returned "always" in the "refresh" dictionary item.
2068 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002069 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002070 && compl_opt_refresh_always);
2071}
2072
2073/*
2074 * Called after changing "compl_leader".
2075 * Show the popup menu with a different set of matches.
2076 * May also search for matches again if the previous search was interrupted.
2077 */
2078 static void
2079ins_compl_new_leader(void)
2080{
2081 ins_compl_del_pum();
2082 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002083 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002084 compl_used_match = FALSE;
2085
2086 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01002087 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002088 else
2089 {
2090#ifdef FEAT_SPELL
2091 spell_bad_len = 0; // need to redetect bad word
2092#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002093 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002094 // the popup menu display the changed text before the cursor. Set
2095 // "compl_restarting" to avoid that the first match is inserted.
2096 pum_call_update_screen();
2097#ifdef FEAT_GUI
2098 if (gui.in_use)
2099 {
2100 // Show the cursor after the match, not after the redrawn text.
2101 setcursor();
2102 out_flush_cursor(FALSE, FALSE);
2103 }
2104#endif
2105 compl_restarting = TRUE;
2106 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2107 compl_cont_status = 0;
2108 compl_restarting = FALSE;
2109 }
2110
2111 compl_enter_selects = !compl_used_match;
2112
2113 // Show the popup menu with a different set of matches.
2114 ins_compl_show_pum();
2115
2116 // Don't let Enter select the original text when there is no popup menu.
2117 if (compl_match_array == NULL)
2118 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002119 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2120 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002121}
2122
2123/*
2124 * Return the length of the completion, from the completion start column to
2125 * the cursor column. Making sure it never goes below zero.
2126 */
2127 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002128get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002129{
2130 int off = (int)curwin->w_cursor.col - (int)compl_col;
2131
2132 if (off < 0)
2133 return 0;
2134 return off;
2135}
2136
2137/*
2138 * Append one character to the match leader. May reduce the number of
2139 * matches.
2140 */
2141 void
2142ins_compl_addleader(int c)
2143{
2144 int cc;
2145
glepniredd4ac32025-01-29 18:53:51 +01002146 if (ins_compl_preinsert_effect())
2147 ins_compl_delete();
2148
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002149 if (stop_arrow() == FAIL)
2150 return;
2151 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2152 {
2153 char_u buf[MB_MAXBYTES + 1];
2154
2155 (*mb_char2bytes)(c, buf);
2156 buf[cc] = NUL;
2157 ins_char_bytes(buf, cc);
2158 if (compl_opt_refresh_always)
2159 AppendToRedobuff(buf);
2160 }
2161 else
2162 {
2163 ins_char(c);
2164 if (compl_opt_refresh_always)
2165 AppendCharToRedobuff(c);
2166 }
2167
2168 // If we didn't complete finding matches we must search again.
2169 if (ins_compl_need_restart())
2170 ins_compl_restart();
2171
2172 // When 'always' is set, don't reset compl_leader. While completing,
2173 // cursor doesn't point original position, changing compl_leader would
2174 // break redo.
2175 if (!compl_opt_refresh_always)
2176 {
John Marriott5e6ea922024-11-23 14:01:57 +01002177 VIM_CLEAR_STRING(compl_leader);
2178 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2179 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2180 compl_leader.length);
2181 if (compl_leader.string == NULL)
2182 {
2183 compl_leader.length = 0;
2184 return;
2185 }
2186
2187 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002188 }
2189}
2190
2191/*
2192 * Setup for finding completions again without leaving CTRL-X mode. Used when
2193 * BS or a key was typed while still searching for matches.
2194 */
2195 static void
2196ins_compl_restart(void)
2197{
2198 ins_compl_free();
2199 compl_started = FALSE;
2200 compl_matches = 0;
2201 compl_cont_status = 0;
2202 compl_cont_mode = 0;
2203}
2204
2205/*
2206 * Set the first match, the original text.
2207 */
2208 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002209ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002210{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002211 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002212 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2213 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002214 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002215 {
John Marriott5e6ea922024-11-23 14:01:57 +01002216 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002217 if (p != NULL)
2218 {
John Marriott5e6ea922024-11-23 14:01:57 +01002219 VIM_CLEAR_STRING(compl_first_match->cp_str);
2220 compl_first_match->cp_str.string = p;
2221 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002222 }
2223 }
2224 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002225 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002226 {
John Marriott5e6ea922024-11-23 14:01:57 +01002227 char_u *p = vim_strnsave(str, len);
2228 if (p != NULL)
2229 {
2230 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2231 compl_first_match->cp_prev->cp_str.string = p;
2232 compl_first_match->cp_prev->cp_str.length = len;
2233 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002234 }
2235}
2236
2237/*
2238 * Append one character to the match leader. May reduce the number of
2239 * matches.
2240 */
2241 void
2242ins_compl_addfrommatch(void)
2243{
2244 char_u *p;
2245 int len = (int)curwin->w_cursor.col - (int)compl_col;
2246 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002247
John Marriott5e6ea922024-11-23 14:01:57 +01002248 p = compl_shown_match->cp_str.string;
2249 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002250 {
John Marriott5e6ea922024-11-23 14:01:57 +01002251 size_t plen;
2252 compl_T *cp;
2253
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002254 // When still at the original match use the first entry that matches
2255 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002256 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002257 return;
2258
2259 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002260 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002261 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002262 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002263 {
John Marriott5e6ea922024-11-23 14:01:57 +01002264 if (compl_leader.string == NULL
2265 || ins_compl_equal(cp, compl_leader.string,
2266 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002267 {
John Marriott5e6ea922024-11-23 14:01:57 +01002268 p = cp->cp_str.string;
2269 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002270 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002271 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002272 }
John Marriott5e6ea922024-11-23 14:01:57 +01002273 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002274 return;
2275 }
2276 p += len;
2277 c = PTR2CHAR(p);
2278 ins_compl_addleader(c);
2279}
2280
2281/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002282 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002283 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2284 * compl_cont_mode and compl_cont_status.
2285 * Returns TRUE when the character is not to be inserted.
2286 */
2287 static int
2288set_ctrl_x_mode(int c)
2289{
2290 int retval = FALSE;
2291
2292 switch (c)
2293 {
2294 case Ctrl_E:
2295 case Ctrl_Y:
2296 // scroll the window one line up or down
2297 ctrl_x_mode = CTRL_X_SCROLL;
2298 if (!(State & REPLACE_FLAG))
2299 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2300 else
2301 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2302 edit_submode_pre = NULL;
2303 showmode();
2304 break;
2305 case Ctrl_L:
2306 // complete whole line
2307 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2308 break;
2309 case Ctrl_F:
2310 // complete filenames
2311 ctrl_x_mode = CTRL_X_FILES;
2312 break;
2313 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002314 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002315 ctrl_x_mode = CTRL_X_DICTIONARY;
2316 break;
2317 case Ctrl_R:
2318 // Register insertion without exiting CTRL-X mode
2319 // Simply allow ^R to happen without affecting ^X mode
2320 break;
2321 case Ctrl_T:
2322 // complete words from a thesaurus
2323 ctrl_x_mode = CTRL_X_THESAURUS;
2324 break;
2325#ifdef FEAT_COMPL_FUNC
2326 case Ctrl_U:
2327 // user defined completion
2328 ctrl_x_mode = CTRL_X_FUNCTION;
2329 break;
2330 case Ctrl_O:
2331 // omni completion
2332 ctrl_x_mode = CTRL_X_OMNI;
2333 break;
2334#endif
2335 case 's':
2336 case Ctrl_S:
2337 // complete spelling suggestions
2338 ctrl_x_mode = CTRL_X_SPELL;
2339#ifdef FEAT_SPELL
2340 ++emsg_off; // Avoid getting the E756 error twice.
2341 spell_back_to_badword();
2342 --emsg_off;
2343#endif
2344 break;
2345 case Ctrl_RSB:
2346 // complete tag names
2347 ctrl_x_mode = CTRL_X_TAGS;
2348 break;
2349#ifdef FEAT_FIND_ID
2350 case Ctrl_I:
2351 case K_S_TAB:
2352 // complete keywords from included files
2353 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2354 break;
2355 case Ctrl_D:
2356 // complete definitions from included files
2357 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2358 break;
2359#endif
2360 case Ctrl_V:
2361 case Ctrl_Q:
2362 // complete vim commands
2363 ctrl_x_mode = CTRL_X_CMDLINE;
2364 break;
2365 case Ctrl_Z:
2366 // stop completion
2367 ctrl_x_mode = CTRL_X_NORMAL;
2368 edit_submode = NULL;
2369 showmode();
2370 retval = TRUE;
2371 break;
2372 case Ctrl_P:
2373 case Ctrl_N:
2374 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2375 // just started ^X mode, or there were enough ^X's to cancel
2376 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2377 // do normal expansion when interrupting a different mode (say
2378 // ^X^F^X^P or ^P^X^X^P, see below)
2379 // nothing changes if interrupting mode 0, (eg, the flag
2380 // doesn't change when going to ADDING mode -- Acevedo
2381 if (!(compl_cont_status & CONT_INTRPT))
2382 compl_cont_status |= CONT_LOCAL;
2383 else if (compl_cont_mode != 0)
2384 compl_cont_status &= ~CONT_LOCAL;
2385 // FALLTHROUGH
2386 default:
2387 // If we have typed at least 2 ^X's... for modes != 0, we set
2388 // compl_cont_status = 0 (eg, as if we had just started ^X
2389 // mode).
2390 // For mode 0, we set "compl_cont_mode" to an impossible
2391 // value, in both cases ^X^X can be used to restart the same
2392 // mode (avoiding ADDING mode).
2393 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2394 // 'complete' and local ^P expansions respectively.
2395 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2396 // mode -- Acevedo
2397 if (c == Ctrl_X)
2398 {
2399 if (compl_cont_mode != 0)
2400 compl_cont_status = 0;
2401 else
2402 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2403 }
2404 ctrl_x_mode = CTRL_X_NORMAL;
2405 edit_submode = NULL;
2406 showmode();
2407 break;
2408 }
2409
2410 return retval;
2411}
2412
2413/*
glepnir1c5a1202024-12-04 20:27:34 +01002414 * Trigger CompleteDone event and adds relevant information to v:event
2415 */
2416 static void
2417trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2418{
2419#if defined(FEAT_EVAL)
2420 save_v_event_T save_v_event;
2421 dict_T *v_event = get_v_event(&save_v_event);
2422 char_u *mode_str = NULL;
2423
2424 mode = mode & ~CTRL_X_WANT_IDENT;
2425 if (ctrl_x_mode_names[mode])
2426 mode_str = (char_u *)ctrl_x_mode_names[mode];
2427
2428 (void)dict_add_string(v_event, "complete_word",
2429 word == NULL ? (char_u *)"" : word);
2430 (void)dict_add_string(v_event, "complete_type",
2431 mode_str != NULL ? mode_str : (char_u *)"");
2432
2433 dict_set_items_ro(v_event);
2434#endif
2435 ins_apply_autocmds(EVENT_COMPLETEDONE);
2436
2437#if defined(FEAT_EVAL)
2438 restore_v_event(v_event, &save_v_event);
2439#endif
2440}
2441
2442/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002443 * Stop insert completion mode
2444 */
2445 static int
2446ins_compl_stop(int c, int prev_mode, int retval)
2447{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002448 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002449 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002450
2451 // Get here when we have finished typing a sequence of ^N and
2452 // ^P or other completion characters in CTRL-X mode. Free up
2453 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002454 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002455 {
John Marriott5e6ea922024-11-23 14:01:57 +01002456 char_u *ptr;
2457
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002458 // If any of the original typed text has been changed, eg when
2459 // ignorecase is set, we must add back-spaces to the redo
2460 // buffer. We add as few as necessary to delete just the part
2461 // of the original text that has changed.
2462 // When using the longest match, edited the match or used
2463 // CTRL-E then don't use the current match.
2464 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002465 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002466 else
2467 ptr = NULL;
2468 ins_compl_fixRedoBufForLeader(ptr);
2469 }
2470
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002471 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002472
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002473 // When completing whole lines: fix indent for 'cindent'.
2474 // Otherwise, break line if it's too long.
2475 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2476 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002477 // re-indent the current line
2478 if (want_cindent)
2479 {
2480 do_c_expr_indent();
2481 want_cindent = FALSE; // don't do it again
2482 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002483 }
2484 else
2485 {
2486 int prev_col = curwin->w_cursor.col;
2487
2488 // put the cursor on the last char, for 'tw' formatting
2489 if (prev_col > 0)
2490 dec_cursor();
2491 // only format when something was inserted
2492 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2493 insertchar(NUL, 0, -1);
2494 if (prev_col > 0
2495 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2496 inc_cursor();
2497 }
2498
2499 // If the popup menu is displayed pressing CTRL-Y means accepting
2500 // the selection without inserting anything. When
2501 // compl_enter_selects is set the Enter key does the same.
2502 if ((c == Ctrl_Y || (compl_enter_selects
2503 && (c == CAR || c == K_KENTER || c == NL)))
2504 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002505 {
2506 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002507 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002508 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002509
2510 // CTRL-E means completion is Ended, go back to the typed text.
2511 // but only do this, if the Popup is still visible
2512 if (c == Ctrl_E)
2513 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002514 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002515 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002516
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002517 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002518 if (compl_leader.string != NULL)
2519 {
2520 p = compl_leader.string;
2521 plen = compl_leader.length;
2522 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002523 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002524 {
2525 p = compl_orig_text.string;
2526 plen = compl_orig_text.length;
2527 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002528 if (p != NULL)
2529 {
2530 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002531
John Marriott5e6ea922024-11-23 14:01:57 +01002532 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002533 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002534 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002535 retval = TRUE;
2536 }
2537
glepnir001c26c2025-02-02 09:36:22 +01002538 if ((c == Ctrl_W || c == Ctrl_U) && ins_compl_preinsert_effect())
2539 ins_compl_delete();
2540
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002541 auto_format(FALSE, TRUE);
2542
2543 // Trigger the CompleteDonePre event to give scripts a chance to
2544 // act upon the completion before clearing the info, and restore
2545 // ctrl_x_mode, so that complete_info() can be used.
2546 ctrl_x_mode = prev_mode;
2547 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2548
2549 ins_compl_free();
2550 compl_started = FALSE;
2551 compl_matches = 0;
2552 if (!shortmess(SHM_COMPLETIONMENU))
2553 msg_clr_cmdline(); // necessary for "noshowmode"
2554 ctrl_x_mode = CTRL_X_NORMAL;
2555 compl_enter_selects = FALSE;
2556 if (edit_submode != NULL)
2557 {
2558 edit_submode = NULL;
2559 showmode();
2560 }
2561
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002562 if (c == Ctrl_C && cmdwin_type != 0)
2563 // Avoid the popup menu remains displayed when leaving the
2564 // command line window.
2565 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002566 // Indent now if a key was typed that is in 'cinkeys'.
2567 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2568 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002569 // Trigger the CompleteDone event to give scripts a chance to act
2570 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002571 trigger_complete_done_event(prev_mode, word);
2572 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002573
2574 return retval;
2575}
2576
2577/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002578 * Prepare for Insert mode completion, or stop it.
2579 * Called just after typing a character in Insert mode.
2580 * Returns TRUE when the character is not to be inserted;
2581 */
2582 int
2583ins_compl_prep(int c)
2584{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002585 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002586 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002587
2588 // Forget any previous 'special' messages if this is actually
2589 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2590 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2591 edit_submode_extra = NULL;
2592
zeertzjq440d4cb2023-03-02 17:51:32 +00002593 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002594 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002595 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002596 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002597 return retval;
2598
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002599#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002600 // Ignore mouse events in a popup window
2601 if (is_mouse_key(c))
2602 {
2603 // Ignore drag and release events, the position does not need to be in
2604 // the popup and it may have just closed.
2605 if (c == K_LEFTRELEASE
2606 || c == K_LEFTRELEASE_NM
2607 || c == K_MIDDLERELEASE
2608 || c == K_RIGHTRELEASE
2609 || c == K_X1RELEASE
2610 || c == K_X2RELEASE
2611 || c == K_LEFTDRAG
2612 || c == K_MIDDLEDRAG
2613 || c == K_RIGHTDRAG
2614 || c == K_X1DRAG
2615 || c == K_X2DRAG)
2616 return retval;
2617 if (popup_visible)
2618 {
2619 int row = mouse_row;
2620 int col = mouse_col;
2621 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2622
2623 if (wp != NULL && WIN_IS_POPUP(wp))
2624 return retval;
2625 }
2626 }
2627#endif
2628
zeertzjqdca29d92021-08-31 19:12:51 +02002629 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2630 {
2631 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2632 || !vim_is_ctrl_x_key(c))
2633 {
2634 // Not starting another completion mode.
2635 ctrl_x_mode = CTRL_X_CMDLINE;
2636
2637 // CTRL-X CTRL-Z should stop completion without inserting anything
2638 if (c == Ctrl_Z)
2639 retval = TRUE;
2640 }
2641 else
2642 {
2643 ctrl_x_mode = CTRL_X_CMDLINE;
2644
2645 // Other CTRL-X keys first stop completion, then start another
2646 // completion mode.
2647 ins_compl_prep(' ');
2648 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2649 }
2650 }
2651
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002652 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002653 if (ctrl_x_mode_not_defined_yet()
2654 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002655 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002656 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002657 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002658 }
2659
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002660 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002661 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2662 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002663 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002664 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002665 {
2666 // We're already in CTRL-X mode, do we stay in it?
2667 if (!vim_is_ctrl_x_key(c))
2668 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002669 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002670 ctrl_x_mode = CTRL_X_NORMAL;
2671 else
2672 ctrl_x_mode = CTRL_X_FINISHED;
2673 edit_submode = NULL;
2674 }
2675 showmode();
2676 }
2677
2678 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2679 {
2680 // Show error message from attempted keyword completion (probably
2681 // 'Pattern not found') until another key is hit, then go back to
2682 // showing what mode we are in.
2683 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002684 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002685 && c != Ctrl_R && !ins_compl_pum_key(c))
2686 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002687 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002688 }
2689 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2690 // Trigger the CompleteDone event to give scripts a chance to act
2691 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002692 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002693
LemonBoy2bf52dd2022-04-09 18:17:34 +01002694 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002695
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002696 // reset continue_* if we left expansion-mode, if we stay they'll be
2697 // (re)set properly in ins_complete()
2698 if (!vim_is_ctrl_x_key(c))
2699 {
2700 compl_cont_status = 0;
2701 compl_cont_mode = 0;
2702 }
2703
2704 return retval;
2705}
2706
2707/*
2708 * Fix the redo buffer for the completion leader replacing some of the typed
2709 * text. This inserts backspaces and appends the changed text.
2710 * "ptr" is the known leader text or NUL.
2711 */
2712 static void
2713ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2714{
John Marriott5e6ea922024-11-23 14:01:57 +01002715 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002716 char_u *p;
2717 char_u *ptr = ptr_arg;
2718
2719 if (ptr == NULL)
2720 {
John Marriott5e6ea922024-11-23 14:01:57 +01002721 if (compl_leader.string != NULL)
2722 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002723 else
2724 return; // nothing to do
2725 }
John Marriott5e6ea922024-11-23 14:01:57 +01002726 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002727 {
John Marriott5e6ea922024-11-23 14:01:57 +01002728 p = compl_orig_text.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002729 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2730 ;
2731 if (len > 0)
2732 len -= (*mb_head_off)(p, p + len);
2733 for (p += len; *p != NUL; MB_PTR_ADV(p))
2734 AppendCharToRedobuff(K_BS);
2735 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002736 if (ptr != NULL)
2737 AppendToRedobuffLit(ptr + len, -1);
2738}
2739
2740/*
2741 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2742 * (depending on flag) starting from buf and looking for a non-scanned
2743 * buffer (other than curbuf). curbuf is special, if it is called with
2744 * buf=curbuf then it has to be the first call for a given flag/expansion.
2745 *
2746 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2747 */
2748 static buf_T *
2749ins_compl_next_buf(buf_T *buf, int flag)
2750{
2751 static win_T *wp = NULL;
2752
2753 if (flag == 'w') // just windows
2754 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002755 if (buf == curbuf || !win_valid(wp))
2756 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002757 wp = curwin;
2758 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2759 && wp->w_buffer->b_scanned)
2760 ;
2761 buf = wp->w_buffer;
2762 }
2763 else
2764 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2765 // (unlisted buffers)
2766 // When completing whole lines skip unloaded buffers.
2767 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2768 && ((flag == 'U'
2769 ? buf->b_p_bl
2770 : (!buf->b_p_bl
2771 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2772 || buf->b_scanned))
2773 ;
2774 return buf;
2775}
2776
2777#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002778
2779# ifdef FEAT_EVAL
2780static callback_T cfu_cb; // 'completefunc' callback function
2781static callback_T ofu_cb; // 'omnifunc' callback function
2782static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2783# endif
2784
2785/*
2786 * Copy a global callback function to a buffer local callback.
2787 */
2788 static void
2789copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2790{
2791 free_callback(bufcb);
2792 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2793 copy_callback(bufcb, globcb);
2794}
2795
2796/*
2797 * Parse the 'completefunc' option value and set the callback function.
2798 * Invoked when the 'completefunc' option is set. The option value can be a
2799 * name of a function (string), or function(<name>) or funcref(<name>) or a
2800 * lambda expression.
2801 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002802 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002803did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002804{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002805 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2806 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002807
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002808 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002809
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002810 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002811}
2812
2813/*
2814 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002815 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002816 */
2817 void
2818set_buflocal_cfu_callback(buf_T *buf UNUSED)
2819{
2820# ifdef FEAT_EVAL
2821 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2822# endif
2823}
2824
2825/*
2826 * Parse the 'omnifunc' option value and set the callback function.
2827 * Invoked when the 'omnifunc' option is set. The option value can be a
2828 * name of a function (string), or function(<name>) or funcref(<name>) or a
2829 * lambda expression.
2830 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002831 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002832did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002833{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002834 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2835 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002836
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002837 set_buflocal_ofu_callback(curbuf);
2838 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002839}
2840
2841/*
2842 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002843 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002844 */
2845 void
2846set_buflocal_ofu_callback(buf_T *buf UNUSED)
2847{
2848# ifdef FEAT_EVAL
2849 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2850# endif
2851}
2852
2853/*
2854 * Parse the 'thesaurusfunc' option value and set the callback function.
2855 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2856 * name of a function (string), or function(<name>) or funcref(<name>) or a
2857 * lambda expression.
2858 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002859 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002860did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002861{
2862 int retval;
2863
zeertzjq6eda2692024-11-03 09:23:33 +01002864 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002865 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002866 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2867 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002868 else
2869 {
2870 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002871 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002872 // when using :set, free the local callback
2873 if (!(args->os_flags & OPT_GLOBAL))
2874 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002875 }
2876
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002877 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002878}
2879
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002880/*
2881 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002882 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002883 */
2884 int
2885set_ref_in_insexpand_funcs(int copyID)
2886{
2887 int abort = FALSE;
2888
2889 abort = set_ref_in_callback(&cfu_cb, copyID);
2890 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2891 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2892
2893 return abort;
2894}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002895
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002896/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002897 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002898 */
2899 static char_u *
2900get_complete_funcname(int type)
2901{
2902 switch (type)
2903 {
2904 case CTRL_X_FUNCTION:
2905 return curbuf->b_p_cfu;
2906 case CTRL_X_OMNI:
2907 return curbuf->b_p_ofu;
2908 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002909 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002910 default:
2911 return (char_u *)"";
2912 }
2913}
2914
2915/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002916 * Get the callback to use for insert mode completion.
2917 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002918 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002919get_insert_callback(int type)
2920{
2921 if (type == CTRL_X_FUNCTION)
2922 return &curbuf->b_cfu_cb;
2923 if (type == CTRL_X_OMNI)
2924 return &curbuf->b_ofu_cb;
2925 // CTRL_X_THESAURUS
2926 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2927}
2928
2929/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002930 * Execute user defined complete function 'completefunc', 'omnifunc' or
2931 * 'thesaurusfunc', and get matches in "matches".
2932 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002933 */
2934 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002935expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002936{
2937 list_T *matchlist = NULL;
2938 dict_T *matchdict = NULL;
2939 typval_T args[3];
2940 char_u *funcname;
2941 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002942 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002943 typval_T rettv;
2944 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002945 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002946
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002947 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002948 if (*funcname == NUL)
2949 return;
2950
2951 // Call 'completefunc' to obtain the list of matches.
2952 args[0].v_type = VAR_NUMBER;
2953 args[0].vval.v_number = 0;
2954 args[1].v_type = VAR_STRING;
2955 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2956 args[2].v_type = VAR_UNKNOWN;
2957
2958 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002959 // Lock the text to avoid weird things from happening. Also disallow
2960 // switching to another window, it should not be needed and may end up in
2961 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002962 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002963
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002964 cb = get_insert_callback(type);
2965 retval = call_callback(cb, 0, &rettv, 2, args);
2966
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002967 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002968 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002969 {
2970 switch (rettv.v_type)
2971 {
2972 case VAR_LIST:
2973 matchlist = rettv.vval.v_list;
2974 break;
2975 case VAR_DICT:
2976 matchdict = rettv.vval.v_dict;
2977 break;
2978 case VAR_SPECIAL:
2979 if (rettv.vval.v_number == VVAL_NONE)
2980 compl_opt_suppress_empty = TRUE;
2981 // FALLTHROUGH
2982 default:
2983 // TODO: Give error message?
2984 clear_tv(&rettv);
2985 break;
2986 }
2987 }
zeertzjqcfe45652022-05-27 17:26:55 +01002988 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002989
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002990 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002991 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002992 validate_cursor();
2993 if (!EQUAL_POS(curwin->w_cursor, pos))
2994 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002995 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002996 goto theend;
2997 }
2998
2999 if (matchlist != NULL)
3000 ins_compl_add_list(matchlist);
3001 else if (matchdict != NULL)
3002 ins_compl_add_dict(matchdict);
3003
3004theend:
3005 // Restore State, it might have been changed.
3006 State = save_State;
3007
3008 if (matchdict != NULL)
3009 dict_unref(matchdict);
3010 if (matchlist != NULL)
3011 list_unref(matchlist);
3012}
3013#endif // FEAT_COMPL_FUNC
3014
3015#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003016
3017 static inline int
3018get_user_highlight_attr(char_u *hlname)
3019{
3020 if (hlname != NULL && *hlname != NUL)
3021 return syn_name2attr(hlname);
3022 return -1;
3023}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003024/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003025 * Add a match to the list of matches from a typeval_T.
3026 * If the given string is already in the list of completions, then return
3027 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3028 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003029 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003030 */
3031 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003032ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003033{
3034 char_u *word;
3035 int dup = FALSE;
3036 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003037 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003038 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003039 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003040 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003041 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003042 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003043 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003044
Bram Moolenaar08928322020-01-04 14:32:48 +01003045 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003046 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3047 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003048 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3049 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3050 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3051 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3052 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003053
glepnir0fe17f82024-10-08 22:26:44 +02003054 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003055 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003056
3057 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003058 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003059
Bram Moolenaard61efa52022-07-23 09:52:04 +01003060 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3061 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3062 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003063 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003064 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3065 dup = dict_get_number(tv->vval.v_dict, "dup");
3066 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3067 empty = dict_get_number(tv->vval.v_dict, "empty");
3068 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3069 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003070 flags |= CP_EQUAL;
3071 }
3072 else
3073 {
3074 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003075 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003076 }
3077 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003078 {
3079 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003080 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003081 }
glepnir508e7852024-07-25 21:39:08 +02003082 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01003083 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003084 if (status != OK)
3085 clear_tv(&user_data);
3086 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003087}
3088
3089/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003090 * Add completions from a list.
3091 */
3092 static void
3093ins_compl_add_list(list_T *list)
3094{
3095 listitem_T *li;
3096 int dir = compl_direction;
3097
3098 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003099 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003100 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003101 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003102 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003103 // if dir was BACKWARD then honor it just once
3104 dir = FORWARD;
3105 else if (did_emsg)
3106 break;
3107 }
3108}
3109
3110/*
3111 * Add completions from a dict.
3112 */
3113 static void
3114ins_compl_add_dict(dict_T *dict)
3115{
3116 dictitem_T *di_refresh;
3117 dictitem_T *di_words;
3118
3119 // Check for optional "refresh" item.
3120 compl_opt_refresh_always = FALSE;
3121 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3122 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3123 {
3124 char_u *v = di_refresh->di_tv.vval.v_string;
3125
3126 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3127 compl_opt_refresh_always = TRUE;
3128 }
3129
3130 // Add completions from a "words" list.
3131 di_words = dict_find(dict, (char_u *)"words", 5);
3132 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3133 ins_compl_add_list(di_words->di_tv.vval.v_list);
3134}
3135
3136/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003137 * Start completion for the complete() function.
3138 * "startcol" is where the matched text starts (1 is first column).
3139 * "list" is the list of matches.
3140 */
3141 static void
3142set_completion(colnr_T startcol, list_T *list)
3143{
3144 int save_w_wrow = curwin->w_wrow;
3145 int save_w_leftcol = curwin->w_leftcol;
3146 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003147 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003148 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3149 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3150 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003151
3152 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003153 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003154 ins_compl_prep(' ');
3155 ins_compl_clear();
3156 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003157 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003158
3159 compl_direction = FORWARD;
3160 if (startcol > curwin->w_cursor.col)
3161 startcol = curwin->w_cursor.col;
3162 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003163 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003164 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3165 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003166 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3167 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003168 if (p_ic)
3169 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003170 if (compl_orig_text.string == NULL)
3171 {
3172 compl_orig_text.length = 0;
3173 return;
3174 }
3175 compl_orig_text.length = (size_t)compl_length;
3176 if (ins_compl_add(compl_orig_text.string,
3177 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3178 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003179 return;
3180
3181 ctrl_x_mode = CTRL_X_EVAL;
3182
3183 ins_compl_add_list(list);
3184 compl_matches = ins_compl_make_cyclic();
3185 compl_started = TRUE;
3186 compl_used_match = TRUE;
3187 compl_cont_status = 0;
3188
3189 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003190 int no_select = compl_no_select || compl_longest;
3191 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003192 {
3193 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003194 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003195 // Down/Up has no real effect.
3196 ins_complete(K_UP, FALSE);
3197 }
3198 else
3199 ins_complete(Ctrl_N, FALSE);
3200 compl_enter_selects = compl_no_insert;
3201
3202 // Lazily show the popup menu, unless we got interrupted.
3203 if (!compl_interrupted)
3204 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003205 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003206 out_flush();
3207}
3208
3209/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003210 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003211 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003212 void
3213f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003214{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003215 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003216
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003217 if (in_vim9script()
3218 && (check_for_number_arg(argvars, 0) == FAIL
3219 || check_for_list_arg(argvars, 1) == FAIL))
3220 return;
3221
Bram Moolenaar24959102022-05-07 20:01:16 +01003222 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003223 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003224 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003225 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003226 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003227
3228 // Check for undo allowed here, because if something was already inserted
3229 // the line was already saved for undo and this check isn't done.
3230 if (!undo_allowed())
3231 return;
3232
Bram Moolenaard83392a2022-09-01 12:22:46 +01003233 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003234 {
3235 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3236 if (startcol > 0)
3237 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003238 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003239}
3240
3241/*
3242 * "complete_add()" function
3243 */
3244 void
3245f_complete_add(typval_T *argvars, typval_T *rettv)
3246{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003247 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003248 return;
3249
Bram Moolenaar440cf092021-04-03 20:13:30 +02003250 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003251}
3252
3253/*
3254 * "complete_check()" function
3255 */
3256 void
3257f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3258{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003259 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003260 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003261
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003262 ins_compl_check_keys(0, TRUE);
3263 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003264
3265 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003266}
3267
3268/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003269 * Return Insert completion mode name string
3270 */
3271 static char_u *
3272ins_compl_mode(void)
3273{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003274 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003275 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3276
3277 return (char_u *)"";
3278}
3279
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003280/*
3281 * Assign the sequence number to all the completion matches which don't have
3282 * one assigned yet.
3283 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003284 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003285ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003286{
3287 int number = 0;
3288 compl_T *match;
3289
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003290 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003291 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003292 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003293 // This should normally succeed already at the first loop
3294 // cycle, so it's fast!
3295 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003296 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003297 if (match->cp_number != -1)
3298 {
3299 number = match->cp_number;
3300 break;
3301 }
3302 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003303 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003304 for (match = match->cp_next;
3305 match != NULL && match->cp_number == -1;
3306 match = match->cp_next)
3307 match->cp_number = ++number;
3308 }
3309 else // BACKWARD
3310 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003311 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003312 // number. This should normally succeed already at the
3313 // first loop cycle, so it's fast!
3314 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003315 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003316 if (match->cp_number != -1)
3317 {
3318 number = match->cp_number;
3319 break;
3320 }
3321 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003322 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003323 for (match = match->cp_prev; match
3324 && match->cp_number == -1;
3325 match = match->cp_prev)
3326 match->cp_number = ++number;
3327 }
3328}
3329
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003330/*
glepnir037b0282025-01-16 14:37:44 +01003331 * Fill the dict of complete_info
3332 */
3333 static void
3334fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3335{
3336 dict_add_string(di, "word", match->cp_str.string);
3337 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3338 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3339 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3340 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3341 if (add_match)
3342 dict_add_bool(di, "match", match->cp_in_match_array);
3343 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3344 // Add an empty string for backwards compatibility
3345 dict_add_string(di, "user_data", (char_u *)"");
3346 else
3347 dict_add_tv(di, "user_data", &match->cp_user_data);
3348}
3349
3350/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003351 * Get complete information
3352 */
3353 static void
3354get_complete_info(list_T *what_list, dict_T *retdict)
3355{
3356 int ret = OK;
3357 listitem_T *item;
3358#define CI_WHAT_MODE 0x01
3359#define CI_WHAT_PUM_VISIBLE 0x02
3360#define CI_WHAT_ITEMS 0x04
3361#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003362#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003363#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003364#define CI_WHAT_ALL 0xff
3365 int what_flag;
3366
3367 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003368 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003369 else
3370 {
3371 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003372 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003373 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003374 {
3375 char_u *what = tv_get_string(&item->li_tv);
3376
3377 if (STRCMP(what, "mode") == 0)
3378 what_flag |= CI_WHAT_MODE;
3379 else if (STRCMP(what, "pum_visible") == 0)
3380 what_flag |= CI_WHAT_PUM_VISIBLE;
3381 else if (STRCMP(what, "items") == 0)
3382 what_flag |= CI_WHAT_ITEMS;
3383 else if (STRCMP(what, "selected") == 0)
3384 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003385 else if (STRCMP(what, "completed") == 0)
3386 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003387 else if (STRCMP(what, "matches") == 0)
3388 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003389 }
3390 }
3391
3392 if (ret == OK && (what_flag & CI_WHAT_MODE))
3393 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3394
3395 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3396 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3397
glepnir037b0282025-01-16 14:37:44 +01003398 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3399 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003400 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003401 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003402 dict_T *di;
3403 compl_T *match;
3404 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003405 int has_items = what_flag & CI_WHAT_ITEMS;
3406 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003407 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003408
glepnird4088ed2024-12-31 10:55:22 +01003409 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003410 {
3411 li = list_alloc();
3412 if (li == NULL)
3413 return;
glepnird4088ed2024-12-31 10:55:22 +01003414 ret = dict_add_list(retdict, (has_matches && !has_items)
3415 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003416 }
3417 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3418 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3419 ins_compl_update_sequence_numbers();
3420 if (ret == OK && compl_first_match != NULL)
3421 {
3422 int list_idx = 0;
3423 match = compl_first_match;
3424 do
3425 {
3426 if (!match_at_original_text(match))
3427 {
glepnird4088ed2024-12-31 10:55:22 +01003428 if (has_items
3429 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003430 {
3431 di = dict_alloc();
3432 if (di == NULL)
3433 return;
3434 ret = list_append_dict(li, di);
3435 if (ret != OK)
3436 return;
glepnir037b0282025-01-16 14:37:44 +01003437 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003438 }
glepnird4088ed2024-12-31 10:55:22 +01003439 if (compl_curr_match != NULL
3440 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003441 selected_idx = list_idx;
3442 list_idx += 1;
3443 }
3444 match = match->cp_next;
3445 }
3446 while (match != NULL && !is_first_match(match));
3447 }
3448 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3449 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003450
glepnir037b0282025-01-16 14:37:44 +01003451 if (ret == OK && selected_idx != -1 && has_completed)
3452 {
3453 di = dict_alloc();
3454 if (di == NULL)
3455 return;
3456 fill_complete_info_dict(di, compl_curr_match, FALSE);
3457 ret = dict_add_dict(retdict, "completed", di);
3458 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003459 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003460}
3461
3462/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003463 * "complete_info()" function
3464 */
3465 void
3466f_complete_info(typval_T *argvars, typval_T *rettv)
3467{
3468 list_T *what_list = NULL;
3469
Bram Moolenaar93a10962022-06-16 11:42:09 +01003470 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003471 return;
3472
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003473 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3474 return;
3475
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003476 if (argvars[0].v_type != VAR_UNKNOWN)
3477 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003478 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003479 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003480 what_list = argvars[0].vval.v_list;
3481 }
3482 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003483}
3484#endif
3485
3486/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003487 * Returns TRUE when using a user-defined function for thesaurus completion.
3488 */
3489 static int
3490thesaurus_func_complete(int type UNUSED)
3491{
3492#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003493 return type == CTRL_X_THESAURUS
3494 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003495#else
3496 return FALSE;
3497#endif
3498}
3499
3500/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003501 * Return value of process_next_cpt_value()
3502 */
3503enum
3504{
3505 INS_COMPL_CPT_OK = 1,
3506 INS_COMPL_CPT_CONT,
3507 INS_COMPL_CPT_END
3508};
3509
3510/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003511 * state information used for getting the next set of insert completion
3512 * matches.
3513 */
3514typedef struct
3515{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003516 char_u *e_cpt_copy; // copy of 'complete'
3517 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003518 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003519 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003520 pos_T prev_match_pos; // previous match position
3521 int set_match_pos; // save first_match_pos/last_match_pos
3522 pos_T first_match_pos; // first match position
3523 pos_T last_match_pos; // last match position
3524 int found_all; // found all matches of a certain type.
3525 char_u *dict; // dictionary file to search
3526 int dict_f; // "dict" is an exact file name or not
3527} ins_compl_next_state_T;
3528
3529/*
3530 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003531 *
3532 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003533 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003534 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003535 * st->found_all - all matches of this type are found
3536 * st->ins_buf - search for completions in this buffer
3537 * st->first_match_pos - position of the first completion match
3538 * st->last_match_pos - position of the last completion match
3539 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003540 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003541 * st->dict - name of the dictionary or thesaurus file to search
3542 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003543 *
3544 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003545 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3546 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003547 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003548 */
3549 static int
3550process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003551 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003552 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003553 pos_T *start_match_pos,
3554 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003555{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003556 int compl_type = -1;
3557 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003558
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003559 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003560
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003561 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3562 st->e_cpt++;
3563
3564 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003565 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003566 st->ins_buf = curbuf;
3567 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003568 // Move the cursor back one character so that ^N can match the
3569 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003570 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003571 {
3572 // Move the cursor to after the last character in the
3573 // buffer, so that word at start of buffer is found
3574 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003575 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003576 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003577 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003578 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003579 compl_type = 0;
3580
3581 // Remember the first match so that the loop stops when we
3582 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003583 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003584 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003585 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003586 && (st->ins_buf = ins_compl_next_buf(
3587 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003588 {
3589 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003590 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003591 {
3592 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003593 st->first_match_pos.col = st->last_match_pos.col = 0;
3594 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3595 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003596 compl_type = 0;
3597 }
3598 else // unloaded buffer, scan like dictionary
3599 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003600 st->found_all = TRUE;
3601 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003602 {
3603 status = INS_COMPL_CPT_CONT;
3604 goto done;
3605 }
3606 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003607 st->dict = st->ins_buf->b_fname;
3608 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003609 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003610 if (!shortmess(SHM_COMPLETIONSCAN))
3611 {
3612 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3613 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3614 st->ins_buf->b_fname == NULL
3615 ? buf_spname(st->ins_buf)
3616 : st->ins_buf->b_sfname == NULL
3617 ? st->ins_buf->b_fname
3618 : st->ins_buf->b_sfname);
3619 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3620 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003621 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003622 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003623 status = INS_COMPL_CPT_END;
3624 else
3625 {
3626 if (ctrl_x_mode_line_or_eval())
3627 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003628 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003629 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003630 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003631 compl_type = CTRL_X_DICTIONARY;
3632 else
3633 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003634 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003635 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003636 st->dict = st->e_cpt;
3637 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003638 }
3639 }
3640#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003641 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003642 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003643 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003644 compl_type = CTRL_X_PATH_DEFINES;
3645#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003646 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003647 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003648 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003649 if (!shortmess(SHM_COMPLETIONSCAN))
3650 {
3651 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3652 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3653 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3654 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003655 }
3656 else
3657 compl_type = -1;
3658
3659 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003660 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003661
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003662 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003663 if (compl_type == -1)
3664 status = INS_COMPL_CPT_CONT;
3665 }
3666
3667done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003668 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003669 return status;
3670}
3671
3672#ifdef FEAT_FIND_ID
3673/*
3674 * Get the next set of identifiers or defines matching "compl_pattern" in
3675 * included files.
3676 */
3677 static void
3678get_next_include_file_completion(int compl_type)
3679{
John Marriott5e6ea922024-11-23 14:01:57 +01003680 find_pattern_in_path(compl_pattern.string, compl_direction,
3681 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003682 (compl_type == CTRL_X_PATH_DEFINES
3683 && !(compl_cont_status & CONT_SOL))
3684 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003685 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003686}
3687#endif
3688
3689/*
3690 * Get the next set of words matching "compl_pattern" in dictionary or
3691 * thesaurus files.
3692 */
3693 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003694get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003695{
3696#ifdef FEAT_COMPL_FUNC
3697 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003698 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003699 else
3700#endif
3701 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003702 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003703 : (compl_type == CTRL_X_THESAURUS
3704 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3705 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003706 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003707 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003708 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003709}
3710
3711/*
3712 * Get the next set of tag names matching "compl_pattern".
3713 */
3714 static void
3715get_next_tag_completion(void)
3716{
3717 int save_p_ic;
3718 char_u **matches;
3719 int num_matches;
3720
3721 // set p_ic according to p_ic, p_scs and pat for find_tags().
3722 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003723 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003724
3725 // Find up to TAG_MANY matches. Avoids that an enormous number
3726 // of matches is found when compl_pattern is empty
3727 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003728 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003729 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003730 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003731 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3732 ins_compl_add_matches(num_matches, matches, p_ic);
3733 g_tag_at_cursor = FALSE;
3734 p_ic = save_p_ic;
3735}
3736
3737/*
glepnir8159fb12024-07-17 20:32:54 +02003738 * Compare function for qsort
3739 */
3740static int compare_scores(const void *a, const void *b)
3741{
3742 int idx_a = *(const int *)a;
3743 int idx_b = *(const int *)b;
3744 int score_a = compl_fuzzy_scores[idx_a];
3745 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003746 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3747 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003748}
3749
3750/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003751 * Get the next set of filename matching "compl_pattern".
3752 */
3753 static void
3754get_next_filename_completion(void)
3755{
3756 char_u **matches;
3757 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003758 char_u *ptr;
3759 garray_T fuzzy_indices;
3760 int i;
3761 int score;
3762 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003763 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003764 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3765 char_u **sorted_matches;
3766 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003767 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003768
glepnirb9de1a02024-08-02 19:14:38 +02003769#ifdef BACKSLASH_IN_FILENAME
3770 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3771 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3772#else
3773 char pathsep = PATHSEP;
3774#endif
3775
glepnir8159fb12024-07-17 20:32:54 +02003776 if (in_fuzzy)
3777 {
glepnirb9de1a02024-08-02 19:14:38 +02003778#ifdef BACKSLASH_IN_FILENAME
3779 if (curbuf->b_p_csl[0] == 's')
3780 {
John Marriott5e6ea922024-11-23 14:01:57 +01003781 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003782 {
3783 if (leader[i] == '\\')
3784 leader[i] = '/';
3785 }
3786 }
3787 else if (curbuf->b_p_csl[0] == 'b')
3788 {
John Marriott5e6ea922024-11-23 14:01:57 +01003789 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003790 {
3791 if (leader[i] == '/')
3792 leader[i] = '\\';
3793 }
3794 }
3795#endif
3796 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003797 if (last_sep == NULL)
3798 {
3799 // No path separator or separator is the last character,
3800 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003801 VIM_CLEAR_STRING(compl_pattern);
3802 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3803 if (compl_pattern.string == NULL)
3804 return;
3805 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003806 }
3807 else if (*(last_sep + 1) == '\0')
3808 in_fuzzy = FALSE;
3809 else
3810 {
3811 // Split leader into path and file parts
3812 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003813 char_u *path_with_wildcard;
3814
3815 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003816 if (path_with_wildcard != NULL)
3817 {
John Marriott5e6ea922024-11-23 14:01:57 +01003818 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3819 VIM_CLEAR_STRING(compl_pattern);
3820 compl_pattern.string = path_with_wildcard;
3821 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003822
3823 // Move leader to the file part
3824 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003825 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003826 }
3827 }
glepnir8159fb12024-07-17 20:32:54 +02003828 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003829
John Marriott5e6ea922024-11-23 14:01:57 +01003830 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003831 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3832 return;
3833
3834 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003835 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003836#ifdef BACKSLASH_IN_FILENAME
3837 if (curbuf->b_p_csl[0] != NUL)
3838 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003839 for (i = 0; i < num_matches; ++i)
3840 {
glepnir8159fb12024-07-17 20:32:54 +02003841 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003842 while (*ptr != NUL)
3843 {
3844 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3845 *ptr = '/';
3846 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3847 *ptr = '\\';
3848 ptr += (*mb_ptr2len)(ptr);
3849 }
3850 }
3851 }
3852#endif
glepnir8159fb12024-07-17 20:32:54 +02003853
3854 if (in_fuzzy)
3855 {
3856 ga_init2(&fuzzy_indices, sizeof(int), 10);
3857 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3858
3859 for (i = 0; i < num_matches; i++)
3860 {
3861 ptr = matches[i];
3862 score = fuzzy_match_str(ptr, leader);
3863 if (score > 0)
3864 {
3865 if (ga_grow(&fuzzy_indices, 1) == OK)
3866 {
3867 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3868 compl_fuzzy_scores[i] = score;
3869 fuzzy_indices.ga_len++;
3870 }
3871 }
3872 }
3873
Christian Brabandt220474d2024-07-20 13:26:44 +02003874 // prevent qsort from deref NULL pointer
3875 if (fuzzy_indices.ga_len > 0)
3876 {
3877 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3878 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003879
Christian Brabandt220474d2024-07-20 13:26:44 +02003880 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3881 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3882 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003883
Christian Brabandt220474d2024-07-20 13:26:44 +02003884 FreeWild(num_matches, matches);
3885 matches = sorted_matches;
3886 num_matches = fuzzy_indices.ga_len;
3887 }
glepnir6b6280c2024-07-27 16:25:45 +02003888 else if (leader_len > 0)
3889 {
3890 FreeWild(num_matches, matches);
3891 num_matches = 0;
3892 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003893
glepnir8159fb12024-07-17 20:32:54 +02003894 vim_free(compl_fuzzy_scores);
3895 ga_clear(&fuzzy_indices);
3896 }
3897
glepnir6b6280c2024-07-27 16:25:45 +02003898 if (num_matches > 0)
3899 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003900}
3901
3902/*
3903 * Get the next set of command-line completions matching "compl_pattern".
3904 */
3905 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003906get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003907{
3908 char_u **matches;
3909 int num_matches;
3910
John Marriott5e6ea922024-11-23 14:01:57 +01003911 if (expand_cmdline(&compl_xp, compl_pattern.string,
3912 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003913 ins_compl_add_matches(num_matches, matches, FALSE);
3914}
3915
3916/*
3917 * Get the next set of spell suggestions matching "compl_pattern".
3918 */
3919 static void
3920get_next_spell_completion(linenr_T lnum UNUSED)
3921{
3922#ifdef FEAT_SPELL
3923 char_u **matches;
3924 int num_matches;
3925
John Marriott5e6ea922024-11-23 14:01:57 +01003926 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003927 if (num_matches > 0)
3928 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003929 else
3930 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003931#endif
3932}
3933
3934/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003935 * Return the next word or line from buffer "ins_buf" at position
3936 * "cur_match_pos" for completion. The length of the match is set in "len".
3937 */
3938 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003939ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003940 buf_T *ins_buf, // buffer being scanned
3941 pos_T *cur_match_pos, // current match position
3942 int *match_len,
3943 int *cont_s_ipos) // next ^X<> will set initial_pos
3944{
3945 char_u *ptr;
3946 int len;
3947
3948 *match_len = 0;
3949 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3950 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003951 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003952 if (ctrl_x_mode_line_or_eval())
3953 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003954 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003955 {
3956 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3957 return NULL;
3958 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003959 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003960 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003961 {
3962 char_u *tmp_ptr = ptr;
3963
3964 ptr = skipwhite(tmp_ptr);
3965 len -= (int)(ptr - tmp_ptr);
3966 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003967 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003968 }
3969 else
3970 {
3971 char_u *tmp_ptr = ptr;
3972
John Marriott5e6ea922024-11-23 14:01:57 +01003973 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003974 {
3975 tmp_ptr += compl_length;
3976 // Skip if already inside a word.
3977 if (vim_iswordp(tmp_ptr))
3978 return NULL;
3979 // Find start of next word.
3980 tmp_ptr = find_word_start(tmp_ptr);
3981 }
3982 // Find end of this word.
3983 tmp_ptr = find_word_end(tmp_ptr);
3984 len = (int)(tmp_ptr - ptr);
3985
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003986 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003987 {
3988 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3989 {
3990 // Try next line, if any. the new word will be
3991 // "join" as if the normal command "J" was used.
3992 // IOSIZE is always greater than
3993 // compl_length, so the next STRNCPY always
3994 // works -- Acevedo
3995 STRNCPY(IObuff, ptr, len);
3996 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3997 tmp_ptr = ptr = skipwhite(ptr);
3998 // Find start of next word.
3999 tmp_ptr = find_word_start(tmp_ptr);
4000 // Find end of next word.
4001 tmp_ptr = find_word_end(tmp_ptr);
4002 if (tmp_ptr > ptr)
4003 {
4004 if (*ptr != ')' && IObuff[len - 1] != TAB)
4005 {
4006 if (IObuff[len - 1] != ' ')
4007 IObuff[len++] = ' ';
4008 // IObuf =~ "\k.* ", thus len >= 2
4009 if (p_js
4010 && (IObuff[len - 2] == '.'
4011 || (vim_strchr(p_cpo, CPO_JOINSP)
4012 == NULL
4013 && (IObuff[len - 2] == '?'
4014 || IObuff[len - 2] == '!'))))
4015 IObuff[len++] = ' ';
4016 }
4017 // copy as much as possible of the new word
4018 if (tmp_ptr - ptr >= IOSIZE - len)
4019 tmp_ptr = ptr + IOSIZE - len - 1;
4020 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4021 len += (int)(tmp_ptr - ptr);
4022 *cont_s_ipos = TRUE;
4023 }
4024 IObuff[len] = NUL;
4025 ptr = IObuff;
4026 }
4027 if (len == compl_length)
4028 return NULL;
4029 }
4030 }
4031
4032 *match_len = len;
4033 return ptr;
4034}
4035
4036/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004037 * Get the next set of words matching "compl_pattern" for default completion(s)
4038 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004039 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4040 * position "st->start_pos" in the "compl_direction" direction. If
4041 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4042 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004043 * Returns OK if a new next match is found, otherwise returns FAIL.
4044 */
4045 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004046get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004047{
4048 int found_new_match = FAIL;
4049 int save_p_scs;
4050 int save_p_ws;
4051 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004052 char_u *ptr = NULL;
4053 int len = 0;
4054 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
4055 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004056
4057 // If 'infercase' is set, don't use 'smartcase' here
4058 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004059 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004060 p_scs = FALSE;
4061
4062 // Buffers other than curbuf are scanned from the beginning or the
4063 // end but never from the middle, thus setting nowrapscan in this
4064 // buffer is a good idea, on the other hand, we always set
4065 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4066 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004067 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004068 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004069 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004070 p_ws = TRUE;
4071 looped_around = FALSE;
4072 for (;;)
4073 {
4074 int cont_s_ipos = FALSE;
4075
4076 ++msg_silent; // Don't want messages for wrapscan.
4077
4078 // ctrl_x_mode_line_or_eval() || word-wise search that
4079 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02004080 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004081 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01004082 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02004083 else if (in_fuzzy)
4084 found_new_match = search_for_fuzzy_match(st->ins_buf,
4085 st->cur_match_pos, leader, compl_direction,
4086 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004087 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004088 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004089 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004090 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004091 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004092 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004093 {
4094 // set "compl_started" even on fail
4095 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004096 st->first_match_pos = *st->cur_match_pos;
4097 st->last_match_pos = *st->cur_match_pos;
4098 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004099 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004100 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4101 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004102 {
4103 found_new_match = FAIL;
4104 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004105 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004106 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4107 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4108 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004109 {
4110 if (looped_around)
4111 found_new_match = FAIL;
4112 else
4113 looped_around = TRUE;
4114 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004115 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004116 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4117 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4118 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004119 {
4120 if (looped_around)
4121 found_new_match = FAIL;
4122 else
4123 looped_around = TRUE;
4124 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004125 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004126 if (found_new_match == FAIL)
4127 break;
4128
4129 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004130 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004131 && start_pos->lnum == st->cur_match_pos->lnum
4132 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004133 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004134
glepnir8159fb12024-07-17 20:32:54 +02004135 if (!in_fuzzy)
4136 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4137 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004138 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004139 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004140
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004141 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004142 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004143 0, cont_s_ipos) != NOTDONE)
4144 {
4145 found_new_match = OK;
4146 break;
4147 }
4148 }
4149 p_scs = save_p_scs;
4150 p_ws = save_p_ws;
4151
4152 return found_new_match;
4153}
4154
4155/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004156 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004157 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004158 */
4159 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004160get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004161{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004162 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004163
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004164 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004165 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004166 case -1:
4167 break;
4168#ifdef FEAT_FIND_ID
4169 case CTRL_X_PATH_PATTERNS:
4170 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004171 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004172 break;
4173#endif
4174
4175 case CTRL_X_DICTIONARY:
4176 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004177 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4178 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004179 break;
4180
4181 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004182 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004183 break;
4184
4185 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004186 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004187 break;
4188
4189 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004190 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004191 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004192 break;
4193
4194#ifdef FEAT_COMPL_FUNC
4195 case CTRL_X_FUNCTION:
4196 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004197 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004198 break;
4199#endif
4200
4201 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004202 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004203 break;
4204
4205 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004206 found_new_match = get_next_default_completion(st, ini);
4207 if (found_new_match == FAIL && st->ins_buf == curbuf)
4208 st->found_all = TRUE;
4209 }
4210
4211 // check if compl_curr_match has changed, (e.g. other type of
4212 // expansion added something)
4213 if (type != 0 && compl_curr_match != compl_old_match)
4214 found_new_match = OK;
4215
4216 return found_new_match;
4217}
4218
4219/*
4220 * Get the next expansion(s), using "compl_pattern".
4221 * The search starts at position "ini" in curbuf and in the direction
4222 * compl_direction.
4223 * When "compl_started" is FALSE start at that position, otherwise continue
4224 * where we stopped searching before.
4225 * This may return before finding all the matches.
4226 * Return the total number of matches or -1 if still unknown -- Acevedo
4227 */
4228 static int
4229ins_compl_get_exp(pos_T *ini)
4230{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004231 static ins_compl_next_state_T st;
4232 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004233 int i;
4234 int found_new_match;
4235 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004236 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004237
4238 if (!compl_started)
4239 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004240 buf_T *buf;
4241
4242 FOR_ALL_BUFFERS(buf)
4243 buf->b_scanned = 0;
4244 if (!st_cleared)
4245 {
4246 CLEAR_FIELD(st);
4247 st_cleared = TRUE;
4248 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004249 st.found_all = FALSE;
4250 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004251 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004252 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004253 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4254 ? (char_u *)"." : curbuf->b_p_cpt);
4255 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004256 st.last_match_pos = st.first_match_pos = *ini;
4257 }
4258 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4259 st.ins_buf = curbuf; // In case the buffer was wiped out.
4260
4261 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004262 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004263 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004264
4265 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4266 for (;;)
4267 {
4268 found_new_match = FAIL;
4269 st.set_match_pos = FALSE;
4270
4271 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4272 // or if found_all says this entry is done. For ^X^L only use the
4273 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004274 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004275 && (!compl_started || st.found_all))
4276 {
glepnir8159fb12024-07-17 20:32:54 +02004277 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004278
4279 if (status == INS_COMPL_CPT_END)
4280 break;
4281 if (status == INS_COMPL_CPT_CONT)
4282 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004283 }
4284
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004285 // If complete() was called then compl_pattern has been reset. The
4286 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004287 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004288 break;
4289
4290 // get the next set of completion matches
4291 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004292
4293 // break the loop for specialized modes (use 'complete' just for the
4294 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4295 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004296 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4297 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004298 {
4299 if (got_int)
4300 break;
4301 // Fill the popup menu as soon as possible.
4302 if (type != -1)
4303 ins_compl_check_keys(0, FALSE);
4304
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004305 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004306 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4307 break;
4308 compl_started = TRUE;
4309 }
4310 else
4311 {
4312 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004313 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004314 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004315
4316 compl_started = FALSE;
4317 }
4318 }
4319 compl_started = TRUE;
4320
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004321 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004322 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004323 found_new_match = FAIL;
4324
4325 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004326 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004327 && !ctrl_x_mode_line_or_eval()))
4328 i = ins_compl_make_cyclic();
4329
4330 if (compl_old_match != NULL)
4331 {
4332 // If several matches were added (FORWARD) or the search failed and has
4333 // just been made cyclic then we have to move compl_curr_match to the
4334 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004335 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004336 : compl_old_match->cp_prev;
4337 if (compl_curr_match == NULL)
4338 compl_curr_match = compl_old_match;
4339 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004340 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004341
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004342 return i;
4343}
4344
4345/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004346 * Update "compl_shown_match" to the actually shown match, it may differ when
4347 * "compl_leader" is used to omit some of the matches.
4348 */
4349 static void
4350ins_compl_update_shown_match(void)
4351{
4352 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004353 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004354 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004355 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004356 compl_shown_match = compl_shown_match->cp_next;
4357
4358 // If we didn't find it searching forward, and compl_shows_dir is
4359 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004360 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004361 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004362 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004363 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004364 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004365 {
4366 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004367 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004368 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004369 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004370 compl_shown_match = compl_shown_match->cp_prev;
4371 }
4372}
4373
4374/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004375 * Delete the old text being completed.
4376 */
4377 void
4378ins_compl_delete(void)
4379{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004380 // In insert mode: Delete the typed part.
4381 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004382 int col = compl_col + (compl_status_adding() ? compl_length : 0);
glepnir76bdb822025-02-08 19:04:51 +01004383 char_u *remaining = NULL;
4384 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004385 int has_preinsert = ins_compl_preinsert_effect();
4386 if (has_preinsert)
4387 {
glepnirbfb4eea2025-01-31 15:28:29 +01004388 col += ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004389 curwin->w_cursor.col = compl_ins_end_col;
4390 }
4391
glepnir76bdb822025-02-08 19:04:51 +01004392 if (curwin->w_cursor.lnum > compl_lnum)
4393 {
4394 if (curwin->w_cursor.col < ml_get_curline_len())
4395 {
4396 char_u *line = ml_get_curline();
4397 remaining = vim_strnsave(line + curwin->w_cursor.col,
4398 (size_t)STRLEN(line + curwin->w_cursor.col));
4399 if (remaining == NULL)
4400 return;
4401 }
4402 while (curwin->w_cursor.lnum > compl_lnum)
4403 {
4404 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4405 {
4406 if (remaining)
4407 VIM_CLEAR(remaining);
4408 return;
4409 }
4410 curwin->w_cursor.lnum--;
4411 }
4412 // move cursor to end of line
4413 curwin->w_cursor.col = ml_get_curline_len();
4414 }
4415
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004416 if ((int)curwin->w_cursor.col > col)
4417 {
4418 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004419 {
4420 if (remaining)
4421 VIM_CLEAR(remaining);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004422 return;
glepnire3647c82025-02-10 21:16:32 +01004423 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004424 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004425 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004426 }
4427
glepnir76bdb822025-02-08 19:04:51 +01004428 if (remaining != NULL)
4429 {
4430 orig_col = curwin->w_cursor.col;
4431 ins_str(remaining);
4432 curwin->w_cursor.col = orig_col;
4433 vim_free(remaining);
4434 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004435 // TODO: is this sufficient for redrawing? Redrawing everything causes
4436 // flicker, thus we can't do that.
4437 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004438#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004439 // clear v:completed_item
4440 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004441#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004442}
4443
4444/*
glepnir76bdb822025-02-08 19:04:51 +01004445 * Insert a completion string that contains newlines.
4446 * The string is split and inserted line by line.
4447 */
4448 static void
4449ins_compl_expand_multiple(char_u *str)
4450{
4451 char_u *start = str;
4452 char_u *curr = str;
4453
4454 while (*curr != NUL)
4455 {
4456 if (*curr == '\n')
4457 {
4458 // Insert the text chunk before newline
4459 if (curr > start)
4460 ins_char_bytes(start, (int)(curr - start));
4461
4462 // Handle newline
4463 open_line(FORWARD, OPENLINE_KEEPTRAIL, FALSE, NULL);
4464 start = curr + 1;
4465 }
4466 curr++;
4467 }
4468
4469 // Handle remaining text after last newline (if any)
4470 if (curr > start)
4471 ins_char_bytes(start, (int)(curr - start));
4472
4473 compl_ins_end_col = curwin->w_cursor.col;
4474}
4475
4476/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004477 * Insert the new text being completed.
4478 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004479 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4480 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004481 */
4482 void
glepniredd4ac32025-01-29 18:53:51 +01004483ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004484{
glepnir76bdb822025-02-08 19:04:51 +01004485 int compl_len = get_compl_len();
4486 int preinsert = ins_compl_has_preinsert();
4487 char_u *cp_str = compl_shown_match->cp_str.string;
4488 size_t cp_str_len = compl_shown_match->cp_str.length;
4489 size_t leader_len = ins_compl_leader_len();
4490 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004491
4492 // Make sure we don't go over the end of the string, this can happen with
4493 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004494 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004495 {
glepnir76bdb822025-02-08 19:04:51 +01004496 if (has_multiple)
4497 ins_compl_expand_multiple(cp_str + compl_len);
4498 else
4499 {
4500 ins_compl_insert_bytes(cp_str + compl_len, -1);
4501 if (preinsert && move_cursor)
4502 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4503 }
glepniredd4ac32025-01-29 18:53:51 +01004504 }
4505 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004506 compl_used_match = FALSE;
4507 else
4508 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004509#ifdef FEAT_EVAL
4510 {
4511 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4512
4513 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4514 }
4515#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004516 if (!in_compl_func)
4517 compl_curr_match = compl_shown_match;
4518}
4519
4520/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004521 * show the file name for the completion match (if any). Truncate the file
4522 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004523 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004524 static void
4525ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004526{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004527 char *lead = _("match in file");
4528 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4529 char_u *s;
4530 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004531
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004532 if (space <= 0)
4533 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004534
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004535 // We need the tail that fits. With double-byte encoding going
4536 // back from the end is very slow, thus go from the start and keep
4537 // the text that fits in "space" between "s" and "e".
4538 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004539 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004540 space -= ptr2cells(e);
4541 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004542 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004543 space += ptr2cells(s);
4544 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004545 }
4546 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004547 msg_hist_off = TRUE;
4548 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4549 s > compl_shown_match->cp_fname ? "<" : "", s);
4550 msg((char *)IObuff);
4551 msg_hist_off = FALSE;
4552 redraw_cmdline = FALSE; // don't overwrite!
4553}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004554
glepnirdca57fb2024-06-04 22:01:21 +02004555/*
zeertzjq551d8c32024-06-05 19:53:32 +02004556 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004557 */
glepnira218cc62024-06-03 19:32:39 +02004558 static compl_T *
4559find_comp_when_fuzzy(void)
4560{
4561 int score;
4562 char_u* str;
4563 int target_idx = -1;
4564 int is_forward = compl_shows_dir_forward();
4565 int is_backward = compl_shows_dir_backward();
4566 compl_T *comp = NULL;
4567
glepnir43eef882024-06-19 20:20:48 +02004568 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004569 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004570 return compl_first_match != compl_shown_match ? compl_first_match :
4571 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004572
4573 if (is_forward)
4574 target_idx = compl_selected_item + 1;
4575 else if (is_backward)
4576 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004577 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004578
4579 score = compl_match_array[target_idx].pum_score;
4580 str = compl_match_array[target_idx].pum_text;
4581
4582 comp = compl_first_match;
4583 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004584 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004585 return comp;
4586 comp = comp->cp_next;
4587 } while (comp != NULL && !is_first_match(comp));
4588
4589 return NULL;
4590}
4591
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004592/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004593 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004594 * times. The number of matches found is returned in 'num_matches'.
4595 *
4596 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4597 * get more completions. If it is FALSE, then do nothing when there are no more
4598 * completions in the given direction.
4599 *
4600 * If "advance" is TRUE, then completion will move to the first match.
4601 * Otherwise, the original text will be shown.
4602 *
4603 * Returns OK on success and -1 if the number of matches are unknown.
4604 */
4605 static int
4606find_next_completion_match(
4607 int allow_get_expansion,
4608 int todo, // repeat completion this many times
4609 int advance,
4610 int *num_matches)
4611{
4612 int found_end = FALSE;
4613 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004614 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004615 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4616 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004617
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004618 while (--todo >= 0)
4619 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004620 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004621 {
glepniraced8c22024-06-15 15:13:05 +02004622 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4623 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004624 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004625 && (is_first_match(compl_shown_match->cp_next)
4626 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004627 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004628 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004629 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004630 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004631 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004632 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4633 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004634 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004635 }
4636 else
4637 {
4638 if (!allow_get_expansion)
4639 {
4640 if (advance)
4641 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004642 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004643 compl_pending -= todo + 1;
4644 else
4645 compl_pending += todo + 1;
4646 }
4647 return -1;
4648 }
4649
4650 if (!compl_no_select && advance)
4651 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004652 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004653 --compl_pending;
4654 else
4655 ++compl_pending;
4656 }
4657
4658 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004659 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004660
4661 // handle any pending completions
4662 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004663 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004664 {
4665 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4666 {
4667 compl_shown_match = compl_shown_match->cp_next;
4668 --compl_pending;
4669 }
4670 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4671 {
4672 compl_shown_match = compl_shown_match->cp_prev;
4673 ++compl_pending;
4674 }
4675 else
4676 break;
4677 }
4678 found_end = FALSE;
4679 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004680 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004681 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004682 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004683 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004684 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004685 ++todo;
4686 else
4687 // Remember a matching item.
4688 found_compl = compl_shown_match;
4689
4690 // Stop at the end of the list when we found a usable match.
4691 if (found_end)
4692 {
4693 if (found_compl != NULL)
4694 {
4695 compl_shown_match = found_compl;
4696 break;
4697 }
4698 todo = 1; // use first usable match after wrapping around
4699 }
4700 }
4701
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004702 return OK;
4703}
4704
4705/*
4706 * Fill in the next completion in the current direction.
4707 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4708 * get more completions. If it is FALSE, then we just do nothing when there
4709 * are no more completions in a given direction. The latter case is used when
4710 * we are still in the middle of finding completions, to allow browsing
4711 * through the ones found so far.
4712 * Return the total number of matches, or -1 if still unknown -- webb.
4713 *
4714 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4715 * compl_shown_match here.
4716 *
4717 * Note that this function may be called recursively once only. First with
4718 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4719 * calls this function with "allow_get_expansion" FALSE.
4720 */
4721 static int
4722ins_compl_next(
4723 int allow_get_expansion,
4724 int count, // repeat completion this many times; should
4725 // be at least 1
4726 int insert_match, // Insert the newly selected match
4727 int in_compl_func) // called from complete_check()
4728{
4729 int num_matches = -1;
4730 int todo = count;
4731 int advance;
4732 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004733 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004734 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004735 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4736 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01004737 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004738
4739 // When user complete function return -1 for findstart which is next
4740 // time of 'always', compl_shown_match become NULL.
4741 if (compl_shown_match == NULL)
4742 return -1;
4743
John Marriott5e6ea922024-11-23 14:01:57 +01004744 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004745 && !match_at_original_text(compl_shown_match)
4746 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004747 // Update "compl_shown_match" to the actually shown match
4748 ins_compl_update_shown_match();
4749
4750 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004751 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004752 // Delete old text to be replaced
4753 ins_compl_delete();
4754
4755 // When finding the longest common text we stick at the original text,
4756 // don't let CTRL-N or CTRL-P move to the first match.
4757 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4758
4759 // When restarting the search don't insert the first match either.
4760 if (compl_restarting)
4761 {
4762 advance = FALSE;
4763 compl_restarting = FALSE;
4764 }
4765
4766 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4767 // around.
4768 if (find_next_completion_match(allow_get_expansion, todo, advance,
4769 &num_matches) == -1)
4770 return -1;
4771
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004772 if (curbuf != orig_curbuf)
4773 {
4774 // In case some completion function switched buffer, don't want to
4775 // insert the completion elsewhere.
4776 return -1;
4777 }
4778
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004779 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01004780 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004781 {
glepnir6a38aff2024-12-16 21:56:16 +01004782 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004783 compl_used_match = FALSE;
4784 }
4785 else if (insert_match)
4786 {
4787 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01004788 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004789 else
glepnir6a38aff2024-12-16 21:56:16 +01004790 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004791 }
4792 else
4793 compl_used_match = FALSE;
4794
4795 if (!allow_get_expansion)
4796 {
4797 // may undisplay the popup menu first
4798 ins_compl_upd_pum();
4799
4800 if (pum_enough_matches())
4801 // Will display the popup menu, don't redraw yet to avoid flicker.
4802 pum_call_update_screen();
4803 else
4804 // Not showing the popup menu yet, redraw to show the user what was
4805 // inserted.
4806 update_screen(0);
4807
4808 // display the updated popup menu
4809 ins_compl_show_pum();
4810#ifdef FEAT_GUI
4811 if (gui.in_use)
4812 {
4813 // Show the cursor after the match, not after the redrawn text.
4814 setcursor();
4815 out_flush_cursor(FALSE, FALSE);
4816 }
4817#endif
4818
4819 // Delete old text to be replaced, since we're still searching and
4820 // don't want to match ourselves!
4821 ins_compl_delete();
4822 }
4823
4824 // Enter will select a match when the match wasn't inserted and the popup
4825 // menu is visible.
4826 if (compl_no_insert && !started)
4827 compl_enter_selects = TRUE;
4828 else
4829 compl_enter_selects = !insert_match && compl_match_array != NULL;
4830
4831 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004832 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004833 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004834
4835 return num_matches;
4836}
4837
4838/*
4839 * Call this while finding completions, to check whether the user has hit a key
4840 * that should change the currently displayed completion, or exit completion
4841 * mode. Also, when compl_pending is not zero, show a completion as soon as
4842 * possible. -- webb
4843 * "frequency" specifies out of how many calls we actually check.
4844 * "in_compl_func" is TRUE when called from complete_check(), don't set
4845 * compl_curr_match.
4846 */
4847 void
4848ins_compl_check_keys(int frequency, int in_compl_func)
4849{
4850 static int count = 0;
4851 int c;
4852
4853 // Don't check when reading keys from a script, :normal or feedkeys().
4854 // That would break the test scripts. But do check for keys when called
4855 // from complete_check().
4856 if (!in_compl_func && (using_script() || ex_normal_busy))
4857 return;
4858
4859 // Only do this at regular intervals
4860 if (++count < frequency)
4861 return;
4862 count = 0;
4863
4864 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4865 // can't do its work correctly.
4866 c = vpeekc_any();
4867 if (c != NUL)
4868 {
4869 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4870 {
4871 c = safe_vgetc(); // Eat the character
4872 compl_shows_dir = ins_compl_key2dir(c);
4873 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4874 c != K_UP && c != K_DOWN, in_compl_func);
4875 }
4876 else
4877 {
4878 // Need to get the character to have KeyTyped set. We'll put it
4879 // back with vungetc() below. But skip K_IGNORE.
4880 c = safe_vgetc();
4881 if (c != K_IGNORE)
4882 {
4883 // Don't interrupt completion when the character wasn't typed,
4884 // e.g., when doing @q to replay keys.
4885 if (c != Ctrl_R && KeyTyped)
4886 compl_interrupted = TRUE;
4887
4888 vungetc(c);
4889 }
4890 }
4891 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004892 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004893 {
4894 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4895
4896 compl_pending = 0;
4897 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4898 }
4899}
4900
4901/*
4902 * Decide the direction of Insert mode complete from the key typed.
4903 * Returns BACKWARD or FORWARD.
4904 */
4905 static int
4906ins_compl_key2dir(int c)
4907{
4908 if (c == Ctrl_P || c == Ctrl_L
4909 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4910 return BACKWARD;
4911 return FORWARD;
4912}
4913
4914/*
4915 * Return TRUE for keys that are used for completion only when the popup menu
4916 * is visible.
4917 */
4918 static int
4919ins_compl_pum_key(int c)
4920{
4921 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4922 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4923 || c == K_UP || c == K_DOWN);
4924}
4925
4926/*
4927 * Decide the number of completions to move forward.
4928 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4929 */
4930 static int
4931ins_compl_key2count(int c)
4932{
4933 int h;
4934
4935 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4936 {
4937 h = pum_get_height();
4938 if (h > 3)
4939 h -= 2; // keep some context
4940 return h;
4941 }
4942 return 1;
4943}
4944
4945/*
4946 * Return TRUE if completion with "c" should insert the match, FALSE if only
4947 * to change the currently selected completion.
4948 */
4949 static int
4950ins_compl_use_match(int c)
4951{
4952 switch (c)
4953 {
4954 case K_UP:
4955 case K_DOWN:
4956 case K_PAGEDOWN:
4957 case K_KPAGEDOWN:
4958 case K_S_DOWN:
4959 case K_PAGEUP:
4960 case K_KPAGEUP:
4961 case K_S_UP:
4962 return FALSE;
4963 }
4964 return TRUE;
4965}
4966
4967/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004968 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4969 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004970 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004971 * Uses the global variables: compl_cont_status and ctrl_x_mode
4972 */
4973 static int
4974get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4975{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004976 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004977 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004978 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004979 {
4980 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4981 ;
4982 compl_col += ++startcol;
4983 compl_length = curs_col - startcol;
4984 }
4985 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004986 {
John Marriott5e6ea922024-11-23 14:01:57 +01004987 compl_pattern.string = str_foldcase(line + compl_col,
4988 compl_length, NULL, 0);
4989 if (compl_pattern.string == NULL)
4990 {
4991 compl_pattern.length = 0;
4992 return FAIL;
4993 }
4994 compl_pattern.length = STRLEN(compl_pattern.string);
4995 }
4996 else
4997 {
4998 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4999 if (compl_pattern.string == NULL)
5000 {
5001 compl_pattern.length = 0;
5002 return FAIL;
5003 }
5004 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005005 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005006 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005007 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005008 {
5009 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005010 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005011 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005012
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005013 if (!vim_iswordp(line + compl_col)
5014 || (compl_col > 0
5015 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005016 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005017 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005018 prefixlen = 0;
5019 }
John Marriott5e6ea922024-11-23 14:01:57 +01005020
5021 // we need up to 2 extra chars for the prefix
5022 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5023 compl_pattern.string = alloc(n);
5024 if (compl_pattern.string == NULL)
5025 {
5026 compl_pattern.length = 0;
5027 return FAIL;
5028 }
5029 STRCPY((char *)compl_pattern.string, prefix);
5030 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005031 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005032 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005033 }
5034 else if (--startcol < 0
5035 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5036 {
John Marriott5e6ea922024-11-23 14:01:57 +01005037 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5038
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005039 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005040 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5041 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005042 {
John Marriott5e6ea922024-11-23 14:01:57 +01005043 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005044 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005045 }
John Marriott5e6ea922024-11-23 14:01:57 +01005046 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005047 compl_col += curs_col;
5048 compl_length = 0;
5049 }
5050 else
5051 {
5052 // Search the point of change class of multibyte character
5053 // or not a word single byte character backward.
5054 if (has_mbyte)
5055 {
5056 int base_class;
5057 int head_off;
5058
5059 startcol -= (*mb_head_off)(line, line + startcol);
5060 base_class = mb_get_class(line + startcol);
5061 while (--startcol >= 0)
5062 {
5063 head_off = (*mb_head_off)(line, line + startcol);
5064 if (base_class != mb_get_class(line + startcol
5065 - head_off))
5066 break;
5067 startcol -= head_off;
5068 }
5069 }
5070 else
5071 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5072 ;
5073 compl_col += ++startcol;
5074 compl_length = (int)curs_col - startcol;
5075 if (compl_length == 1)
5076 {
5077 // Only match word with at least two chars -- webb
5078 // there's no need to call quote_meta,
5079 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005080 compl_pattern.string = alloc(7);
5081 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005082 {
John Marriott5e6ea922024-11-23 14:01:57 +01005083 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005084 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005085 }
John Marriott5e6ea922024-11-23 14:01:57 +01005086 STRCPY((char *)compl_pattern.string, "\\<");
5087 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5088 STRCAT((char *)compl_pattern.string, "\\k");
5089 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005090 }
5091 else
5092 {
John Marriott5e6ea922024-11-23 14:01:57 +01005093 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5094
5095 compl_pattern.string = alloc(n);
5096 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005097 {
John Marriott5e6ea922024-11-23 14:01:57 +01005098 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005099 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005100 }
John Marriott5e6ea922024-11-23 14:01:57 +01005101 STRCPY((char *)compl_pattern.string, "\\<");
5102 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005103 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005104 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005105 }
5106 }
5107
5108 return OK;
5109}
5110
5111/*
5112 * Get the pattern, column and length for whole line completion or for the
5113 * complete() function.
5114 * Sets the global variables: compl_col, compl_length and compl_pattern.
5115 */
5116 static int
5117get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5118{
5119 compl_col = (colnr_T)getwhitecols(line);
5120 compl_length = (int)curs_col - (int)compl_col;
5121 if (compl_length < 0) // cursor in indent: empty pattern
5122 compl_length = 0;
5123 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005124 {
John Marriott5e6ea922024-11-23 14:01:57 +01005125 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5126 NULL, 0);
5127 if (compl_pattern.string == NULL)
5128 {
5129 compl_pattern.length = 0;
5130 return FAIL;
5131 }
5132 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005133 }
John Marriott5e6ea922024-11-23 14:01:57 +01005134 else
5135 {
5136 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5137 if (compl_pattern.string == NULL)
5138 {
5139 compl_pattern.length = 0;
5140 return FAIL;
5141 }
5142 compl_pattern.length = (size_t)compl_length;
5143 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005144
5145 return OK;
5146}
5147
5148/*
5149 * Get the pattern, column and length for filename completion.
5150 * Sets the global variables: compl_col, compl_length and compl_pattern.
5151 */
5152 static int
5153get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5154{
5155 // Go back to just before the first filename character.
5156 if (startcol > 0)
5157 {
5158 char_u *p = line + startcol;
5159
5160 MB_PTR_BACK(line, p);
5161 while (p > line && vim_isfilec(PTR2CHAR(p)))
5162 MB_PTR_BACK(line, p);
5163 if (p == line && vim_isfilec(PTR2CHAR(p)))
5164 startcol = 0;
5165 else
5166 startcol = (int)(p - line) + 1;
5167 }
5168
5169 compl_col += startcol;
5170 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005171 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5172 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005173 {
John Marriott5e6ea922024-11-23 14:01:57 +01005174 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005175 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005176 }
5177
John Marriott5e6ea922024-11-23 14:01:57 +01005178 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005179
5180 return OK;
5181}
5182
5183/*
5184 * Get the pattern, column and length for command-line completion.
5185 * Sets the global variables: compl_col, compl_length and compl_pattern.
5186 */
5187 static int
5188get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5189{
John Marriott5e6ea922024-11-23 14:01:57 +01005190 compl_pattern.string = vim_strnsave(line, curs_col);
5191 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005192 {
John Marriott5e6ea922024-11-23 14:01:57 +01005193 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005194 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005195 }
John Marriott5e6ea922024-11-23 14:01:57 +01005196 compl_pattern.length = curs_col;
5197 set_cmd_context(&compl_xp, compl_pattern.string,
5198 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005199 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5200 || compl_xp.xp_context == EXPAND_NOTHING)
5201 // No completion possible, use an empty pattern to get a
5202 // "pattern not found" message.
5203 compl_col = curs_col;
5204 else
John Marriott5e6ea922024-11-23 14:01:57 +01005205 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005206 compl_length = curs_col - compl_col;
5207
5208 return OK;
5209}
5210
5211/*
5212 * Get the pattern, column and length for user defined completion ('omnifunc',
5213 * 'completefunc' and 'thesaurusfunc')
5214 * Sets the global variables: compl_col, compl_length and compl_pattern.
5215 * Uses the global variable: spell_bad_len
5216 */
5217 static int
5218get_userdefined_compl_info(colnr_T curs_col UNUSED)
5219{
5220 int ret = FAIL;
5221
5222#ifdef FEAT_COMPL_FUNC
5223 // Call user defined function 'completefunc' with "a:findstart"
5224 // set to 1 to obtain the length of text to use for completion.
5225 char_u *line;
5226 typval_T args[3];
5227 int col;
5228 char_u *funcname;
5229 pos_T pos;
5230 int save_State = State;
5231 callback_T *cb;
5232
5233 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5234 // length as a string
5235 funcname = get_complete_funcname(ctrl_x_mode);
5236 if (*funcname == NUL)
5237 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005238 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005239 ? "completefunc" : "omnifunc");
5240 return FAIL;
5241 }
5242
5243 args[0].v_type = VAR_NUMBER;
5244 args[0].vval.v_number = 1;
5245 args[1].v_type = VAR_STRING;
5246 args[1].vval.v_string = (char_u *)"";
5247 args[2].v_type = VAR_UNKNOWN;
5248 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005249 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005250 cb = get_insert_callback(ctrl_x_mode);
5251 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005252 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005253
5254 State = save_State;
5255 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005256 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005257 validate_cursor();
5258 if (!EQUAL_POS(curwin->w_cursor, pos))
5259 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005260 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005261 return FAIL;
5262 }
5263
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005264 // Return value -2 means the user complete function wants to cancel the
5265 // complete without an error, do the same if the function did not execute
5266 // successfully.
5267 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005268 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005269 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005270 if (col == -3)
5271 {
5272 ctrl_x_mode = CTRL_X_NORMAL;
5273 edit_submode = NULL;
5274 if (!shortmess(SHM_COMPLETIONMENU))
5275 msg_clr_cmdline();
5276 return FAIL;
5277 }
5278
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005279 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005280 // completion.
5281 compl_opt_refresh_always = FALSE;
5282 compl_opt_suppress_empty = FALSE;
5283
5284 if (col < 0)
5285 col = curs_col;
5286 compl_col = col;
5287 if (compl_col > curs_col)
5288 compl_col = curs_col;
5289
5290 // Setup variables for completion. Need to obtain "line" again,
5291 // it may have become invalid.
5292 line = ml_get(curwin->w_cursor.lnum);
5293 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005294 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5295 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005296 {
John Marriott5e6ea922024-11-23 14:01:57 +01005297 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005298 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005299 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005300
John Marriott5e6ea922024-11-23 14:01:57 +01005301 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005302 ret = OK;
5303#endif
5304
5305 return ret;
5306}
5307
5308/*
5309 * Get the pattern, column and length for spell completion.
5310 * Sets the global variables: compl_col, compl_length and compl_pattern.
5311 * Uses the global variable: spell_bad_len
5312 */
5313 static int
5314get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5315{
5316 int ret = FAIL;
5317#ifdef FEAT_SPELL
5318 char_u *line;
5319
5320 if (spell_bad_len > 0)
5321 compl_col = curs_col - spell_bad_len;
5322 else
5323 compl_col = spell_word_start(startcol);
5324 if (compl_col >= (colnr_T)startcol)
5325 {
5326 compl_length = 0;
5327 compl_col = curs_col;
5328 }
5329 else
5330 {
5331 spell_expand_check_cap(compl_col);
5332 compl_length = (int)curs_col - compl_col;
5333 }
5334 // Need to obtain "line" again, it may have become invalid.
5335 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005336 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5337 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005338 {
John Marriott5e6ea922024-11-23 14:01:57 +01005339 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005340 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005341 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005342
John Marriott5e6ea922024-11-23 14:01:57 +01005343 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005344 ret = OK;
5345#endif
5346
5347 return ret;
5348}
5349
5350/*
5351 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005352 * "startcol" - start column number of the completion pattern/text
5353 * "cur_col" - current cursor column
5354 * On return, "line_invalid" is set to TRUE, if the current line may have
5355 * become invalid and needs to be fetched again.
5356 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005357 */
5358 static int
5359compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5360{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005361 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005362 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5363 && !thesaurus_func_complete(ctrl_x_mode)))
5364 {
5365 return get_normal_compl_info(line, startcol, curs_col);
5366 }
5367 else if (ctrl_x_mode_line_or_eval())
5368 {
5369 return get_wholeline_compl_info(line, curs_col);
5370 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005371 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005372 {
5373 return get_filename_compl_info(line, startcol, curs_col);
5374 }
5375 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5376 {
5377 return get_cmdline_compl_info(line, curs_col);
5378 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005379 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005380 || thesaurus_func_complete(ctrl_x_mode))
5381 {
5382 if (get_userdefined_compl_info(curs_col) == FAIL)
5383 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005384 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005385 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005386 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005387 {
5388 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5389 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005390 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005391 }
5392 else
5393 {
5394 internal_error("ins_complete()");
5395 return FAIL;
5396 }
5397
5398 return OK;
5399}
5400
5401/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005402 * Continue an interrupted completion mode search in "line".
5403 *
5404 * If this same ctrl_x_mode has been interrupted use the text from
5405 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5406 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5407 * the same line as the cursor then fix it (the line has been split because it
5408 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5409 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005410 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005411 static void
5412ins_compl_continue_search(char_u *line)
5413{
5414 // it is a continued search
5415 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005416 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5417 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005418 {
5419 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5420 {
5421 // line (probably) wrapped, set compl_startpos to the
5422 // first non_blank in the line, if it is not a wordchar
5423 // include it to get a better pattern, but then we don't
5424 // want the "\\<" prefix, check it below
5425 compl_col = (colnr_T)getwhitecols(line);
5426 compl_startpos.col = compl_col;
5427 compl_startpos.lnum = curwin->w_cursor.lnum;
5428 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5429 }
5430 else
5431 {
5432 // S_IPOS was set when we inserted a word that was at the
5433 // beginning of the line, which means that we'll go to SOL
5434 // mode but first we need to redefine compl_startpos
5435 if (compl_cont_status & CONT_S_IPOS)
5436 {
5437 compl_cont_status |= CONT_SOL;
5438 compl_startpos.col = (colnr_T)(skipwhite(
5439 line + compl_length
5440 + compl_startpos.col) - line);
5441 }
5442 compl_col = compl_startpos.col;
5443 }
5444 compl_length = curwin->w_cursor.col - (int)compl_col;
5445 // IObuff is used to add a "word from the next line" would we
5446 // have enough space? just being paranoid
5447#define MIN_SPACE 75
5448 if (compl_length > (IOSIZE - MIN_SPACE))
5449 {
5450 compl_cont_status &= ~CONT_SOL;
5451 compl_length = (IOSIZE - MIN_SPACE);
5452 compl_col = curwin->w_cursor.col - compl_length;
5453 }
5454 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5455 if (compl_length < 1)
5456 compl_cont_status &= CONT_LOCAL;
5457 }
5458 else if (ctrl_x_mode_line_or_eval())
5459 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5460 else
5461 compl_cont_status = 0;
5462}
5463
5464/*
5465 * start insert mode completion
5466 */
5467 static int
5468ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005469{
5470 char_u *line;
5471 int startcol = 0; // column where searched text starts
5472 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005473 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005474 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005475 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005476
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005477 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005478
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005479 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005480 did_si = FALSE;
5481 can_si = FALSE;
5482 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005483 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005484 return FAIL;
5485
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005486 line = ml_get(curwin->w_cursor.lnum);
5487 curs_col = curwin->w_cursor.col;
5488 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005489 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005491 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5492 && compl_cont_mode == ctrl_x_mode)
5493 // this same ctrl-x_mode was interrupted previously. Continue the
5494 // completion.
5495 ins_compl_continue_search(line);
5496 else
5497 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005498
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005499 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005500 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005501 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005502 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005503 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5504 compl_cont_status = 0;
5505 compl_cont_status |= CONT_N_ADDS;
5506 compl_startpos = curwin->w_cursor;
5507 startcol = (int)curs_col;
5508 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005509 }
5510
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005511 // Work out completion pattern and original text -- webb
5512 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5513 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005514 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5515 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005516 // restore did_ai, so that adding comment leader works
5517 did_ai = save_did_ai;
5518 return FAIL;
5519 }
5520 // If "line" was changed while getting completion info get it again.
5521 if (line_invalid)
5522 line = ml_get(curwin->w_cursor.lnum);
5523
glepnir7cfe6932024-09-15 20:06:28 +02005524 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005525 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005526 {
5527 edit_submode_pre = (char_u *)_(" Adding");
5528 if (ctrl_x_mode_line_or_eval())
5529 {
5530 // Insert a new line, keep indentation but ignore 'comments'.
5531 char_u *old = curbuf->b_p_com;
5532
5533 curbuf->b_p_com = (char_u *)"";
5534 compl_startpos.lnum = curwin->w_cursor.lnum;
5535 compl_startpos.col = compl_col;
5536 ins_eol('\r');
5537 curbuf->b_p_com = old;
5538 compl_length = 0;
5539 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01005540 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005541 }
glepnir7cfe6932024-09-15 20:06:28 +02005542 else if (ctrl_x_mode_normal() && in_fuzzy)
5543 {
5544 compl_startpos = curwin->w_cursor;
5545 compl_cont_status &= CONT_S_IPOS;
5546 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005547 }
5548 else
5549 {
5550 edit_submode_pre = NULL;
5551 compl_startpos.col = compl_col;
5552 }
5553
5554 if (compl_cont_status & CONT_LOCAL)
5555 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5556 else
5557 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5558
5559 // If any of the original typed text has been changed we need to fix
5560 // the redo buffer.
5561 ins_compl_fixRedoBufForLeader(NULL);
5562
5563 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005564 VIM_CLEAR_STRING(compl_orig_text);
5565 compl_orig_text.length = (size_t)compl_length;
5566 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005567 if (p_ic)
5568 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005569 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5570 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005571 {
John Marriott5e6ea922024-11-23 14:01:57 +01005572 VIM_CLEAR_STRING(compl_pattern);
5573 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005574 return FAIL;
5575 }
5576
5577 // showmode might reset the internal line pointers, so it must
5578 // be called before line = ml_get(), or when this address is no
5579 // longer needed. -- Acevedo.
5580 edit_submode_extra = (char_u *)_("-- Searching...");
5581 edit_submode_highl = HLF_COUNT;
5582 showmode();
5583 edit_submode_extra = NULL;
5584 out_flush();
5585
5586 return OK;
5587}
5588
5589/*
5590 * display the completion status message
5591 */
5592 static void
5593ins_compl_show_statusmsg(void)
5594{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005595 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005596 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005597 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005598 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005599 ? (char_u *)_("Hit end of paragraph")
5600 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005601 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005602 }
5603
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005604 if (edit_submode_extra == NULL)
5605 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005606 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005607 {
5608 edit_submode_extra = (char_u *)_("Back at original");
5609 edit_submode_highl = HLF_W;
5610 }
5611 else if (compl_cont_status & CONT_S_IPOS)
5612 {
5613 edit_submode_extra = (char_u *)_("Word from other line");
5614 edit_submode_highl = HLF_COUNT;
5615 }
5616 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5617 {
5618 edit_submode_extra = (char_u *)_("The only match");
5619 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005620 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005621 }
5622 else
5623 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005624#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005625 // Update completion sequence number when needed.
5626 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005627 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005628#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005629 // The match should always have a sequence number now, this is
5630 // just a safety check.
5631 if (compl_curr_match->cp_number != -1)
5632 {
5633 // Space for 10 text chars. + 2x10-digit no.s = 31.
5634 // Translations may need more than twice that.
5635 static char_u match_ref[81];
5636
5637 if (compl_matches > 0)
5638 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005639 _("match %d of %d"),
5640 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005641 else
5642 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005643 _("match %d"),
5644 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005645 edit_submode_extra = match_ref;
5646 edit_submode_highl = HLF_R;
5647 if (dollar_vcol >= 0)
5648 curs_columns(FALSE);
5649 }
5650 }
5651 }
5652
5653 // Show a message about what (completion) mode we're in.
5654 if (!compl_opt_suppress_empty)
5655 {
5656 showmode();
5657 if (!shortmess(SHM_COMPLETIONMENU))
5658 {
5659 if (edit_submode_extra != NULL)
5660 {
5661 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005662 {
5663 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005664 msg_attr((char *)edit_submode_extra,
5665 edit_submode_highl < HLF_COUNT
5666 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005667 msg_hist_off = FALSE;
5668 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005669 }
5670 else
5671 msg_clr_cmdline(); // necessary for "noshowmode"
5672 }
5673 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005674}
5675
5676/*
5677 * Do Insert mode completion.
5678 * Called when character "c" was typed, which has a meaning for completion.
5679 * Returns OK if completion was done, FAIL if something failed (out of mem).
5680 */
5681 int
5682ins_complete(int c, int enable_pum)
5683{
5684 int n;
5685 int save_w_wrow;
5686 int save_w_leftcol;
5687 int insert_match;
5688
5689 compl_direction = ins_compl_key2dir(c);
5690 insert_match = ins_compl_use_match(c);
5691
5692 if (!compl_started)
5693 {
5694 if (ins_compl_start() == FAIL)
5695 return FAIL;
5696 }
5697 else if (insert_match && stop_arrow() == FAIL)
5698 return FAIL;
5699
5700 compl_shown_match = compl_curr_match;
5701 compl_shows_dir = compl_direction;
5702
5703 // Find next match (and following matches).
5704 save_w_wrow = curwin->w_wrow;
5705 save_w_leftcol = curwin->w_leftcol;
5706 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5707
5708 // may undisplay the popup menu
5709 ins_compl_upd_pum();
5710
5711 if (n > 1) // all matches have been found
5712 compl_matches = n;
5713 compl_curr_match = compl_shown_match;
5714 compl_direction = compl_shows_dir;
5715
5716 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5717 // mode.
5718 if (got_int && !global_busy)
5719 {
5720 (void)vgetc();
5721 got_int = FALSE;
5722 }
5723
5724 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005725 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005726 {
5727 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5728 // because we couldn't expand anything at first place, but if we used
5729 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5730 // (such as M in M'exico) if not tried already. -- Acevedo
5731 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005732 || compl_status_adding()
5733 || (ctrl_x_mode_not_default()
5734 && !ctrl_x_mode_path_patterns()
5735 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005736 compl_cont_status &= ~CONT_N_ADDS;
5737 }
5738
5739 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5740 compl_cont_status |= CONT_S_IPOS;
5741 else
5742 compl_cont_status &= ~CONT_S_IPOS;
5743
5744 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005745
5746 // Show the popup menu, unless we got interrupted.
5747 if (enable_pum && !compl_interrupted)
5748 show_pum(save_w_wrow, save_w_leftcol);
5749
5750 compl_was_interrupted = compl_interrupted;
5751 compl_interrupted = FALSE;
5752
5753 return OK;
5754}
5755
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005756/*
5757 * Remove (if needed) and show the popup menu
5758 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005759 static void
5760show_pum(int prev_w_wrow, int prev_w_leftcol)
5761{
5762 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005763 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005764 RedrawingDisabled = 0;
5765
5766 // If the cursor moved or the display scrolled we need to remove the pum
5767 // first.
5768 setcursor();
5769 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5770 ins_compl_del_pum();
5771
5772 ins_compl_show_pum();
5773 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005774
5775 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005776}
5777
5778/*
5779 * Looks in the first "len" chars. of "src" for search-metachars.
5780 * If dest is not NULL the chars. are copied there quoting (with
5781 * a backslash) the metachars, and dest would be NUL terminated.
5782 * Returns the length (needed) of dest
5783 */
5784 static unsigned
5785quote_meta(char_u *dest, char_u *src, int len)
5786{
5787 unsigned m = (unsigned)len + 1; // one extra for the NUL
5788
5789 for ( ; --len >= 0; src++)
5790 {
5791 switch (*src)
5792 {
5793 case '.':
5794 case '*':
5795 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005796 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005797 break;
5798 // FALLTHROUGH
5799 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005800 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005801 break;
5802 // FALLTHROUGH
5803 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005804 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005805 break;
5806 // FALLTHROUGH
5807 case '^': // currently it's not needed.
5808 case '$':
5809 m++;
5810 if (dest != NULL)
5811 *dest++ = '\\';
5812 break;
5813 }
5814 if (dest != NULL)
5815 *dest++ = *src;
5816 // Copy remaining bytes of a multibyte character.
5817 if (has_mbyte)
5818 {
5819 int i, mb_len;
5820
5821 mb_len = (*mb_ptr2len)(src) - 1;
5822 if (mb_len > 0 && len >= mb_len)
5823 for (i = 0; i < mb_len; ++i)
5824 {
5825 --len;
5826 ++src;
5827 if (dest != NULL)
5828 *dest++ = *src;
5829 }
5830 }
5831 }
5832 if (dest != NULL)
5833 *dest = NUL;
5834
5835 return m;
5836}
5837
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005838#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005839 void
5840free_insexpand_stuff(void)
5841{
John Marriott5e6ea922024-11-23 14:01:57 +01005842 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005843# ifdef FEAT_EVAL
5844 free_callback(&cfu_cb);
5845 free_callback(&ofu_cb);
5846 free_callback(&tsrfu_cb);
5847# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005848}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005849#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005850
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005851#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005852/*
5853 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5854 * spelled word, if there is one.
5855 */
5856 static void
5857spell_back_to_badword(void)
5858{
5859 pos_T tpos = curwin->w_cursor;
5860
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005861 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005862 if (curwin->w_cursor.col != tpos.col)
5863 start_arrow(&tpos);
5864}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005865#endif