blob: 9a8d0faac7c26d8848e92b34287fea56fba767f0 [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/*
91 * Array indexes used for cp_text[].
92 */
93#define CPT_ABBR 0 // "abbr"
94#define CPT_MENU 1 // "menu"
95#define CPT_KIND 2 // "kind"
96#define CPT_INFO 3 // "info"
Bram Moolenaar08928322020-01-04 14:32:48 +010097#define CPT_COUNT 4 // Number of entries
Bram Moolenaar7591bb32019-03-30 13:53:47 +010098
99/*
100 * Structure used to store one match for insert completion.
101 */
102typedef struct compl_S compl_T;
103struct compl_S
104{
105 compl_T *cp_next;
106 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200107 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200108 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100109#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100110 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100111#endif
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200112 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113 // cp_flags has CP_FREE_FNAME
114 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200115 int cp_number; // sequence number
glepnira218cc62024-06-03 19:32:39 +0200116 int cp_score; // fuzzy match score
zeertzjq41008522024-07-27 13:21:49 +0200117 int cp_user_hlattr; // highlight attribute to combine with
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100118};
119
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200120// values for cp_flags
121# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
122# define CP_FREE_FNAME 2 // cp_fname is allocated
123# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
124# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
125# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200126# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100127
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100128/*
129 * All the current matches are stored in a list.
130 * "compl_first_match" points to the start of the list.
131 * "compl_curr_match" points to the currently selected entry.
132 * "compl_shown_match" is different from compl_curr_match during
133 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000134 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100135 */
136static compl_T *compl_first_match = NULL;
137static compl_T *compl_curr_match = NULL;
138static compl_T *compl_shown_match = NULL;
139static compl_T *compl_old_match = NULL;
140
141// After using a cursor key <Enter> selects a match in the popup menu,
142// otherwise it inserts a line break.
143static int compl_enter_selects = FALSE;
144
145// When "compl_leader" is not NULL only matches that start with this string
146// are used.
147static char_u *compl_leader = NULL;
148
149static int compl_get_longest = FALSE; // put longest common string
150 // in compl_leader
151
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100152// Selected one of the matches. When FALSE the match was edited or using the
153// longest common string.
154static int compl_used_match;
155
156// didn't finish finding completions.
157static int compl_was_interrupted = FALSE;
158
159// Set when character typed while looking for matches and it means we should
160// stop looking for matches.
161static int compl_interrupted = FALSE;
162
163static int compl_restarting = FALSE; // don't insert match
164
165// When the first completion is done "compl_started" is set. When it's
166// FALSE the word to be completed must be located.
167static int compl_started = FALSE;
168
169// Which Ctrl-X mode are we in?
170static int ctrl_x_mode = CTRL_X_NORMAL;
171
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000172static int compl_matches = 0; // number of completion matches
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100173static char_u *compl_pattern = NULL;
John Marriott8c85a2a2024-05-20 19:18:26 +0200174static size_t compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100175static int compl_direction = FORWARD;
176static int compl_shows_dir = FORWARD;
177static int compl_pending = 0; // > 1 for postponed CTRL-N
178static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000179// Length in bytes of the text being completed (this is deleted to be replaced
180// by the match.)
181static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100182static colnr_T compl_col = 0; // column where the text starts
183 // that is being completed
184static char_u *compl_orig_text = NULL; // text as it was before
185 // completion started
186static int compl_cont_mode = 0;
187static expand_T compl_xp;
188
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000189// List of flags for method of completion.
190static int compl_cont_status = 0;
191# define CONT_ADDING 1 // "normal" or "adding" expansion
192# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
193 // it's set only iff N_ADDS is set
194# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
195# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
196 // if so, word-wise-expansion will set SOL
197# define CONT_SOL 16 // pattern includes start of line, just for
198 // word-wise expansion, not set for ^X^L
199# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
200 // expansion, (eg use complete=.)
201
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100202static int compl_opt_refresh_always = FALSE;
203static int compl_opt_suppress_empty = FALSE;
204
glepnira218cc62024-06-03 19:32:39 +0200205static int compl_selected_item = -1;
206
glepnir8159fb12024-07-17 20:32:54 +0200207static int *compl_fuzzy_scores;
208
zeertzjq41008522024-07-27 13:21:49 +0200209static 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_hlattr);
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);
219static void ins_compl_set_original_text(char_u *str);
220static 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);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100230
231#ifdef FEAT_SPELL
232static void spell_back_to_badword(void);
233static int spell_bad_len = 0; // length of located bad word
234#endif
235
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100236/*
237 * CTRL-X pressed in Insert mode.
238 */
239 void
240ins_ctrl_x(void)
241{
zeertzjqdca29d92021-08-31 19:12:51 +0200242 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100243 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000244 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100245 if (compl_cont_status & CONT_N_ADDS)
246 compl_cont_status |= CONT_INTRPT;
247 else
248 compl_cont_status = 0;
249 // We're not sure which CTRL-X mode it will be yet
250 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
251 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
252 edit_submode_pre = NULL;
253 showmode();
254 }
zeertzjqdca29d92021-08-31 19:12:51 +0200255 else
256 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
257 // CTRL-V look like CTRL-N
258 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100259
LemonBoy2bf52dd2022-04-09 18:17:34 +0100260 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100261}
262
263/*
264 * Functions to check the current CTRL-X mode.
265 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000266int ctrl_x_mode_none(void)
267 { return ctrl_x_mode == 0; }
268int ctrl_x_mode_normal(void)
269 { return ctrl_x_mode == CTRL_X_NORMAL; }
270int ctrl_x_mode_scroll(void)
271 { return ctrl_x_mode == CTRL_X_SCROLL; }
272int ctrl_x_mode_whole_line(void)
273 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
274int ctrl_x_mode_files(void)
275 { return ctrl_x_mode == CTRL_X_FILES; }
276int ctrl_x_mode_tags(void)
277 { return ctrl_x_mode == CTRL_X_TAGS; }
278int ctrl_x_mode_path_patterns(void)
279 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
280int ctrl_x_mode_path_defines(void)
281 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
282int ctrl_x_mode_dictionary(void)
283 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
284int ctrl_x_mode_thesaurus(void)
285 { return ctrl_x_mode == CTRL_X_THESAURUS; }
286int ctrl_x_mode_cmdline(void)
287 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200288 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000289int ctrl_x_mode_function(void)
290 { return ctrl_x_mode == CTRL_X_FUNCTION; }
291int ctrl_x_mode_omni(void)
292 { return ctrl_x_mode == CTRL_X_OMNI; }
293int ctrl_x_mode_spell(void)
294 { return ctrl_x_mode == CTRL_X_SPELL; }
295static int ctrl_x_mode_eval(void)
296 { return ctrl_x_mode == CTRL_X_EVAL; }
297int ctrl_x_mode_line_or_eval(void)
298 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100299
300/*
301 * Whether other than default completion has been selected.
302 */
303 int
304ctrl_x_mode_not_default(void)
305{
306 return ctrl_x_mode != CTRL_X_NORMAL;
307}
308
309/*
zeertzjqdca29d92021-08-31 19:12:51 +0200310 * Whether CTRL-X was typed without a following character,
311 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100312 */
313 int
314ctrl_x_mode_not_defined_yet(void)
315{
316 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
317}
318
319/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000320 * Return TRUE if currently in "normal" or "adding" insert completion matches
321 * state
322 */
323 int
324compl_status_adding(void)
325{
326 return compl_cont_status & CONT_ADDING;
327}
328
329/*
330 * Return TRUE if the completion pattern includes start of line, just for
331 * word-wise expansion.
332 */
333 int
334compl_status_sol(void)
335{
336 return compl_cont_status & CONT_SOL;
337}
338
339/*
340 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
341 */
342 int
343compl_status_local(void)
344{
345 return compl_cont_status & CONT_LOCAL;
346}
347
348/*
349 * Clear the completion status flags
350 */
351 void
352compl_status_clear(void)
353{
354 compl_cont_status = 0;
355}
356
357/*
358 * Return TRUE if completion is using the forward direction matches
359 */
360 static int
361compl_dir_forward(void)
362{
363 return compl_direction == FORWARD;
364}
365
366/*
367 * Return TRUE if currently showing forward completion matches
368 */
369 static int
370compl_shows_dir_forward(void)
371{
372 return compl_shows_dir == FORWARD;
373}
374
375/*
376 * Return TRUE if currently showing backward completion matches
377 */
378 static int
379compl_shows_dir_backward(void)
380{
381 return compl_shows_dir == BACKWARD;
382}
383
384/*
385 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100386 */
387 int
388has_compl_option(int dict_opt)
389{
390 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200391#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100392 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200393#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100394 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100395 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
396#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100397 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100398#endif
399 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100400 {
401 ctrl_x_mode = CTRL_X_NORMAL;
402 edit_submode = NULL;
403 msg_attr(dict_opt ? _("'dictionary' option is empty")
404 : _("'thesaurus' option is empty"),
405 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100406 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100407 {
408 vim_beep(BO_COMPL);
409 setcursor();
410 out_flush();
411#ifdef FEAT_EVAL
412 if (!get_vim_var_nr(VV_TESTING))
413#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100414 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100415 }
416 return FALSE;
417 }
418 return TRUE;
419}
420
421/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000422 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100423 * This depends on the current mode.
424 */
425 int
426vim_is_ctrl_x_key(int c)
427{
428 // Always allow ^R - let its results then be checked
429 if (c == Ctrl_R)
430 return TRUE;
431
432 // Accept <PageUp> and <PageDown> if the popup menu is visible.
433 if (ins_compl_pum_key(c))
434 return TRUE;
435
436 switch (ctrl_x_mode)
437 {
438 case 0: // Not in any CTRL-X mode
439 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
440 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200441 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100442 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
443 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
444 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
445 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
446 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200447 || c == Ctrl_S || c == Ctrl_K || c == 's'
448 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100449 case CTRL_X_SCROLL:
450 return (c == Ctrl_Y || c == Ctrl_E);
451 case CTRL_X_WHOLE_LINE:
452 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
453 case CTRL_X_FILES:
454 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
455 case CTRL_X_DICTIONARY:
456 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
457 case CTRL_X_THESAURUS:
458 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
459 case CTRL_X_TAGS:
460 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
461#ifdef FEAT_FIND_ID
462 case CTRL_X_PATH_PATTERNS:
463 return (c == Ctrl_P || c == Ctrl_N);
464 case CTRL_X_PATH_DEFINES:
465 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
466#endif
467 case CTRL_X_CMDLINE:
468 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
469 || c == Ctrl_X);
470#ifdef FEAT_COMPL_FUNC
471 case CTRL_X_FUNCTION:
472 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
473 case CTRL_X_OMNI:
474 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
475#endif
476 case CTRL_X_SPELL:
477 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
478 case CTRL_X_EVAL:
479 return (c == Ctrl_P || c == Ctrl_N);
480 }
481 internal_error("vim_is_ctrl_x_key()");
482 return FALSE;
483}
484
485/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000486 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000487 */
488 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000489match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000490{
491 return match->cp_flags & CP_ORIGINAL_TEXT;
492}
493
494/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000495 * Returns TRUE if "match" is the first match in the completion list.
496 */
497 static int
498is_first_match(compl_T *match)
499{
500 return match == compl_first_match;
501}
502
503/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100504 * Return TRUE when character "c" is part of the item currently being
505 * completed. Used to decide whether to abandon complete mode when the menu
506 * is visible.
507 */
508 int
509ins_compl_accept_char(int c)
510{
511 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
512 // When expanding an identifier only accept identifier chars.
513 return vim_isIDc(c);
514
515 switch (ctrl_x_mode)
516 {
517 case CTRL_X_FILES:
518 // When expanding file name only accept file name chars. But not
519 // path separators, so that "proto/<Tab>" expands files in
520 // "proto", not "proto/" as a whole
521 return vim_isfilec(c) && !vim_ispathsep(c);
522
523 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200524 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100525 case CTRL_X_OMNI:
526 // Command line and Omni completion can work with just about any
527 // printable character, but do stop at white space.
528 return vim_isprintc(c) && !VIM_ISWHITE(c);
529
530 case CTRL_X_WHOLE_LINE:
531 // For while line completion a space can be part of the line.
532 return vim_isprintc(c);
533 }
534 return vim_iswordc(c);
535}
536
537/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000538 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100539 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000540 */
541 static char_u *
542ins_compl_infercase_gettext(
543 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100544 int char_len,
545 int compl_char_len,
546 int min_len,
547 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000548{
549 int *wca; // Wide character array.
550 char_u *p;
551 int i, c;
552 int has_lower = FALSE;
553 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100554 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000555
556 IObuff[0] = NUL;
557
558 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100559 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000560 if (wca == NULL)
561 return IObuff;
562
563 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100564 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000565 if (has_mbyte)
566 wca[i] = mb_ptr2char_adv(&p);
567 else
568 wca[i] = *(p++);
569
570 // Rule 1: Were any chars converted to lower?
571 p = compl_orig_text;
572 for (i = 0; i < min_len; ++i)
573 {
574 if (has_mbyte)
575 c = mb_ptr2char_adv(&p);
576 else
577 c = *(p++);
578 if (MB_ISLOWER(c))
579 {
580 has_lower = TRUE;
581 if (MB_ISUPPER(wca[i]))
582 {
583 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100584 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000585 wca[i] = MB_TOLOWER(wca[i]);
586 break;
587 }
588 }
589 }
590
591 // Rule 2: No lower case, 2nd consecutive letter converted to
592 // upper case.
593 if (!has_lower)
594 {
595 p = compl_orig_text;
596 for (i = 0; i < min_len; ++i)
597 {
598 if (has_mbyte)
599 c = mb_ptr2char_adv(&p);
600 else
601 c = *(p++);
602 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
603 {
604 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100605 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000606 wca[i] = MB_TOUPPER(wca[i]);
607 break;
608 }
609 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
610 }
611 }
612
613 // Copy the original case of the part we typed.
614 p = compl_orig_text;
615 for (i = 0; i < min_len; ++i)
616 {
617 if (has_mbyte)
618 c = mb_ptr2char_adv(&p);
619 else
620 c = *(p++);
621 if (MB_ISLOWER(c))
622 wca[i] = MB_TOLOWER(wca[i]);
623 else if (MB_ISUPPER(c))
624 wca[i] = MB_TOUPPER(wca[i]);
625 }
626
627 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000628 p = IObuff;
629 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100630 ga_init2(&gap, 1, 500);
631 while (i < char_len)
632 {
633 if (gap.ga_data != NULL)
634 {
635 if (ga_grow(&gap, 10) == FAIL)
636 {
637 ga_clear(&gap);
638 return (char_u *)"[failed]";
639 }
640 p = (char_u *)gap.ga_data + gap.ga_len;
641 if (has_mbyte)
642 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
643 else
644 {
645 *p = wca[i++];
646 ++gap.ga_len;
647 }
648 }
649 else if ((p - IObuff) + 6 >= IOSIZE)
650 {
651 // Multi-byte characters can occupy up to five bytes more than
652 // ASCII characters, and we also need one byte for NUL, so when
653 // getting to six bytes from the edge of IObuff switch to using a
654 // growarray. Add the character in the next round.
655 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100656 {
657 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100658 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100659 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100660 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100661 STRCPY(gap.ga_data, IObuff);
Bram Moolenaarc7bd2f02022-07-15 20:45:20 +0100662 gap.ga_len = (int)STRLEN(IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100663 }
664 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000665 p += (*mb_char2bytes)(wca[i++], p);
666 else
667 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100668 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000669 vim_free(wca);
670
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100671 if (gap.ga_data != NULL)
672 {
673 *tofree = gap.ga_data;
674 return gap.ga_data;
675 }
676
677 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000678 return IObuff;
679}
680
681/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100682 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
683 * case of the originally typed text is used, and the case of the completed
684 * text is inferred, ie this tries to work out what case you probably wanted
685 * the rest of the word to be in -- webb
686 */
687 int
688ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200689 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100690 int len,
691 int icase,
692 char_u *fname,
693 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200694 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100695{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200696 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100697 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100698 int char_len; // count multi-byte characters
699 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100700 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200701 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100702 int res;
703 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100704
705 if (p_ic && curbuf->b_p_inf && len > 0)
706 {
707 // Infer case of completed part.
708
709 // Find actual length of completion.
710 if (has_mbyte)
711 {
712 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100713 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100714 while (*p != NUL)
715 {
716 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100717 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100718 }
719 }
720 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100721 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100722
723 // Find actual length of original text.
724 if (has_mbyte)
725 {
726 p = compl_orig_text;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100727 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100728 while (*p != NUL)
729 {
730 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100731 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100732 }
733 }
734 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100735 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100736
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100737 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100738 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100739 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100740
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100741 str = ins_compl_infercase_gettext(str, char_len,
742 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100743 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200744 if (cont_s_ipos)
745 flags |= CP_CONT_S_IPOS;
746 if (icase)
747 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200748
glepnir508e7852024-07-25 21:39:08 +0200749 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, -1);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100750 vim_free(tofree);
751 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752}
753
754/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000755 * Add a match to the list of matches. The arguments are:
756 * str - text of the match to add
757 * len - length of "str". If -1, then the length of "str" is
758 * computed.
759 * fname - file name to associate with this match.
760 * cptext - list of strings to use with this match (for abbr, menu, info
761 * and kind)
762 * user_data - user supplied data (any vim type) for this match
763 * cdir - match direction. If 0, use "compl_direction".
764 * flags_arg - match flags (cp_flags)
765 * adup - accept this match even if it is already present.
766 * 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
zeertzjq41008522024-07-27 13:21:49 +0200783 int user_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)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100805 && STRNCMP(match->cp_str, str, len) == 0
Bram Moolenaarbaefde12022-07-07 19:59:49 +0100806 && ((int)STRLEN(match->cp_str) <= len
807 || match->cp_str[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;
824 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
825 {
826 vim_free(match);
827 return FAIL;
828 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829
830 // match-fname is:
831 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200832 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100833 // - NULL otherwise. --Acevedo
834 if (fname != NULL
835 && compl_curr_match != NULL
836 && compl_curr_match->cp_fname != NULL
837 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
838 match->cp_fname = compl_curr_match->cp_fname;
839 else if (fname != NULL)
840 {
841 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200842 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100843 }
844 else
845 match->cp_fname = NULL;
846 match->cp_flags = flags;
zeertzjq41008522024-07-27 13:21:49 +0200847 match->cp_user_hlattr = user_hlattr;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100848
849 if (cptext != NULL)
850 {
851 int i;
852
853 for (i = 0; i < CPT_COUNT; ++i)
854 if (cptext[i] != NULL && *cptext[i] != NUL)
855 match->cp_text[i] = vim_strsave(cptext[i]);
856 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100857#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100858 if (user_data != NULL)
859 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100860#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100861
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000862 // Link the new match structure after (FORWARD) or before (BACKWARD) the
863 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100864 if (compl_first_match == NULL)
865 match->cp_next = match->cp_prev = NULL;
866 else if (dir == FORWARD)
867 {
868 match->cp_next = compl_curr_match->cp_next;
869 match->cp_prev = compl_curr_match;
870 }
871 else // BACKWARD
872 {
873 match->cp_next = compl_curr_match;
874 match->cp_prev = compl_curr_match->cp_prev;
875 }
876 if (match->cp_next)
877 match->cp_next->cp_prev = match;
878 if (match->cp_prev)
879 match->cp_prev->cp_next = match;
880 else // if there's nothing before, it is the first match
881 compl_first_match = match;
882 compl_curr_match = match;
883
884 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200885 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100886 ins_compl_longest_match(match);
887
888 return OK;
889}
890
891/*
892 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200893 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100894 */
895 static int
896ins_compl_equal(compl_T *match, char_u *str, int len)
897{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200898 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200899 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200900 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100901 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
902 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
903}
904
905/*
906 * Reduce the longest common string for match "match".
907 */
908 static void
909ins_compl_longest_match(compl_T *match)
910{
911 char_u *p, *s;
912 int c1, c2;
913 int had_match;
914
915 if (compl_leader == NULL)
916 {
917 // First match, use it as a whole.
918 compl_leader = vim_strsave(match->cp_str);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000919 if (compl_leader == NULL)
920 return;
921
922 had_match = (curwin->w_cursor.col > compl_col);
923 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000924 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000925 ins_redraw(FALSE);
926
927 // When the match isn't there (to avoid matching itself) remove it
928 // again after redrawing.
929 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100930 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100931 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000932
933 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100934 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000935
936 // Reduce the text if this match differs from compl_leader.
937 p = compl_leader;
938 s = match->cp_str;
939 while (*p != NUL)
940 {
941 if (has_mbyte)
942 {
943 c1 = mb_ptr2char(p);
944 c2 = mb_ptr2char(s);
945 }
946 else
947 {
948 c1 = *p;
949 c2 = *s;
950 }
951 if ((match->cp_flags & CP_ICASE)
952 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
953 break;
954 if (has_mbyte)
955 {
956 MB_PTR_ADV(p);
957 MB_PTR_ADV(s);
958 }
959 else
960 {
961 ++p;
962 ++s;
963 }
964 }
965
966 if (*p != NUL)
967 {
968 // Leader was shortened, need to change the inserted text.
969 *p = NUL;
970 had_match = (curwin->w_cursor.col > compl_col);
971 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000972 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000973 ins_redraw(FALSE);
974
975 // When the match isn't there (to avoid matching itself) remove it
976 // again after redrawing.
977 if (!had_match)
978 ins_compl_delete();
979 }
980
981 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100982}
983
984/*
985 * Add an array of matches to the list of matches.
986 * Frees matches[].
987 */
988 static void
989ins_compl_add_matches(
990 int num_matches,
991 char_u **matches,
992 int icase)
993{
994 int i;
995 int add_r = OK;
996 int dir = compl_direction;
997
998 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100999 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnir508e7852024-07-25 21:39:08 +02001000 CP_FAST | (icase ? CP_ICASE : 0), FALSE, -1)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001001 // if dir was BACKWARD then honor it just once
1002 dir = FORWARD;
1003 FreeWild(num_matches, matches);
1004}
1005
1006/*
1007 * Make the completion list cyclic.
1008 * Return the number of matches (excluding the original).
1009 */
1010 static int
1011ins_compl_make_cyclic(void)
1012{
1013 compl_T *match;
1014 int count = 0;
1015
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001016 if (compl_first_match == NULL)
1017 return 0;
1018
1019 // Find the end of the list.
1020 match = compl_first_match;
1021 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001022 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001023 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001024 match = match->cp_next;
1025 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001026 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001027 match->cp_next = compl_first_match;
1028 compl_first_match->cp_prev = match;
1029
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001030 return count;
1031}
1032
1033/*
1034 * Return whether there currently is a shown match.
1035 */
1036 int
1037ins_compl_has_shown_match(void)
1038{
1039 return compl_shown_match == NULL
1040 || compl_shown_match != compl_shown_match->cp_next;
1041}
1042
1043/*
1044 * Return whether the shown match is long enough.
1045 */
1046 int
1047ins_compl_long_shown_match(void)
1048{
1049 return (int)STRLEN(compl_shown_match->cp_str)
1050 > curwin->w_cursor.col - compl_col;
1051}
1052
1053/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001054 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001055 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001056 unsigned int
1057get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001058{
zeertzjq529b9ad2024-06-05 20:27:06 +02001059 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001060}
1061
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001062
1063// "compl_match_array" points the currently displayed list of entries in the
1064// popup menu. It is NULL when there is no popup menu.
1065static pumitem_T *compl_match_array = NULL;
1066static int compl_match_arraysize;
1067
1068/*
1069 * Update the screen and when there is any scrolling remove the popup menu.
1070 */
1071 static void
1072ins_compl_upd_pum(void)
1073{
1074 int h;
1075
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001076 if (compl_match_array == NULL)
1077 return;
1078
1079 h = curwin->w_cline_height;
1080 // Update the screen later, before drawing the popup menu over it.
1081 pum_call_update_screen();
1082 if (h != curwin->w_cline_height)
1083 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001084}
1085
1086/*
1087 * Remove any popup menu.
1088 */
1089 static void
1090ins_compl_del_pum(void)
1091{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001092 if (compl_match_array == NULL)
1093 return;
1094
1095 pum_undisplay();
1096 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001097}
1098
1099/*
1100 * Return TRUE if the popup menu should be displayed.
1101 */
1102 int
1103pum_wanted(void)
1104{
1105 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001106 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001107 return FALSE;
1108
1109 // The display looks bad on a B&W display.
1110 if (t_colors < 8
1111#ifdef FEAT_GUI
1112 && !gui.in_use
1113#endif
1114 )
1115 return FALSE;
1116 return TRUE;
1117}
1118
1119/*
1120 * Return TRUE if there are two or more matches to be shown in the popup menu.
1121 * One if 'completopt' contains "menuone".
1122 */
1123 static int
1124pum_enough_matches(void)
1125{
1126 compl_T *compl;
1127 int i;
1128
1129 // Don't display the popup menu if there are no matches or there is only
1130 // one (ignoring the original text).
1131 compl = compl_first_match;
1132 i = 0;
1133 do
1134 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001135 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001136 break;
1137 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001138 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001139
zeertzjq529b9ad2024-06-05 20:27:06 +02001140 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001141 return (i >= 1);
1142 return (i >= 2);
1143}
1144
Bram Moolenaar3075a452021-11-17 15:51:52 +00001145#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001146/*
1147 * Allocate Dict for the completed item.
1148 * { word, abbr, menu, kind, info }
1149 */
1150 static dict_T *
1151ins_compl_dict_alloc(compl_T *match)
1152{
1153 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1154
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001155 if (dict == NULL)
1156 return NULL;
1157
1158 dict_add_string(dict, "word", match->cp_str);
1159 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1160 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1161 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1162 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1163 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1164 dict_add_string(dict, "user_data", (char_u *)"");
1165 else
1166 dict_add_tv(dict, "user_data", &match->cp_user_data);
1167
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001168 return dict;
1169}
1170
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001171/*
1172 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1173 * completion menu is changed.
1174 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001175 static void
1176trigger_complete_changed_event(int cur)
1177{
1178 dict_T *v_event;
1179 dict_T *item;
1180 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001181 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001182
1183 if (recursive)
1184 return;
1185
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001186 if (cur < 0)
1187 item = dict_alloc();
1188 else
1189 item = ins_compl_dict_alloc(compl_curr_match);
1190 if (item == NULL)
1191 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001192 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001193 dict_add_dict(v_event, "completed_item", item);
1194 pum_set_event_info(v_event);
1195 dict_set_items_ro(v_event);
1196
1197 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001198 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001199 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001200 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001201 recursive = FALSE;
1202
Bram Moolenaar3075a452021-11-17 15:51:52 +00001203 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001204}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001205#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001206
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001207/*
glepnira218cc62024-06-03 19:32:39 +02001208 * pumitem qsort compare func
1209 */
1210 static int
zeertzjq8e567472024-06-14 20:04:42 +02001211ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001212{
1213 const int sa = (*(pumitem_T *)a).pum_score;
1214 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001215 const int ia = (*(pumitem_T *)a).pum_idx;
1216 const int ib = (*(pumitem_T *)b).pum_idx;
1217 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001218}
1219
1220/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001221 * Build a popup menu to show the completion matches.
1222 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1223 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001224 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001225 static int
1226ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227{
1228 compl_T *compl;
1229 compl_T *shown_compl = NULL;
1230 int did_find_shown_match = FALSE;
1231 int shown_match_ok = FALSE;
1232 int i;
1233 int cur = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001234 int lead_len = 0;
glepnira218cc62024-06-03 19:32:39 +02001235 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001236 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001237 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1238 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001239
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001240 // Need to build the popup menu list.
1241 compl_match_arraysize = 0;
1242 compl = compl_first_match;
1243 if (compl_leader != NULL)
1244 lead_len = (int)STRLEN(compl_leader);
1245
1246 do
1247 {
zeertzjq551d8c32024-06-05 19:53:32 +02001248 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1249 // set the cp_score for later comparisons.
glepnira218cc62024-06-03 19:32:39 +02001250 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1251 compl->cp_score = fuzzy_match_str(compl->cp_str, compl_leader);
1252
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001253 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001254 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001255 || ins_compl_equal(compl, compl_leader, lead_len)
1256 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001257 ++compl_match_arraysize;
1258 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001259 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001260
1261 if (compl_match_arraysize == 0)
1262 return -1;
1263
1264 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1265 if (compl_match_array == NULL)
1266 return -1;
1267
1268 // If the current match is the original text don't find the first
1269 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001270 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001271 shown_match_ok = TRUE;
1272
glepnir53387c52024-05-27 15:11:01 +02001273 if (compl_leader != NULL
1274 && STRCMP(compl_leader, compl_orig_text) == 0
1275 && shown_match_ok == FALSE)
1276 compl_shown_match = compl_no_select ? compl_first_match
1277 : compl_first_match->cp_next;
1278
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001279 i = 0;
1280 compl = compl_first_match;
1281 do
1282 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001283 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001284 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001285 || ins_compl_equal(compl, compl_leader, lead_len)
1286 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001287 {
glepnira218cc62024-06-03 19:32:39 +02001288 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001289 {
1290 if (compl == compl_shown_match || did_find_shown_match)
1291 {
1292 // This item is the shown match or this is the
1293 // first displayed item after the shown match.
1294 compl_shown_match = compl;
1295 did_find_shown_match = TRUE;
1296 shown_match_ok = TRUE;
1297 }
1298 else
1299 // Remember this displayed match for when the
1300 // shown match is just below it.
1301 shown_compl = compl;
1302 cur = i;
1303 }
glepnira218cc62024-06-03 19:32:39 +02001304 else if (compl_fuzzy_match)
1305 {
glepnirf94c9c42024-06-14 21:11:56 +02001306 if (i == 0)
glepnir105f7412024-06-15 15:32:22 +02001307 shown_compl = compl;
glepnirdca57fb2024-06-04 22:01:21 +02001308 // Update the maximum fuzzy score and the shown match
1309 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001310 if (compl->cp_score > max_fuzzy_score)
1311 {
1312 did_find_shown_match = TRUE;
1313 max_fuzzy_score = compl->cp_score;
1314 compl_shown_match = compl;
glepnir65407ce2024-07-06 16:09:19 +02001315 }
1316
1317 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1318 {
1319 cur = i;
glepnira218cc62024-06-03 19:32:39 +02001320 shown_match_ok = TRUE;
1321 }
1322
glepnirdca57fb2024-06-04 22:01:21 +02001323 // If there is no "no select" condition and the max fuzzy
1324 // score is positive, or there is no completion leader or the
1325 // leader length is zero, mark the shown match as valid and
1326 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001327 if (!compl_no_select
1328 && (max_fuzzy_score > 0
1329 || (compl_leader == NULL || lead_len == 0)))
1330 {
glepnirf94c9c42024-06-14 21:11:56 +02001331 if (match_at_original_text(compl_shown_match))
glepnir105f7412024-06-15 15:32:22 +02001332 compl_shown_match = shown_compl;
glepnira218cc62024-06-03 19:32:39 +02001333 }
1334 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001335
1336 if (compl->cp_text[CPT_ABBR] != NULL)
1337 compl_match_array[i].pum_text =
1338 compl->cp_text[CPT_ABBR];
1339 else
1340 compl_match_array[i].pum_text = compl->cp_str;
1341 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1342 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001343 compl_match_array[i].pum_score = compl->cp_score;
zeertzjq41008522024-07-27 13:21:49 +02001344 compl_match_array[i].pum_user_hlattr = compl->cp_user_hlattr;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001345 if (compl->cp_text[CPT_MENU] != NULL)
1346 compl_match_array[i++].pum_extra =
1347 compl->cp_text[CPT_MENU];
1348 else
1349 compl_match_array[i++].pum_extra = compl->cp_fname;
1350 }
1351
glepnira218cc62024-06-03 19:32:39 +02001352 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001353 {
1354 did_find_shown_match = TRUE;
1355
1356 // When the original text is the shown match don't set
1357 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001358 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001359 shown_match_ok = TRUE;
1360
1361 if (!shown_match_ok && shown_compl != NULL)
1362 {
1363 // The shown match isn't displayed, set it to the
1364 // previously displayed match.
1365 compl_shown_match = shown_compl;
1366 shown_match_ok = TRUE;
1367 }
1368 }
1369 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001370 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001371
glepnira218cc62024-06-03 19:32:39 +02001372 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001373 {
1374 for (i = 0; i < compl_match_arraysize; i++)
1375 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001376 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001377 qsort(compl_match_array, (size_t)compl_match_arraysize,
1378 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001379 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001380 }
glepnira218cc62024-06-03 19:32:39 +02001381
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001382 if (!shown_match_ok) // no displayed match at all
1383 cur = -1;
1384
1385 return cur;
1386}
1387
1388/*
1389 * Show the popup menu for the list of matches.
1390 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1391 */
1392 void
1393ins_compl_show_pum(void)
1394{
1395 int i;
1396 int cur = -1;
1397 colnr_T col;
1398
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001399 if (!pum_wanted() || !pum_enough_matches())
1400 return;
1401
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001402 // Update the screen later, before drawing the popup menu over it.
1403 pum_call_update_screen();
1404
1405 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001406 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001407 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001408 else
1409 {
1410 // popup menu already exists, only need to find the current item.
1411 for (i = 0; i < compl_match_arraysize; ++i)
1412 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1413 || compl_match_array[i].pum_text
1414 == compl_shown_match->cp_text[CPT_ABBR])
1415 {
1416 cur = i;
1417 break;
1418 }
1419 }
1420
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001421 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001422 {
1423#ifdef FEAT_EVAL
1424 if (compl_started && has_completechanged())
1425 trigger_complete_changed_event(cur);
1426#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001427 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001428 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001429
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001430 // In Replace mode when a $ is displayed at the end of the line only
1431 // part of the screen would be updated. We do need to redraw here.
1432 dollar_vcol = -1;
1433
1434 // Compute the screen column of the start of the completed text.
1435 // Use the cursor to get all wrapping and other settings right.
1436 col = curwin->w_cursor.col;
1437 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001438 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001439 pum_display(compl_match_array, compl_match_arraysize, cur);
1440 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001441
glepnircbb46b42024-02-03 18:11:13 +01001442 // After adding leader, set the current match to shown match.
1443 if (compl_started && compl_curr_match != compl_shown_match)
1444 compl_curr_match = compl_shown_match;
1445
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001446#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001447 if (has_completechanged())
1448 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001449#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001450}
1451
1452#define DICT_FIRST (1) // use just first element in "dict"
1453#define DICT_EXACT (2) // "dict" is the exact name of a file
1454
1455/*
glepnir40c1c332024-06-11 19:37:04 +02001456 * Get current completion leader
1457 */
1458 char_u *
1459ins_compl_leader(void)
1460{
glepnirf1891382024-06-17 18:35:25 +02001461 return compl_leader != NULL ? compl_leader : compl_orig_text;
glepnir40c1c332024-06-11 19:37:04 +02001462}
1463
1464/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001465 * Add any identifiers that match the given pattern "pat" in the list of
1466 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001467 */
1468 static void
1469ins_compl_dictionaries(
1470 char_u *dict_start,
1471 char_u *pat,
1472 int flags, // DICT_FIRST and/or DICT_EXACT
1473 int thesaurus) // Thesaurus completion
1474{
1475 char_u *dict = dict_start;
1476 char_u *ptr;
1477 char_u *buf;
1478 regmatch_T regmatch;
1479 char_u **files;
1480 int count;
1481 int save_p_scs;
1482 int dir = compl_direction;
1483
1484 if (*dict == NUL)
1485 {
1486#ifdef FEAT_SPELL
1487 // When 'dictionary' is empty and spell checking is enabled use
1488 // "spell".
1489 if (!thesaurus && curwin->w_p_spell)
1490 dict = (char_u *)"spell";
1491 else
1492#endif
1493 return;
1494 }
1495
1496 buf = alloc(LSIZE);
1497 if (buf == NULL)
1498 return;
1499 regmatch.regprog = NULL; // so that we can goto theend
1500
1501 // If 'infercase' is set, don't use 'smartcase' here
1502 save_p_scs = p_scs;
1503 if (curbuf->b_p_inf)
1504 p_scs = FALSE;
1505
1506 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1507 // to only match at the start of a line. Otherwise just match the
1508 // pattern. Also need to double backslashes.
1509 if (ctrl_x_mode_line_or_eval())
1510 {
1511 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1512 size_t len;
1513
1514 if (pat_esc == NULL)
1515 goto theend;
1516 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001517 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001518 if (ptr == NULL)
1519 {
1520 vim_free(pat_esc);
1521 goto theend;
1522 }
1523 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1524 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1525 vim_free(pat_esc);
1526 vim_free(ptr);
1527 }
1528 else
1529 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001530 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001531 if (regmatch.regprog == NULL)
1532 goto theend;
1533 }
1534
1535 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1536 regmatch.rm_ic = ignorecase(pat);
1537 while (*dict != NUL && !got_int && !compl_interrupted)
1538 {
1539 // copy one dictionary file name into buf
1540 if (flags == DICT_EXACT)
1541 {
1542 count = 1;
1543 files = &dict;
1544 }
1545 else
1546 {
1547 // Expand wildcards in the dictionary name, but do not allow
1548 // backticks (for security, the 'dict' option may have been set in
1549 // a modeline).
1550 copy_option_part(&dict, buf, LSIZE, ",");
1551# ifdef FEAT_SPELL
1552 if (!thesaurus && STRCMP(buf, "spell") == 0)
1553 count = -1;
1554 else
1555# endif
1556 if (vim_strchr(buf, '`') != NULL
1557 || expand_wildcards(1, &buf, &count, &files,
1558 EW_FILE|EW_SILENT) != OK)
1559 count = 0;
1560 }
1561
1562# ifdef FEAT_SPELL
1563 if (count == -1)
1564 {
1565 // Complete from active spelling. Skip "\<" in the pattern, we
1566 // don't use it as a RE.
1567 if (pat[0] == '\\' && pat[1] == '<')
1568 ptr = pat + 2;
1569 else
1570 ptr = pat;
1571 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1572 }
1573 else
1574# endif
1575 if (count > 0) // avoid warning for using "files" uninit
1576 {
1577 ins_compl_files(count, files, thesaurus, flags,
1578 &regmatch, buf, &dir);
1579 if (flags != DICT_EXACT)
1580 FreeWild(count, files);
1581 }
1582 if (flags != 0)
1583 break;
1584 }
1585
1586theend:
1587 p_scs = save_p_scs;
1588 vim_regfree(regmatch.regprog);
1589 vim_free(buf);
1590}
1591
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001592/*
1593 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1594 * skipping the word at 'skip_word'. Returns OK on success.
1595 */
1596 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001597thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001598 char_u *fname,
1599 char_u **buf_arg,
1600 int dir,
1601 char_u *skip_word)
1602{
1603 int status = OK;
1604 char_u *ptr;
1605 char_u *wstart;
1606
1607 // Add the other matches on the line
1608 ptr = *buf_arg;
1609 while (!got_int)
1610 {
1611 // Find start of the next word. Skip white
1612 // space and punctuation.
1613 ptr = find_word_start(ptr);
1614 if (*ptr == NUL || *ptr == NL)
1615 break;
1616 wstart = ptr;
1617
1618 // Find end of the word.
1619 if (has_mbyte)
1620 // Japanese words may have characters in
1621 // different classes, only separate words
1622 // with single-byte non-word characters.
1623 while (*ptr != NUL)
1624 {
1625 int l = (*mb_ptr2len)(ptr);
1626
1627 if (l < 2 && !vim_iswordc(*ptr))
1628 break;
1629 ptr += l;
1630 }
1631 else
1632 ptr = find_word_end(ptr);
1633
1634 // Add the word. Skip the regexp match.
1635 if (wstart != skip_word)
1636 {
1637 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1638 fname, dir, FALSE);
1639 if (status == FAIL)
1640 break;
1641 }
1642 }
1643
1644 *buf_arg = ptr;
1645 return status;
1646}
1647
1648/*
1649 * Process "count" dictionary/thesaurus "files" and add the text matching
1650 * "regmatch".
1651 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001652 static void
1653ins_compl_files(
1654 int count,
1655 char_u **files,
1656 int thesaurus,
1657 int flags,
1658 regmatch_T *regmatch,
1659 char_u *buf,
1660 int *dir)
1661{
1662 char_u *ptr;
1663 int i;
1664 FILE *fp;
1665 int add_r;
1666
1667 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1668 {
1669 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001670 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001671 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001672 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001673 vim_snprintf((char *)IObuff, IOSIZE,
1674 _("Scanning dictionary: %s"), (char *)files[i]);
1675 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1676 }
1677
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001678 if (fp == NULL)
1679 continue;
1680
1681 // Read dictionary file line by line.
1682 // Check each line for a match.
1683 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001684 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001685 ptr = buf;
1686 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001687 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001688 ptr = regmatch->startp[0];
1689 if (ctrl_x_mode_line_or_eval())
1690 ptr = find_line_end(ptr);
1691 else
1692 ptr = find_word_end(ptr);
1693 add_r = ins_compl_add_infercase(regmatch->startp[0],
1694 (int)(ptr - regmatch->startp[0]),
1695 p_ic, files[i], *dir, FALSE);
1696 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001697 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001698 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001699 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001700 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001701 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001702 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001703 if (add_r == OK)
1704 // if dir was BACKWARD then honor it just once
1705 *dir = FORWARD;
1706 else if (add_r == FAIL)
1707 break;
1708 // avoid expensive call to vim_regexec() when at end
1709 // of line
1710 if (*ptr == '\n' || got_int)
1711 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001712 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001713 line_breakcheck();
1714 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001715 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001716 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001717 }
1718}
1719
1720/*
1721 * Find the start of the next word.
1722 * Returns a pointer to the first char of the word. Also stops at a NUL.
1723 */
1724 char_u *
1725find_word_start(char_u *ptr)
1726{
1727 if (has_mbyte)
1728 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1729 ptr += (*mb_ptr2len)(ptr);
1730 else
1731 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1732 ++ptr;
1733 return ptr;
1734}
1735
1736/*
1737 * Find the end of the word. Assumes it starts inside a word.
1738 * Returns a pointer to just after the word.
1739 */
1740 char_u *
1741find_word_end(char_u *ptr)
1742{
1743 int start_class;
1744
1745 if (has_mbyte)
1746 {
1747 start_class = mb_get_class(ptr);
1748 if (start_class > 1)
1749 while (*ptr != NUL)
1750 {
1751 ptr += (*mb_ptr2len)(ptr);
1752 if (mb_get_class(ptr) != start_class)
1753 break;
1754 }
1755 }
1756 else
1757 while (vim_iswordc(*ptr))
1758 ++ptr;
1759 return ptr;
1760}
1761
1762/*
1763 * Find the end of the line, omitting CR and NL at the end.
1764 * Returns a pointer to just after the line.
1765 */
1766 static char_u *
1767find_line_end(char_u *ptr)
1768{
1769 char_u *s;
1770
1771 s = ptr + STRLEN(ptr);
1772 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1773 --s;
1774 return s;
1775}
1776
1777/*
1778 * Free the list of completions
1779 */
1780 static void
1781ins_compl_free(void)
1782{
1783 compl_T *match;
1784 int i;
1785
1786 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001787 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001788 VIM_CLEAR(compl_leader);
1789
1790 if (compl_first_match == NULL)
1791 return;
1792
1793 ins_compl_del_pum();
1794 pum_clear();
1795
1796 compl_curr_match = compl_first_match;
1797 do
1798 {
1799 match = compl_curr_match;
1800 compl_curr_match = compl_curr_match->cp_next;
1801 vim_free(match->cp_str);
1802 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001803 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001804 vim_free(match->cp_fname);
1805 for (i = 0; i < CPT_COUNT; ++i)
1806 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001807#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001808 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001809#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001810 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001811 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001812 compl_first_match = compl_curr_match = NULL;
1813 compl_shown_match = NULL;
1814 compl_old_match = NULL;
1815}
1816
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001817/*
1818 * Reset/clear the completion state.
1819 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001820 void
1821ins_compl_clear(void)
1822{
1823 compl_cont_status = 0;
1824 compl_started = FALSE;
1825 compl_matches = 0;
1826 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001827 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001828 VIM_CLEAR(compl_leader);
1829 edit_submode_extra = NULL;
1830 VIM_CLEAR(compl_orig_text);
1831 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001832#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001833 // clear v:completed_item
1834 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001835#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001836}
1837
1838/*
1839 * Return TRUE when Insert completion is active.
1840 */
1841 int
1842ins_compl_active(void)
1843{
1844 return compl_started;
1845}
1846
1847/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001848 * Selected one of the matches. When FALSE the match was edited or using the
1849 * longest common string.
1850 */
1851 int
1852ins_compl_used_match(void)
1853{
1854 return compl_used_match;
1855}
1856
1857/*
1858 * Initialize get longest common string.
1859 */
1860 void
1861ins_compl_init_get_longest(void)
1862{
1863 compl_get_longest = FALSE;
1864}
1865
1866/*
1867 * Returns TRUE when insert completion is interrupted.
1868 */
1869 int
1870ins_compl_interrupted(void)
1871{
1872 return compl_interrupted;
1873}
1874
1875/*
1876 * Returns TRUE if the <Enter> key selects a match in the completion popup
1877 * menu.
1878 */
1879 int
1880ins_compl_enter_selects(void)
1881{
1882 return compl_enter_selects;
1883}
1884
1885/*
1886 * Return the column where the text starts that is being completed
1887 */
1888 colnr_T
1889ins_compl_col(void)
1890{
1891 return compl_col;
1892}
1893
1894/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001895 * Return the length in bytes of the text being completed
1896 */
1897 int
1898ins_compl_len(void)
1899{
1900 return compl_length;
1901}
1902
1903/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001904 * Delete one character before the cursor and show the subset of the matches
1905 * that match the word that is now before the cursor.
1906 * Returns the character to be used, NUL if the work is done and another char
1907 * to be got from the user.
1908 */
1909 int
1910ins_compl_bs(void)
1911{
1912 char_u *line;
1913 char_u *p;
1914
1915 line = ml_get_curline();
1916 p = line + curwin->w_cursor.col;
1917 MB_PTR_BACK(line, p);
1918
1919 // Stop completion when the whole word was deleted. For Omni completion
1920 // allow the word to be deleted, we won't match everything.
1921 // Respect the 'backspace' option.
1922 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001923 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1924 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001925 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1926 - compl_length < 0))
1927 return K_BS;
1928
1929 // Deleted more than what was used to find matches or didn't finish
1930 // finding all matches: need to look for matches all over again.
1931 if (curwin->w_cursor.col <= compl_col + compl_length
1932 || ins_compl_need_restart())
1933 ins_compl_restart();
1934
1935 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001936 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001937 if (compl_leader == NULL)
1938 return K_BS;
1939
1940 ins_compl_new_leader();
1941 if (compl_shown_match != NULL)
1942 // Make sure current match is not a hidden item.
1943 compl_curr_match = compl_shown_match;
1944 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001945}
1946
1947/*
1948 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1949 * be called.
1950 */
1951 static int
1952ins_compl_need_restart(void)
1953{
1954 // Return TRUE if we didn't complete finding matches or when the
1955 // 'completefunc' returned "always" in the "refresh" dictionary item.
1956 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001957 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001958 && compl_opt_refresh_always);
1959}
1960
1961/*
1962 * Called after changing "compl_leader".
1963 * Show the popup menu with a different set of matches.
1964 * May also search for matches again if the previous search was interrupted.
1965 */
1966 static void
1967ins_compl_new_leader(void)
1968{
1969 ins_compl_del_pum();
1970 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001971 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001972 compl_used_match = FALSE;
1973
1974 if (compl_started)
1975 ins_compl_set_original_text(compl_leader);
1976 else
1977 {
1978#ifdef FEAT_SPELL
1979 spell_bad_len = 0; // need to redetect bad word
1980#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001981 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001982 // the popup menu display the changed text before the cursor. Set
1983 // "compl_restarting" to avoid that the first match is inserted.
1984 pum_call_update_screen();
1985#ifdef FEAT_GUI
1986 if (gui.in_use)
1987 {
1988 // Show the cursor after the match, not after the redrawn text.
1989 setcursor();
1990 out_flush_cursor(FALSE, FALSE);
1991 }
1992#endif
1993 compl_restarting = TRUE;
1994 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1995 compl_cont_status = 0;
1996 compl_restarting = FALSE;
1997 }
1998
1999 compl_enter_selects = !compl_used_match;
2000
2001 // Show the popup menu with a different set of matches.
2002 ins_compl_show_pum();
2003
2004 // Don't let Enter select the original text when there is no popup menu.
2005 if (compl_match_array == NULL)
2006 compl_enter_selects = FALSE;
2007}
2008
2009/*
2010 * Return the length of the completion, from the completion start column to
2011 * the cursor column. Making sure it never goes below zero.
2012 */
2013 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002014get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002015{
2016 int off = (int)curwin->w_cursor.col - (int)compl_col;
2017
2018 if (off < 0)
2019 return 0;
2020 return off;
2021}
2022
2023/*
2024 * Append one character to the match leader. May reduce the number of
2025 * matches.
2026 */
2027 void
2028ins_compl_addleader(int c)
2029{
2030 int cc;
2031
2032 if (stop_arrow() == FAIL)
2033 return;
2034 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2035 {
2036 char_u buf[MB_MAXBYTES + 1];
2037
2038 (*mb_char2bytes)(c, buf);
2039 buf[cc] = NUL;
2040 ins_char_bytes(buf, cc);
2041 if (compl_opt_refresh_always)
2042 AppendToRedobuff(buf);
2043 }
2044 else
2045 {
2046 ins_char(c);
2047 if (compl_opt_refresh_always)
2048 AppendCharToRedobuff(c);
2049 }
2050
2051 // If we didn't complete finding matches we must search again.
2052 if (ins_compl_need_restart())
2053 ins_compl_restart();
2054
2055 // When 'always' is set, don't reset compl_leader. While completing,
2056 // cursor doesn't point original position, changing compl_leader would
2057 // break redo.
2058 if (!compl_opt_refresh_always)
2059 {
2060 vim_free(compl_leader);
2061 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002062 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002063 if (compl_leader != NULL)
2064 ins_compl_new_leader();
2065 }
2066}
2067
2068/*
2069 * Setup for finding completions again without leaving CTRL-X mode. Used when
2070 * BS or a key was typed while still searching for matches.
2071 */
2072 static void
2073ins_compl_restart(void)
2074{
2075 ins_compl_free();
2076 compl_started = FALSE;
2077 compl_matches = 0;
2078 compl_cont_status = 0;
2079 compl_cont_mode = 0;
2080}
2081
2082/*
2083 * Set the first match, the original text.
2084 */
2085 static void
2086ins_compl_set_original_text(char_u *str)
2087{
2088 char_u *p;
2089
2090 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002091 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2092 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002093 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002094 {
2095 p = vim_strsave(str);
2096 if (p != NULL)
2097 {
2098 vim_free(compl_first_match->cp_str);
2099 compl_first_match->cp_str = p;
2100 }
2101 }
2102 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002103 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002104 {
2105 p = vim_strsave(str);
2106 if (p != NULL)
2107 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002108 vim_free(compl_first_match->cp_prev->cp_str);
2109 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002110 }
2111 }
2112}
2113
2114/*
2115 * Append one character to the match leader. May reduce the number of
2116 * matches.
2117 */
2118 void
2119ins_compl_addfrommatch(void)
2120{
2121 char_u *p;
2122 int len = (int)curwin->w_cursor.col - (int)compl_col;
2123 int c;
2124 compl_T *cp;
2125
2126 p = compl_shown_match->cp_str;
2127 if ((int)STRLEN(p) <= len) // the match is too short
2128 {
2129 // When still at the original match use the first entry that matches
2130 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002131 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002132 return;
2133
2134 p = NULL;
2135 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002136 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002137 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002138 if (compl_leader == NULL
2139 || ins_compl_equal(cp, compl_leader,
2140 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002141 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002142 p = cp->cp_str;
2143 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002144 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002145 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002146 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002147 return;
2148 }
2149 p += len;
2150 c = PTR2CHAR(p);
2151 ins_compl_addleader(c);
2152}
2153
2154/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002155 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002156 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2157 * compl_cont_mode and compl_cont_status.
2158 * Returns TRUE when the character is not to be inserted.
2159 */
2160 static int
2161set_ctrl_x_mode(int c)
2162{
2163 int retval = FALSE;
2164
2165 switch (c)
2166 {
2167 case Ctrl_E:
2168 case Ctrl_Y:
2169 // scroll the window one line up or down
2170 ctrl_x_mode = CTRL_X_SCROLL;
2171 if (!(State & REPLACE_FLAG))
2172 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2173 else
2174 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2175 edit_submode_pre = NULL;
2176 showmode();
2177 break;
2178 case Ctrl_L:
2179 // complete whole line
2180 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2181 break;
2182 case Ctrl_F:
2183 // complete filenames
2184 ctrl_x_mode = CTRL_X_FILES;
2185 break;
2186 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002187 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002188 ctrl_x_mode = CTRL_X_DICTIONARY;
2189 break;
2190 case Ctrl_R:
2191 // Register insertion without exiting CTRL-X mode
2192 // Simply allow ^R to happen without affecting ^X mode
2193 break;
2194 case Ctrl_T:
2195 // complete words from a thesaurus
2196 ctrl_x_mode = CTRL_X_THESAURUS;
2197 break;
2198#ifdef FEAT_COMPL_FUNC
2199 case Ctrl_U:
2200 // user defined completion
2201 ctrl_x_mode = CTRL_X_FUNCTION;
2202 break;
2203 case Ctrl_O:
2204 // omni completion
2205 ctrl_x_mode = CTRL_X_OMNI;
2206 break;
2207#endif
2208 case 's':
2209 case Ctrl_S:
2210 // complete spelling suggestions
2211 ctrl_x_mode = CTRL_X_SPELL;
2212#ifdef FEAT_SPELL
2213 ++emsg_off; // Avoid getting the E756 error twice.
2214 spell_back_to_badword();
2215 --emsg_off;
2216#endif
2217 break;
2218 case Ctrl_RSB:
2219 // complete tag names
2220 ctrl_x_mode = CTRL_X_TAGS;
2221 break;
2222#ifdef FEAT_FIND_ID
2223 case Ctrl_I:
2224 case K_S_TAB:
2225 // complete keywords from included files
2226 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2227 break;
2228 case Ctrl_D:
2229 // complete definitions from included files
2230 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2231 break;
2232#endif
2233 case Ctrl_V:
2234 case Ctrl_Q:
2235 // complete vim commands
2236 ctrl_x_mode = CTRL_X_CMDLINE;
2237 break;
2238 case Ctrl_Z:
2239 // stop completion
2240 ctrl_x_mode = CTRL_X_NORMAL;
2241 edit_submode = NULL;
2242 showmode();
2243 retval = TRUE;
2244 break;
2245 case Ctrl_P:
2246 case Ctrl_N:
2247 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2248 // just started ^X mode, or there were enough ^X's to cancel
2249 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2250 // do normal expansion when interrupting a different mode (say
2251 // ^X^F^X^P or ^P^X^X^P, see below)
2252 // nothing changes if interrupting mode 0, (eg, the flag
2253 // doesn't change when going to ADDING mode -- Acevedo
2254 if (!(compl_cont_status & CONT_INTRPT))
2255 compl_cont_status |= CONT_LOCAL;
2256 else if (compl_cont_mode != 0)
2257 compl_cont_status &= ~CONT_LOCAL;
2258 // FALLTHROUGH
2259 default:
2260 // If we have typed at least 2 ^X's... for modes != 0, we set
2261 // compl_cont_status = 0 (eg, as if we had just started ^X
2262 // mode).
2263 // For mode 0, we set "compl_cont_mode" to an impossible
2264 // value, in both cases ^X^X can be used to restart the same
2265 // mode (avoiding ADDING mode).
2266 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2267 // 'complete' and local ^P expansions respectively.
2268 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2269 // mode -- Acevedo
2270 if (c == Ctrl_X)
2271 {
2272 if (compl_cont_mode != 0)
2273 compl_cont_status = 0;
2274 else
2275 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2276 }
2277 ctrl_x_mode = CTRL_X_NORMAL;
2278 edit_submode = NULL;
2279 showmode();
2280 break;
2281 }
2282
2283 return retval;
2284}
2285
2286/*
2287 * Stop insert completion mode
2288 */
2289 static int
2290ins_compl_stop(int c, int prev_mode, int retval)
2291{
2292 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002293 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002294
2295 // Get here when we have finished typing a sequence of ^N and
2296 // ^P or other completion characters in CTRL-X mode. Free up
2297 // memory that was used, and make sure we can redo the insert.
2298 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2299 {
2300 // If any of the original typed text has been changed, eg when
2301 // ignorecase is set, we must add back-spaces to the redo
2302 // buffer. We add as few as necessary to delete just the part
2303 // of the original text that has changed.
2304 // When using the longest match, edited the match or used
2305 // CTRL-E then don't use the current match.
2306 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2307 ptr = compl_curr_match->cp_str;
2308 else
2309 ptr = NULL;
2310 ins_compl_fixRedoBufForLeader(ptr);
2311 }
2312
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002313 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002314
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002315 // When completing whole lines: fix indent for 'cindent'.
2316 // Otherwise, break line if it's too long.
2317 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2318 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002319 // re-indent the current line
2320 if (want_cindent)
2321 {
2322 do_c_expr_indent();
2323 want_cindent = FALSE; // don't do it again
2324 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002325 }
2326 else
2327 {
2328 int prev_col = curwin->w_cursor.col;
2329
2330 // put the cursor on the last char, for 'tw' formatting
2331 if (prev_col > 0)
2332 dec_cursor();
2333 // only format when something was inserted
2334 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2335 insertchar(NUL, 0, -1);
2336 if (prev_col > 0
2337 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2338 inc_cursor();
2339 }
2340
2341 // If the popup menu is displayed pressing CTRL-Y means accepting
2342 // the selection without inserting anything. When
2343 // compl_enter_selects is set the Enter key does the same.
2344 if ((c == Ctrl_Y || (compl_enter_selects
2345 && (c == CAR || c == K_KENTER || c == NL)))
2346 && pum_visible())
2347 retval = TRUE;
2348
2349 // CTRL-E means completion is Ended, go back to the typed text.
2350 // but only do this, if the Popup is still visible
2351 if (c == Ctrl_E)
2352 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002353 char_u *p = NULL;
2354
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002355 ins_compl_delete();
2356 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002357 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002358 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002359 p = compl_orig_text;
2360 if (p != NULL)
2361 {
2362 int compl_len = get_compl_len();
2363 int len = (int)STRLEN(p);
2364
2365 if (len > compl_len)
2366 ins_bytes_len(p + compl_len, len - compl_len);
2367 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002368 retval = TRUE;
2369 }
2370
2371 auto_format(FALSE, TRUE);
2372
2373 // Trigger the CompleteDonePre event to give scripts a chance to
2374 // act upon the completion before clearing the info, and restore
2375 // ctrl_x_mode, so that complete_info() can be used.
2376 ctrl_x_mode = prev_mode;
2377 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2378
2379 ins_compl_free();
2380 compl_started = FALSE;
2381 compl_matches = 0;
2382 if (!shortmess(SHM_COMPLETIONMENU))
2383 msg_clr_cmdline(); // necessary for "noshowmode"
2384 ctrl_x_mode = CTRL_X_NORMAL;
2385 compl_enter_selects = FALSE;
2386 if (edit_submode != NULL)
2387 {
2388 edit_submode = NULL;
2389 showmode();
2390 }
2391
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002392 if (c == Ctrl_C && cmdwin_type != 0)
2393 // Avoid the popup menu remains displayed when leaving the
2394 // command line window.
2395 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002396 // Indent now if a key was typed that is in 'cinkeys'.
2397 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2398 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002399 // Trigger the CompleteDone event to give scripts a chance to act
2400 // upon the end of completion.
2401 ins_apply_autocmds(EVENT_COMPLETEDONE);
2402
2403 return retval;
2404}
2405
2406/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002407 * Prepare for Insert mode completion, or stop it.
2408 * Called just after typing a character in Insert mode.
2409 * Returns TRUE when the character is not to be inserted;
2410 */
2411 int
2412ins_compl_prep(int c)
2413{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002414 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002415 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002416
2417 // Forget any previous 'special' messages if this is actually
2418 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2419 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2420 edit_submode_extra = NULL;
2421
zeertzjq440d4cb2023-03-02 17:51:32 +00002422 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002423 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002424 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002425 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002426 return retval;
2427
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002428#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002429 // Ignore mouse events in a popup window
2430 if (is_mouse_key(c))
2431 {
2432 // Ignore drag and release events, the position does not need to be in
2433 // the popup and it may have just closed.
2434 if (c == K_LEFTRELEASE
2435 || c == K_LEFTRELEASE_NM
2436 || c == K_MIDDLERELEASE
2437 || c == K_RIGHTRELEASE
2438 || c == K_X1RELEASE
2439 || c == K_X2RELEASE
2440 || c == K_LEFTDRAG
2441 || c == K_MIDDLEDRAG
2442 || c == K_RIGHTDRAG
2443 || c == K_X1DRAG
2444 || c == K_X2DRAG)
2445 return retval;
2446 if (popup_visible)
2447 {
2448 int row = mouse_row;
2449 int col = mouse_col;
2450 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2451
2452 if (wp != NULL && WIN_IS_POPUP(wp))
2453 return retval;
2454 }
2455 }
2456#endif
2457
zeertzjqdca29d92021-08-31 19:12:51 +02002458 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2459 {
2460 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2461 || !vim_is_ctrl_x_key(c))
2462 {
2463 // Not starting another completion mode.
2464 ctrl_x_mode = CTRL_X_CMDLINE;
2465
2466 // CTRL-X CTRL-Z should stop completion without inserting anything
2467 if (c == Ctrl_Z)
2468 retval = TRUE;
2469 }
2470 else
2471 {
2472 ctrl_x_mode = CTRL_X_CMDLINE;
2473
2474 // Other CTRL-X keys first stop completion, then start another
2475 // completion mode.
2476 ins_compl_prep(' ');
2477 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2478 }
2479 }
2480
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002481 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002482 if (ctrl_x_mode_not_defined_yet()
2483 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002484 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002485 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002486 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002487 }
2488
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002489 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002490 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2491 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002492 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002493 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002494 {
2495 // We're already in CTRL-X mode, do we stay in it?
2496 if (!vim_is_ctrl_x_key(c))
2497 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002498 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002499 ctrl_x_mode = CTRL_X_NORMAL;
2500 else
2501 ctrl_x_mode = CTRL_X_FINISHED;
2502 edit_submode = NULL;
2503 }
2504 showmode();
2505 }
2506
2507 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2508 {
2509 // Show error message from attempted keyword completion (probably
2510 // 'Pattern not found') until another key is hit, then go back to
2511 // showing what mode we are in.
2512 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002513 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002514 && c != Ctrl_R && !ins_compl_pum_key(c))
2515 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002516 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002517 }
2518 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2519 // Trigger the CompleteDone event to give scripts a chance to act
2520 // upon the (possibly failed) completion.
2521 ins_apply_autocmds(EVENT_COMPLETEDONE);
2522
LemonBoy2bf52dd2022-04-09 18:17:34 +01002523 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002524
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002525 // reset continue_* if we left expansion-mode, if we stay they'll be
2526 // (re)set properly in ins_complete()
2527 if (!vim_is_ctrl_x_key(c))
2528 {
2529 compl_cont_status = 0;
2530 compl_cont_mode = 0;
2531 }
2532
2533 return retval;
2534}
2535
2536/*
2537 * Fix the redo buffer for the completion leader replacing some of the typed
2538 * text. This inserts backspaces and appends the changed text.
2539 * "ptr" is the known leader text or NUL.
2540 */
2541 static void
2542ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2543{
2544 int len;
2545 char_u *p;
2546 char_u *ptr = ptr_arg;
2547
2548 if (ptr == NULL)
2549 {
2550 if (compl_leader != NULL)
2551 ptr = compl_leader;
2552 else
2553 return; // nothing to do
2554 }
2555 if (compl_orig_text != NULL)
2556 {
2557 p = compl_orig_text;
2558 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2559 ;
2560 if (len > 0)
2561 len -= (*mb_head_off)(p, p + len);
2562 for (p += len; *p != NUL; MB_PTR_ADV(p))
2563 AppendCharToRedobuff(K_BS);
2564 }
2565 else
2566 len = 0;
2567 if (ptr != NULL)
2568 AppendToRedobuffLit(ptr + len, -1);
2569}
2570
2571/*
2572 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2573 * (depending on flag) starting from buf and looking for a non-scanned
2574 * buffer (other than curbuf). curbuf is special, if it is called with
2575 * buf=curbuf then it has to be the first call for a given flag/expansion.
2576 *
2577 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2578 */
2579 static buf_T *
2580ins_compl_next_buf(buf_T *buf, int flag)
2581{
2582 static win_T *wp = NULL;
2583
2584 if (flag == 'w') // just windows
2585 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002586 if (buf == curbuf || !win_valid(wp))
2587 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002588 wp = curwin;
2589 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2590 && wp->w_buffer->b_scanned)
2591 ;
2592 buf = wp->w_buffer;
2593 }
2594 else
2595 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2596 // (unlisted buffers)
2597 // When completing whole lines skip unloaded buffers.
2598 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2599 && ((flag == 'U'
2600 ? buf->b_p_bl
2601 : (!buf->b_p_bl
2602 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2603 || buf->b_scanned))
2604 ;
2605 return buf;
2606}
2607
2608#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002609
2610# ifdef FEAT_EVAL
2611static callback_T cfu_cb; // 'completefunc' callback function
2612static callback_T ofu_cb; // 'omnifunc' callback function
2613static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2614# endif
2615
2616/*
2617 * Copy a global callback function to a buffer local callback.
2618 */
2619 static void
2620copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2621{
2622 free_callback(bufcb);
2623 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2624 copy_callback(bufcb, globcb);
2625}
2626
2627/*
2628 * Parse the 'completefunc' option value and set the callback function.
2629 * Invoked when the 'completefunc' option is set. The option value can be a
2630 * name of a function (string), or function(<name>) or funcref(<name>) or a
2631 * lambda expression.
2632 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002633 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002634did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002635{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002636 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2637 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002638
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002639 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002640
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002641 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002642}
2643
2644/*
2645 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002646 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002647 */
2648 void
2649set_buflocal_cfu_callback(buf_T *buf UNUSED)
2650{
2651# ifdef FEAT_EVAL
2652 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2653# endif
2654}
2655
2656/*
2657 * Parse the 'omnifunc' option value and set the callback function.
2658 * Invoked when the 'omnifunc' option is set. The option value can be a
2659 * name of a function (string), or function(<name>) or funcref(<name>) or a
2660 * lambda expression.
2661 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002662 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002663did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002664{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002665 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2666 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002667
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002668 set_buflocal_ofu_callback(curbuf);
2669 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002670}
2671
2672/*
2673 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002674 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002675 */
2676 void
2677set_buflocal_ofu_callback(buf_T *buf UNUSED)
2678{
2679# ifdef FEAT_EVAL
2680 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2681# endif
2682}
2683
2684/*
2685 * Parse the 'thesaurusfunc' option value and set the callback function.
2686 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2687 * name of a function (string), or function(<name>) or funcref(<name>) or a
2688 * lambda expression.
2689 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002690 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002691did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002692{
2693 int retval;
2694
2695 if (*curbuf->b_p_tsrfu != NUL)
2696 {
2697 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002698 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2699 &curbuf->b_tsrfu_cb);
2700 }
2701 else
2702 {
2703 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002704 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2705 }
2706
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002707 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002708}
2709
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002710/*
2711 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002712 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002713 */
2714 int
2715set_ref_in_insexpand_funcs(int copyID)
2716{
2717 int abort = FALSE;
2718
2719 abort = set_ref_in_callback(&cfu_cb, copyID);
2720 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2721 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2722
2723 return abort;
2724}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002725
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002726/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002727 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002728 */
2729 static char_u *
2730get_complete_funcname(int type)
2731{
2732 switch (type)
2733 {
2734 case CTRL_X_FUNCTION:
2735 return curbuf->b_p_cfu;
2736 case CTRL_X_OMNI:
2737 return curbuf->b_p_ofu;
2738 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002739 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002740 default:
2741 return (char_u *)"";
2742 }
2743}
2744
2745/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002746 * Get the callback to use for insert mode completion.
2747 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002748 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002749get_insert_callback(int type)
2750{
2751 if (type == CTRL_X_FUNCTION)
2752 return &curbuf->b_cfu_cb;
2753 if (type == CTRL_X_OMNI)
2754 return &curbuf->b_ofu_cb;
2755 // CTRL_X_THESAURUS
2756 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2757}
2758
2759/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002760 * Execute user defined complete function 'completefunc', 'omnifunc' or
2761 * 'thesaurusfunc', and get matches in "matches".
2762 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002763 */
2764 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002765expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002766{
2767 list_T *matchlist = NULL;
2768 dict_T *matchdict = NULL;
2769 typval_T args[3];
2770 char_u *funcname;
2771 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002772 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002773 typval_T rettv;
2774 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002775 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002776
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002777 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002778 if (*funcname == NUL)
2779 return;
2780
2781 // Call 'completefunc' to obtain the list of matches.
2782 args[0].v_type = VAR_NUMBER;
2783 args[0].vval.v_number = 0;
2784 args[1].v_type = VAR_STRING;
2785 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2786 args[2].v_type = VAR_UNKNOWN;
2787
2788 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002789 // Lock the text to avoid weird things from happening. Also disallow
2790 // switching to another window, it should not be needed and may end up in
2791 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002792 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002793
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002794 cb = get_insert_callback(type);
2795 retval = call_callback(cb, 0, &rettv, 2, args);
2796
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002797 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002798 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002799 {
2800 switch (rettv.v_type)
2801 {
2802 case VAR_LIST:
2803 matchlist = rettv.vval.v_list;
2804 break;
2805 case VAR_DICT:
2806 matchdict = rettv.vval.v_dict;
2807 break;
2808 case VAR_SPECIAL:
2809 if (rettv.vval.v_number == VVAL_NONE)
2810 compl_opt_suppress_empty = TRUE;
2811 // FALLTHROUGH
2812 default:
2813 // TODO: Give error message?
2814 clear_tv(&rettv);
2815 break;
2816 }
2817 }
zeertzjqcfe45652022-05-27 17:26:55 +01002818 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002819
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002820 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002821 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002822 validate_cursor();
2823 if (!EQUAL_POS(curwin->w_cursor, pos))
2824 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002825 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002826 goto theend;
2827 }
2828
2829 if (matchlist != NULL)
2830 ins_compl_add_list(matchlist);
2831 else if (matchdict != NULL)
2832 ins_compl_add_dict(matchdict);
2833
2834theend:
2835 // Restore State, it might have been changed.
2836 State = save_State;
2837
2838 if (matchdict != NULL)
2839 dict_unref(matchdict);
2840 if (matchlist != NULL)
2841 list_unref(matchlist);
2842}
2843#endif // FEAT_COMPL_FUNC
2844
2845#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2846/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002847 * Add a match to the list of matches from a typeval_T.
2848 * If the given string is already in the list of completions, then return
2849 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2850 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002851 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002852 */
2853 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002854ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002855{
2856 char_u *word;
2857 int dup = FALSE;
2858 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002859 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002860 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002861 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002862 int status;
zeertzjq41008522024-07-27 13:21:49 +02002863 char_u *user_hlname;
2864 int user_hlattr = -1;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002865
Bram Moolenaar08928322020-01-04 14:32:48 +01002866 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002867 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2868 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002869 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2870 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2871 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2872 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2873 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
zeertzjq41008522024-07-27 13:21:49 +02002874 user_hlname = dict_get_string(tv->vval.v_dict, "hl_group", FALSE);
2875 if (user_hlname != NULL && *user_hlname != NUL)
2876 user_hlattr = syn_name2attr(user_hlname);
glepnir508e7852024-07-25 21:39:08 +02002877
Bram Moolenaard61efa52022-07-23 09:52:04 +01002878 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2879 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2880 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002881 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002882 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2883 dup = dict_get_number(tv->vval.v_dict, "dup");
2884 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2885 empty = dict_get_number(tv->vval.v_dict, "empty");
2886 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2887 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002888 flags |= CP_EQUAL;
2889 }
2890 else
2891 {
2892 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002893 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002894 }
2895 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002896 {
2897 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002898 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002899 }
glepnir508e7852024-07-25 21:39:08 +02002900 status = ins_compl_add(word, -1, NULL, cptext,
zeertzjq41008522024-07-27 13:21:49 +02002901 &user_data, dir, flags, dup, user_hlattr);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002902 if (status != OK)
2903 clear_tv(&user_data);
2904 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002905}
2906
2907/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002908 * Add completions from a list.
2909 */
2910 static void
2911ins_compl_add_list(list_T *list)
2912{
2913 listitem_T *li;
2914 int dir = compl_direction;
2915
2916 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002917 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002918 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002919 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002920 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002921 // if dir was BACKWARD then honor it just once
2922 dir = FORWARD;
2923 else if (did_emsg)
2924 break;
2925 }
2926}
2927
2928/*
2929 * Add completions from a dict.
2930 */
2931 static void
2932ins_compl_add_dict(dict_T *dict)
2933{
2934 dictitem_T *di_refresh;
2935 dictitem_T *di_words;
2936
2937 // Check for optional "refresh" item.
2938 compl_opt_refresh_always = FALSE;
2939 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2940 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2941 {
2942 char_u *v = di_refresh->di_tv.vval.v_string;
2943
2944 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2945 compl_opt_refresh_always = TRUE;
2946 }
2947
2948 // Add completions from a "words" list.
2949 di_words = dict_find(dict, (char_u *)"words", 5);
2950 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2951 ins_compl_add_list(di_words->di_tv.vval.v_list);
2952}
2953
2954/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002955 * Start completion for the complete() function.
2956 * "startcol" is where the matched text starts (1 is first column).
2957 * "list" is the list of matches.
2958 */
2959 static void
2960set_completion(colnr_T startcol, list_T *list)
2961{
2962 int save_w_wrow = curwin->w_wrow;
2963 int save_w_leftcol = curwin->w_leftcol;
2964 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002965 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002966 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2967 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2968 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002969
2970 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002971 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002972 ins_compl_prep(' ');
2973 ins_compl_clear();
2974 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002975 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002976
2977 compl_direction = FORWARD;
2978 if (startcol > curwin->w_cursor.col)
2979 startcol = curwin->w_cursor.col;
2980 compl_col = startcol;
2981 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2982 // compl_pattern doesn't need to be set
2983 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2984 if (p_ic)
2985 flags |= CP_ICASE;
2986 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002987 -1, NULL, NULL, NULL, 0,
glepnir508e7852024-07-25 21:39:08 +02002988 flags | CP_FAST, FALSE, -1) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002989 return;
2990
2991 ctrl_x_mode = CTRL_X_EVAL;
2992
2993 ins_compl_add_list(list);
2994 compl_matches = ins_compl_make_cyclic();
2995 compl_started = TRUE;
2996 compl_used_match = TRUE;
2997 compl_cont_status = 0;
2998
2999 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003000 int no_select = compl_no_select || compl_longest;
3001 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003002 {
3003 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003004 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003005 // Down/Up has no real effect.
3006 ins_complete(K_UP, FALSE);
3007 }
3008 else
3009 ins_complete(Ctrl_N, FALSE);
3010 compl_enter_selects = compl_no_insert;
3011
3012 // Lazily show the popup menu, unless we got interrupted.
3013 if (!compl_interrupted)
3014 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003015 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003016 out_flush();
3017}
3018
3019/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003020 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003021 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003022 void
3023f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003024{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003025 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003026
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003027 if (in_vim9script()
3028 && (check_for_number_arg(argvars, 0) == FAIL
3029 || check_for_list_arg(argvars, 1) == FAIL))
3030 return;
3031
Bram Moolenaar24959102022-05-07 20:01:16 +01003032 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003033 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003034 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003035 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003036 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003037
3038 // Check for undo allowed here, because if something was already inserted
3039 // the line was already saved for undo and this check isn't done.
3040 if (!undo_allowed())
3041 return;
3042
Bram Moolenaard83392a2022-09-01 12:22:46 +01003043 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003044 {
3045 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3046 if (startcol > 0)
3047 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003048 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003049}
3050
3051/*
3052 * "complete_add()" function
3053 */
3054 void
3055f_complete_add(typval_T *argvars, typval_T *rettv)
3056{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003057 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003058 return;
3059
Bram Moolenaar440cf092021-04-03 20:13:30 +02003060 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003061}
3062
3063/*
3064 * "complete_check()" function
3065 */
3066 void
3067f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3068{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003069 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003070 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003071
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003072 ins_compl_check_keys(0, TRUE);
3073 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003074
3075 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003076}
3077
3078/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003079 * Return Insert completion mode name string
3080 */
3081 static char_u *
3082ins_compl_mode(void)
3083{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003084 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003085 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3086
3087 return (char_u *)"";
3088}
3089
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003090/*
3091 * Assign the sequence number to all the completion matches which don't have
3092 * one assigned yet.
3093 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003094 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003095ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003096{
3097 int number = 0;
3098 compl_T *match;
3099
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003100 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003101 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003102 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003103 // This should normally succeed already at the first loop
3104 // cycle, so it's fast!
3105 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003106 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003107 if (match->cp_number != -1)
3108 {
3109 number = match->cp_number;
3110 break;
3111 }
3112 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003113 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003114 for (match = match->cp_next;
3115 match != NULL && match->cp_number == -1;
3116 match = match->cp_next)
3117 match->cp_number = ++number;
3118 }
3119 else // BACKWARD
3120 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003121 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003122 // number. This should normally succeed already at the
3123 // first loop cycle, so it's fast!
3124 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003125 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003126 if (match->cp_number != -1)
3127 {
3128 number = match->cp_number;
3129 break;
3130 }
3131 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003132 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003133 for (match = match->cp_prev; match
3134 && match->cp_number == -1;
3135 match = match->cp_prev)
3136 match->cp_number = ++number;
3137 }
3138}
3139
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003140/*
3141 * Get complete information
3142 */
3143 static void
3144get_complete_info(list_T *what_list, dict_T *retdict)
3145{
3146 int ret = OK;
3147 listitem_T *item;
3148#define CI_WHAT_MODE 0x01
3149#define CI_WHAT_PUM_VISIBLE 0x02
3150#define CI_WHAT_ITEMS 0x04
3151#define CI_WHAT_SELECTED 0x08
3152#define CI_WHAT_INSERTED 0x10
3153#define CI_WHAT_ALL 0xff
3154 int what_flag;
3155
3156 if (what_list == NULL)
3157 what_flag = CI_WHAT_ALL;
3158 else
3159 {
3160 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003161 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003162 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003163 {
3164 char_u *what = tv_get_string(&item->li_tv);
3165
3166 if (STRCMP(what, "mode") == 0)
3167 what_flag |= CI_WHAT_MODE;
3168 else if (STRCMP(what, "pum_visible") == 0)
3169 what_flag |= CI_WHAT_PUM_VISIBLE;
3170 else if (STRCMP(what, "items") == 0)
3171 what_flag |= CI_WHAT_ITEMS;
3172 else if (STRCMP(what, "selected") == 0)
3173 what_flag |= CI_WHAT_SELECTED;
3174 else if (STRCMP(what, "inserted") == 0)
3175 what_flag |= CI_WHAT_INSERTED;
3176 }
3177 }
3178
3179 if (ret == OK && (what_flag & CI_WHAT_MODE))
3180 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3181
3182 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3183 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3184
Girish Palya8950bf72024-03-20 20:07:29 +01003185 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003186 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003187 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003188 dict_T *di;
3189 compl_T *match;
3190 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003191
Girish Palya8950bf72024-03-20 20:07:29 +01003192 if (what_flag & CI_WHAT_ITEMS)
3193 {
3194 li = list_alloc();
3195 if (li == NULL)
3196 return;
3197 ret = dict_add_list(retdict, "items", li);
3198 }
3199 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3200 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3201 ins_compl_update_sequence_numbers();
3202 if (ret == OK && compl_first_match != NULL)
3203 {
3204 int list_idx = 0;
3205 match = compl_first_match;
3206 do
3207 {
3208 if (!match_at_original_text(match))
3209 {
3210 if (what_flag & CI_WHAT_ITEMS)
3211 {
3212 di = dict_alloc();
3213 if (di == NULL)
3214 return;
3215 ret = list_append_dict(li, di);
3216 if (ret != OK)
3217 return;
3218 dict_add_string(di, "word", match->cp_str);
3219 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3220 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3221 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3222 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3223 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3224 // Add an empty string for backwards compatibility
3225 dict_add_string(di, "user_data", (char_u *)"");
3226 else
3227 dict_add_tv(di, "user_data", &match->cp_user_data);
3228 }
3229 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3230 selected_idx = list_idx;
3231 list_idx += 1;
3232 }
3233 match = match->cp_next;
3234 }
3235 while (match != NULL && !is_first_match(match));
3236 }
3237 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3238 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003239 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003240
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003241 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3242 {
3243 // TODO
3244 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003245}
3246
3247/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003248 * "complete_info()" function
3249 */
3250 void
3251f_complete_info(typval_T *argvars, typval_T *rettv)
3252{
3253 list_T *what_list = NULL;
3254
Bram Moolenaar93a10962022-06-16 11:42:09 +01003255 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003256 return;
3257
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003258 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3259 return;
3260
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003261 if (argvars[0].v_type != VAR_UNKNOWN)
3262 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003263 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003264 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003265 what_list = argvars[0].vval.v_list;
3266 }
3267 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003268}
3269#endif
3270
3271/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003272 * Returns TRUE when using a user-defined function for thesaurus completion.
3273 */
3274 static int
3275thesaurus_func_complete(int type UNUSED)
3276{
3277#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003278 return type == CTRL_X_THESAURUS
3279 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003280#else
3281 return FALSE;
3282#endif
3283}
3284
3285/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003286 * Return value of process_next_cpt_value()
3287 */
3288enum
3289{
3290 INS_COMPL_CPT_OK = 1,
3291 INS_COMPL_CPT_CONT,
3292 INS_COMPL_CPT_END
3293};
3294
3295/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003296 * state information used for getting the next set of insert completion
3297 * matches.
3298 */
3299typedef struct
3300{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003301 char_u *e_cpt_copy; // copy of 'complete'
3302 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003303 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003304 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003305 pos_T prev_match_pos; // previous match position
3306 int set_match_pos; // save first_match_pos/last_match_pos
3307 pos_T first_match_pos; // first match position
3308 pos_T last_match_pos; // last match position
3309 int found_all; // found all matches of a certain type.
3310 char_u *dict; // dictionary file to search
3311 int dict_f; // "dict" is an exact file name or not
3312} ins_compl_next_state_T;
3313
3314/*
3315 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003316 *
3317 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003318 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003319 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003320 * st->found_all - all matches of this type are found
3321 * st->ins_buf - search for completions in this buffer
3322 * st->first_match_pos - position of the first completion match
3323 * st->last_match_pos - position of the last completion match
3324 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003325 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003326 * st->dict - name of the dictionary or thesaurus file to search
3327 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003328 *
3329 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003330 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3331 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003332 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003333 */
3334 static int
3335process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003336 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003337 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003338 pos_T *start_match_pos,
3339 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003340{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003341 int compl_type = -1;
3342 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003343
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003344 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003345
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003346 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3347 st->e_cpt++;
3348
3349 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003350 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003351 st->ins_buf = curbuf;
3352 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003353 // Move the cursor back one character so that ^N can match the
3354 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003355 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003356 {
3357 // Move the cursor to after the last character in the
3358 // buffer, so that word at start of buffer is found
3359 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003360 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003361 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003362 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003363 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003364 compl_type = 0;
3365
3366 // Remember the first match so that the loop stops when we
3367 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003368 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003369 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003370 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003371 && (st->ins_buf = ins_compl_next_buf(
3372 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003373 {
3374 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003375 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003376 {
3377 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003378 st->first_match_pos.col = st->last_match_pos.col = 0;
3379 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3380 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003381 compl_type = 0;
3382 }
3383 else // unloaded buffer, scan like dictionary
3384 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003385 st->found_all = TRUE;
3386 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003387 {
3388 status = INS_COMPL_CPT_CONT;
3389 goto done;
3390 }
3391 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003392 st->dict = st->ins_buf->b_fname;
3393 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003395 if (!shortmess(SHM_COMPLETIONSCAN))
3396 {
3397 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3398 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3399 st->ins_buf->b_fname == NULL
3400 ? buf_spname(st->ins_buf)
3401 : st->ins_buf->b_sfname == NULL
3402 ? st->ins_buf->b_fname
3403 : st->ins_buf->b_sfname);
3404 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3405 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003406 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003407 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003408 status = INS_COMPL_CPT_END;
3409 else
3410 {
3411 if (ctrl_x_mode_line_or_eval())
3412 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003413 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003414 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003415 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003416 compl_type = CTRL_X_DICTIONARY;
3417 else
3418 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003419 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003420 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003421 st->dict = st->e_cpt;
3422 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003423 }
3424 }
3425#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003426 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003427 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003428 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003429 compl_type = CTRL_X_PATH_DEFINES;
3430#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003431 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003432 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003433 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003434 if (!shortmess(SHM_COMPLETIONSCAN))
3435 {
3436 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3437 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3438 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3439 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003440 }
3441 else
3442 compl_type = -1;
3443
3444 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003445 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003446
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003447 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003448 if (compl_type == -1)
3449 status = INS_COMPL_CPT_CONT;
3450 }
3451
3452done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003453 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003454 return status;
3455}
3456
3457#ifdef FEAT_FIND_ID
3458/*
3459 * Get the next set of identifiers or defines matching "compl_pattern" in
3460 * included files.
3461 */
3462 static void
3463get_next_include_file_completion(int compl_type)
3464{
3465 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003466 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003467 (compl_type == CTRL_X_PATH_DEFINES
3468 && !(compl_cont_status & CONT_SOL))
3469 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003470 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003471}
3472#endif
3473
3474/*
3475 * Get the next set of words matching "compl_pattern" in dictionary or
3476 * thesaurus files.
3477 */
3478 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003479get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003480{
3481#ifdef FEAT_COMPL_FUNC
3482 if (thesaurus_func_complete(compl_type))
3483 expand_by_function(compl_type, compl_pattern);
3484 else
3485#endif
3486 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003487 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003488 : (compl_type == CTRL_X_THESAURUS
3489 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3490 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3491 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003492 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003493 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003494}
3495
3496/*
3497 * Get the next set of tag names matching "compl_pattern".
3498 */
3499 static void
3500get_next_tag_completion(void)
3501{
3502 int save_p_ic;
3503 char_u **matches;
3504 int num_matches;
3505
3506 // set p_ic according to p_ic, p_scs and pat for find_tags().
3507 save_p_ic = p_ic;
3508 p_ic = ignorecase(compl_pattern);
3509
3510 // Find up to TAG_MANY matches. Avoids that an enormous number
3511 // of matches is found when compl_pattern is empty
3512 g_tag_at_cursor = TRUE;
3513 if (find_tags(compl_pattern, &num_matches, &matches,
3514 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003515 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003516 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3517 ins_compl_add_matches(num_matches, matches, p_ic);
3518 g_tag_at_cursor = FALSE;
3519 p_ic = save_p_ic;
3520}
3521
3522/*
glepnir8159fb12024-07-17 20:32:54 +02003523 * Compare function for qsort
3524 */
3525static int compare_scores(const void *a, const void *b)
3526{
3527 int idx_a = *(const int *)a;
3528 int idx_b = *(const int *)b;
3529 int score_a = compl_fuzzy_scores[idx_a];
3530 int score_b = compl_fuzzy_scores[idx_b];
3531 return (score_a > score_b) ? -1 : (score_a < score_b) ? 1 : 0;
3532}
3533
3534/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003535 * Get the next set of filename matching "compl_pattern".
3536 */
3537 static void
3538get_next_filename_completion(void)
3539{
3540 char_u **matches;
3541 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003542 char_u *ptr;
3543 garray_T fuzzy_indices;
3544 int i;
3545 int score;
3546 char_u *leader = ins_compl_leader();
Ken Takata073cb022024-07-28 17:08:15 +02003547 size_t leader_len = STRLEN(leader);
glepnir8159fb12024-07-17 20:32:54 +02003548 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3549 char_u **sorted_matches;
3550 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003551 char_u *last_sep = NULL;
3552 size_t path_with_wildcard_len;
3553 char_u *path_with_wildcard;
glepnir8159fb12024-07-17 20:32:54 +02003554
glepnirb9de1a02024-08-02 19:14:38 +02003555#ifdef BACKSLASH_IN_FILENAME
3556 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3557 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3558#else
3559 char pathsep = PATHSEP;
3560#endif
3561
glepnir8159fb12024-07-17 20:32:54 +02003562 if (in_fuzzy)
3563 {
glepnirb9de1a02024-08-02 19:14:38 +02003564#ifdef BACKSLASH_IN_FILENAME
3565 if (curbuf->b_p_csl[0] == 's')
3566 {
3567 for (i = 0; i < leader_len; i++)
3568 {
3569 if (leader[i] == '\\')
3570 leader[i] = '/';
3571 }
3572 }
3573 else if (curbuf->b_p_csl[0] == 'b')
3574 {
3575 for (i = 0; i < leader_len; i++)
3576 {
3577 if (leader[i] == '/')
3578 leader[i] = '\\';
3579 }
3580 }
3581#endif
3582 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003583 if (last_sep == NULL)
3584 {
3585 // No path separator or separator is the last character,
3586 // fuzzy match the whole leader
3587 vim_free(compl_pattern);
3588 compl_pattern = vim_strsave((char_u *)"*");
3589 compl_patternlen = STRLEN(compl_pattern);
3590 }
3591 else if (*(last_sep + 1) == '\0')
3592 in_fuzzy = FALSE;
3593 else
3594 {
3595 // Split leader into path and file parts
3596 int path_len = last_sep - leader + 1;
3597 path_with_wildcard_len = path_len + 2;
3598 path_with_wildcard = alloc(path_with_wildcard_len);
3599 if (path_with_wildcard != NULL)
3600 {
3601 vim_strncpy(path_with_wildcard, leader, path_len);
3602 vim_strcat(path_with_wildcard, (char_u *)"*", path_with_wildcard_len);
3603 vim_free(compl_pattern);
3604 compl_pattern = path_with_wildcard;
3605 compl_patternlen = STRLEN(compl_pattern);
3606
3607 // Move leader to the file part
3608 leader = last_sep + 1;
glepnir6b6280c2024-07-27 16:25:45 +02003609 leader_len = STRLEN(leader);
glepnir0be03e12024-07-19 16:45:05 +02003610 }
3611 }
glepnir8159fb12024-07-17 20:32:54 +02003612 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003613
3614 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3615 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3616 return;
3617
3618 // May change home directory back to "~".
3619 tilde_replace(compl_pattern, num_matches, matches);
3620#ifdef BACKSLASH_IN_FILENAME
3621 if (curbuf->b_p_csl[0] != NUL)
3622 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003623 for (i = 0; i < num_matches; ++i)
3624 {
glepnir8159fb12024-07-17 20:32:54 +02003625 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003626 while (*ptr != NUL)
3627 {
3628 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3629 *ptr = '/';
3630 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3631 *ptr = '\\';
3632 ptr += (*mb_ptr2len)(ptr);
3633 }
3634 }
3635 }
3636#endif
glepnir8159fb12024-07-17 20:32:54 +02003637
3638 if (in_fuzzy)
3639 {
3640 ga_init2(&fuzzy_indices, sizeof(int), 10);
3641 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3642
3643 for (i = 0; i < num_matches; i++)
3644 {
3645 ptr = matches[i];
3646 score = fuzzy_match_str(ptr, leader);
3647 if (score > 0)
3648 {
3649 if (ga_grow(&fuzzy_indices, 1) == OK)
3650 {
3651 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3652 compl_fuzzy_scores[i] = score;
3653 fuzzy_indices.ga_len++;
3654 }
3655 }
3656 }
3657
Christian Brabandt220474d2024-07-20 13:26:44 +02003658 // prevent qsort from deref NULL pointer
3659 if (fuzzy_indices.ga_len > 0)
3660 {
3661 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3662 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003663
Christian Brabandt220474d2024-07-20 13:26:44 +02003664 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3665 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3666 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003667
Christian Brabandt220474d2024-07-20 13:26:44 +02003668 FreeWild(num_matches, matches);
3669 matches = sorted_matches;
3670 num_matches = fuzzy_indices.ga_len;
3671 }
glepnir6b6280c2024-07-27 16:25:45 +02003672 else if (leader_len > 0)
3673 {
3674 FreeWild(num_matches, matches);
3675 num_matches = 0;
3676 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003677
glepnir8159fb12024-07-17 20:32:54 +02003678 vim_free(compl_fuzzy_scores);
3679 ga_clear(&fuzzy_indices);
3680 }
3681
glepnir6b6280c2024-07-27 16:25:45 +02003682 if (num_matches > 0)
3683 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003684}
3685
3686/*
3687 * Get the next set of command-line completions matching "compl_pattern".
3688 */
3689 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003690get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003691{
3692 char_u **matches;
3693 int num_matches;
3694
3695 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003696 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003697 ins_compl_add_matches(num_matches, matches, FALSE);
3698}
3699
3700/*
3701 * Get the next set of spell suggestions matching "compl_pattern".
3702 */
3703 static void
3704get_next_spell_completion(linenr_T lnum UNUSED)
3705{
3706#ifdef FEAT_SPELL
3707 char_u **matches;
3708 int num_matches;
3709
3710 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3711 if (num_matches > 0)
3712 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003713 else
3714 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003715#endif
3716}
3717
3718/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003719 * Return the next word or line from buffer "ins_buf" at position
3720 * "cur_match_pos" for completion. The length of the match is set in "len".
3721 */
3722 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003723ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003724 buf_T *ins_buf, // buffer being scanned
3725 pos_T *cur_match_pos, // current match position
3726 int *match_len,
3727 int *cont_s_ipos) // next ^X<> will set initial_pos
3728{
3729 char_u *ptr;
3730 int len;
3731
3732 *match_len = 0;
3733 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3734 cur_match_pos->col;
3735 if (ctrl_x_mode_line_or_eval())
3736 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003737 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003738 {
3739 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3740 return NULL;
3741 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3742 if (!p_paste)
3743 ptr = skipwhite(ptr);
3744 }
3745 len = (int)STRLEN(ptr);
3746 }
3747 else
3748 {
3749 char_u *tmp_ptr = ptr;
3750
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003751 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003752 {
3753 tmp_ptr += compl_length;
3754 // Skip if already inside a word.
3755 if (vim_iswordp(tmp_ptr))
3756 return NULL;
3757 // Find start of next word.
3758 tmp_ptr = find_word_start(tmp_ptr);
3759 }
3760 // Find end of this word.
3761 tmp_ptr = find_word_end(tmp_ptr);
3762 len = (int)(tmp_ptr - ptr);
3763
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003764 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003765 {
3766 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3767 {
3768 // Try next line, if any. the new word will be
3769 // "join" as if the normal command "J" was used.
3770 // IOSIZE is always greater than
3771 // compl_length, so the next STRNCPY always
3772 // works -- Acevedo
3773 STRNCPY(IObuff, ptr, len);
3774 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3775 tmp_ptr = ptr = skipwhite(ptr);
3776 // Find start of next word.
3777 tmp_ptr = find_word_start(tmp_ptr);
3778 // Find end of next word.
3779 tmp_ptr = find_word_end(tmp_ptr);
3780 if (tmp_ptr > ptr)
3781 {
3782 if (*ptr != ')' && IObuff[len - 1] != TAB)
3783 {
3784 if (IObuff[len - 1] != ' ')
3785 IObuff[len++] = ' ';
3786 // IObuf =~ "\k.* ", thus len >= 2
3787 if (p_js
3788 && (IObuff[len - 2] == '.'
3789 || (vim_strchr(p_cpo, CPO_JOINSP)
3790 == NULL
3791 && (IObuff[len - 2] == '?'
3792 || IObuff[len - 2] == '!'))))
3793 IObuff[len++] = ' ';
3794 }
3795 // copy as much as possible of the new word
3796 if (tmp_ptr - ptr >= IOSIZE - len)
3797 tmp_ptr = ptr + IOSIZE - len - 1;
3798 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3799 len += (int)(tmp_ptr - ptr);
3800 *cont_s_ipos = TRUE;
3801 }
3802 IObuff[len] = NUL;
3803 ptr = IObuff;
3804 }
3805 if (len == compl_length)
3806 return NULL;
3807 }
3808 }
3809
3810 *match_len = len;
3811 return ptr;
3812}
3813
3814/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003815 * Get the next set of words matching "compl_pattern" for default completion(s)
3816 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003817 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3818 * position "st->start_pos" in the "compl_direction" direction. If
3819 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3820 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003821 * Returns OK if a new next match is found, otherwise returns FAIL.
3822 */
3823 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003824get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003825{
3826 int found_new_match = FAIL;
3827 int save_p_scs;
3828 int save_p_ws;
3829 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003830 char_u *ptr = NULL;
3831 int len = 0;
3832 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3833 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003834
3835 // If 'infercase' is set, don't use 'smartcase' here
3836 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003837 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003838 p_scs = FALSE;
3839
3840 // Buffers other than curbuf are scanned from the beginning or the
3841 // end but never from the middle, thus setting nowrapscan in this
3842 // buffer is a good idea, on the other hand, we always set
3843 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3844 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003845 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003846 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003847 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003848 p_ws = TRUE;
3849 looped_around = FALSE;
3850 for (;;)
3851 {
3852 int cont_s_ipos = FALSE;
3853
3854 ++msg_silent; // Don't want messages for wrapscan.
3855
3856 // ctrl_x_mode_line_or_eval() || word-wise search that
3857 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003858 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003859 found_new_match = search_for_exact_line(st->ins_buf,
3860 st->cur_match_pos, compl_direction, compl_pattern);
glepnir8159fb12024-07-17 20:32:54 +02003861 else if (in_fuzzy)
3862 found_new_match = search_for_fuzzy_match(st->ins_buf,
3863 st->cur_match_pos, leader, compl_direction,
3864 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003865 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003866 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003867 NULL, compl_direction, compl_pattern, compl_patternlen,
3868 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003869 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003870 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003871 {
3872 // set "compl_started" even on fail
3873 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003874 st->first_match_pos = *st->cur_match_pos;
3875 st->last_match_pos = *st->cur_match_pos;
3876 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003877 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003878 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3879 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003880 {
3881 found_new_match = FAIL;
3882 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003883 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003884 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3885 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3886 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003887 {
3888 if (looped_around)
3889 found_new_match = FAIL;
3890 else
3891 looped_around = TRUE;
3892 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003893 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003894 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3895 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3896 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003897 {
3898 if (looped_around)
3899 found_new_match = FAIL;
3900 else
3901 looped_around = TRUE;
3902 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003903 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003904 if (found_new_match == FAIL)
3905 break;
3906
3907 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003908 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003909 && start_pos->lnum == st->cur_match_pos->lnum
3910 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003911 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003912
glepnir8159fb12024-07-17 20:32:54 +02003913 if (!in_fuzzy)
3914 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3915 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003916 if (ptr == NULL)
3917 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003918
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003919 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003920 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003921 0, cont_s_ipos) != NOTDONE)
3922 {
3923 found_new_match = OK;
3924 break;
3925 }
3926 }
3927 p_scs = save_p_scs;
3928 p_ws = save_p_ws;
3929
3930 return found_new_match;
3931}
3932
3933/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003934 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003935 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003936 */
3937 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003938get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003939{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003940 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003941
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003942 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003943 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003944 case -1:
3945 break;
3946#ifdef FEAT_FIND_ID
3947 case CTRL_X_PATH_PATTERNS:
3948 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003949 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003950 break;
3951#endif
3952
3953 case CTRL_X_DICTIONARY:
3954 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003955 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3956 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003957 break;
3958
3959 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003960 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003961 break;
3962
3963 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003964 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003965 break;
3966
3967 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003968 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003969 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003970 break;
3971
3972#ifdef FEAT_COMPL_FUNC
3973 case CTRL_X_FUNCTION:
3974 case CTRL_X_OMNI:
3975 expand_by_function(type, compl_pattern);
3976 break;
3977#endif
3978
3979 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003980 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003981 break;
3982
3983 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003984 found_new_match = get_next_default_completion(st, ini);
3985 if (found_new_match == FAIL && st->ins_buf == curbuf)
3986 st->found_all = TRUE;
3987 }
3988
3989 // check if compl_curr_match has changed, (e.g. other type of
3990 // expansion added something)
3991 if (type != 0 && compl_curr_match != compl_old_match)
3992 found_new_match = OK;
3993
3994 return found_new_match;
3995}
3996
3997/*
3998 * Get the next expansion(s), using "compl_pattern".
3999 * The search starts at position "ini" in curbuf and in the direction
4000 * compl_direction.
4001 * When "compl_started" is FALSE start at that position, otherwise continue
4002 * where we stopped searching before.
4003 * This may return before finding all the matches.
4004 * Return the total number of matches or -1 if still unknown -- Acevedo
4005 */
4006 static int
4007ins_compl_get_exp(pos_T *ini)
4008{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004009 static ins_compl_next_state_T st;
4010 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004011 int i;
4012 int found_new_match;
4013 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004014 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004015
4016 if (!compl_started)
4017 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004018 buf_T *buf;
4019
4020 FOR_ALL_BUFFERS(buf)
4021 buf->b_scanned = 0;
4022 if (!st_cleared)
4023 {
4024 CLEAR_FIELD(st);
4025 st_cleared = TRUE;
4026 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004027 st.found_all = FALSE;
4028 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004029 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004030 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004031 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4032 ? (char_u *)"." : curbuf->b_p_cpt);
4033 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004034 st.last_match_pos = st.first_match_pos = *ini;
4035 }
4036 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4037 st.ins_buf = curbuf; // In case the buffer was wiped out.
4038
4039 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004040 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004041 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004042
4043 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4044 for (;;)
4045 {
4046 found_new_match = FAIL;
4047 st.set_match_pos = FALSE;
4048
4049 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4050 // or if found_all says this entry is done. For ^X^L only use the
4051 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004052 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004053 && (!compl_started || st.found_all))
4054 {
glepnir8159fb12024-07-17 20:32:54 +02004055 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004056
4057 if (status == INS_COMPL_CPT_END)
4058 break;
4059 if (status == INS_COMPL_CPT_CONT)
4060 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004061 }
4062
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004063 // If complete() was called then compl_pattern has been reset. The
4064 // following won't work then, bail out.
4065 if (compl_pattern == NULL)
4066 break;
4067
4068 // get the next set of completion matches
4069 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004070
4071 // break the loop for specialized modes (use 'complete' just for the
4072 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4073 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004074 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4075 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004076 {
4077 if (got_int)
4078 break;
4079 // Fill the popup menu as soon as possible.
4080 if (type != -1)
4081 ins_compl_check_keys(0, FALSE);
4082
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004083 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004084 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4085 break;
4086 compl_started = TRUE;
4087 }
4088 else
4089 {
4090 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004091 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004092 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004093
4094 compl_started = FALSE;
4095 }
4096 }
4097 compl_started = TRUE;
4098
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004099 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004100 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004101 found_new_match = FAIL;
4102
4103 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004104 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004105 && !ctrl_x_mode_line_or_eval()))
4106 i = ins_compl_make_cyclic();
4107
4108 if (compl_old_match != NULL)
4109 {
4110 // If several matches were added (FORWARD) or the search failed and has
4111 // just been made cyclic then we have to move compl_curr_match to the
4112 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004113 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004114 : compl_old_match->cp_prev;
4115 if (compl_curr_match == NULL)
4116 compl_curr_match = compl_old_match;
4117 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004118 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004119
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004120 return i;
4121}
4122
4123/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004124 * Update "compl_shown_match" to the actually shown match, it may differ when
4125 * "compl_leader" is used to omit some of the matches.
4126 */
4127 static void
4128ins_compl_update_shown_match(void)
4129{
4130 while (!ins_compl_equal(compl_shown_match,
4131 compl_leader, (int)STRLEN(compl_leader))
4132 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004133 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004134 compl_shown_match = compl_shown_match->cp_next;
4135
4136 // If we didn't find it searching forward, and compl_shows_dir is
4137 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004138 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004139 && !ins_compl_equal(compl_shown_match,
4140 compl_leader, (int)STRLEN(compl_leader))
4141 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004142 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004143 {
4144 while (!ins_compl_equal(compl_shown_match,
4145 compl_leader, (int)STRLEN(compl_leader))
4146 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004147 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004148 compl_shown_match = compl_shown_match->cp_prev;
4149 }
4150}
4151
4152/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004153 * Delete the old text being completed.
4154 */
4155 void
4156ins_compl_delete(void)
4157{
4158 int col;
4159
4160 // In insert mode: Delete the typed part.
4161 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004162 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004163 if ((int)curwin->w_cursor.col > col)
4164 {
4165 if (stop_arrow() == FAIL)
4166 return;
4167 backspace_until_column(col);
4168 }
4169
4170 // TODO: is this sufficient for redrawing? Redrawing everything causes
4171 // flicker, thus we can't do that.
4172 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004173#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004174 // clear v:completed_item
4175 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004176#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004177}
4178
4179/*
4180 * Insert the new text being completed.
4181 * "in_compl_func" is TRUE when called from complete_check().
4182 */
4183 void
4184ins_compl_insert(int in_compl_func)
4185{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004186 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004187
4188 // Make sure we don't go over the end of the string, this can happen with
4189 // illegal bytes.
4190 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4191 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004192 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004193 compl_used_match = FALSE;
4194 else
4195 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004196#ifdef FEAT_EVAL
4197 {
4198 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4199
4200 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4201 }
4202#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004203 if (!in_compl_func)
4204 compl_curr_match = compl_shown_match;
4205}
4206
4207/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004208 * show the file name for the completion match (if any). Truncate the file
4209 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004210 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004211 static void
4212ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004213{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004214 char *lead = _("match in file");
4215 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4216 char_u *s;
4217 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004218
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004219 if (space <= 0)
4220 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004221
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004222 // We need the tail that fits. With double-byte encoding going
4223 // back from the end is very slow, thus go from the start and keep
4224 // the text that fits in "space" between "s" and "e".
4225 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004226 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004227 space -= ptr2cells(e);
4228 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004229 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004230 space += ptr2cells(s);
4231 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004232 }
4233 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004234 msg_hist_off = TRUE;
4235 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4236 s > compl_shown_match->cp_fname ? "<" : "", s);
4237 msg((char *)IObuff);
4238 msg_hist_off = FALSE;
4239 redraw_cmdline = FALSE; // don't overwrite!
4240}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004241
glepnirdca57fb2024-06-04 22:01:21 +02004242/*
zeertzjq551d8c32024-06-05 19:53:32 +02004243 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004244 */
glepnira218cc62024-06-03 19:32:39 +02004245 static compl_T *
4246find_comp_when_fuzzy(void)
4247{
4248 int score;
4249 char_u* str;
4250 int target_idx = -1;
4251 int is_forward = compl_shows_dir_forward();
4252 int is_backward = compl_shows_dir_backward();
4253 compl_T *comp = NULL;
4254
glepnir43eef882024-06-19 20:20:48 +02004255 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004256 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004257 return compl_first_match != compl_shown_match ? compl_first_match :
4258 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004259
4260 if (is_forward)
4261 target_idx = compl_selected_item + 1;
4262 else if (is_backward)
4263 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004264 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004265
4266 score = compl_match_array[target_idx].pum_score;
4267 str = compl_match_array[target_idx].pum_text;
4268
4269 comp = compl_first_match;
4270 do {
4271 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4272 return comp;
4273 comp = comp->cp_next;
4274 } while (comp != NULL && !is_first_match(comp));
4275
4276 return NULL;
4277}
4278
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004279/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004280 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004281 * times. The number of matches found is returned in 'num_matches'.
4282 *
4283 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4284 * get more completions. If it is FALSE, then do nothing when there are no more
4285 * completions in the given direction.
4286 *
4287 * If "advance" is TRUE, then completion will move to the first match.
4288 * Otherwise, the original text will be shown.
4289 *
4290 * Returns OK on success and -1 if the number of matches are unknown.
4291 */
4292 static int
4293find_next_completion_match(
4294 int allow_get_expansion,
4295 int todo, // repeat completion this many times
4296 int advance,
4297 int *num_matches)
4298{
4299 int found_end = FALSE;
4300 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004301 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004302 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4303 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004304
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004305 while (--todo >= 0)
4306 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004307 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004308 {
glepniraced8c22024-06-15 15:13:05 +02004309 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4310 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004311 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004312 && (is_first_match(compl_shown_match->cp_next)
4313 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004314 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004315 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004316 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004317 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004318 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004319 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4320 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004321 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004322 }
4323 else
4324 {
4325 if (!allow_get_expansion)
4326 {
4327 if (advance)
4328 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004329 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004330 compl_pending -= todo + 1;
4331 else
4332 compl_pending += todo + 1;
4333 }
4334 return -1;
4335 }
4336
4337 if (!compl_no_select && advance)
4338 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004339 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004340 --compl_pending;
4341 else
4342 ++compl_pending;
4343 }
4344
4345 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004346 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004347
4348 // handle any pending completions
4349 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004350 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004351 {
4352 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4353 {
4354 compl_shown_match = compl_shown_match->cp_next;
4355 --compl_pending;
4356 }
4357 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4358 {
4359 compl_shown_match = compl_shown_match->cp_prev;
4360 ++compl_pending;
4361 }
4362 else
4363 break;
4364 }
4365 found_end = FALSE;
4366 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004367 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004368 && compl_leader != NULL
4369 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004370 compl_leader, (int)STRLEN(compl_leader))
4371 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004372 ++todo;
4373 else
4374 // Remember a matching item.
4375 found_compl = compl_shown_match;
4376
4377 // Stop at the end of the list when we found a usable match.
4378 if (found_end)
4379 {
4380 if (found_compl != NULL)
4381 {
4382 compl_shown_match = found_compl;
4383 break;
4384 }
4385 todo = 1; // use first usable match after wrapping around
4386 }
4387 }
4388
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004389 return OK;
4390}
4391
4392/*
4393 * Fill in the next completion in the current direction.
4394 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4395 * get more completions. If it is FALSE, then we just do nothing when there
4396 * are no more completions in a given direction. The latter case is used when
4397 * we are still in the middle of finding completions, to allow browsing
4398 * through the ones found so far.
4399 * Return the total number of matches, or -1 if still unknown -- webb.
4400 *
4401 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4402 * compl_shown_match here.
4403 *
4404 * Note that this function may be called recursively once only. First with
4405 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4406 * calls this function with "allow_get_expansion" FALSE.
4407 */
4408 static int
4409ins_compl_next(
4410 int allow_get_expansion,
4411 int count, // repeat completion this many times; should
4412 // be at least 1
4413 int insert_match, // Insert the newly selected match
4414 int in_compl_func) // called from complete_check()
4415{
4416 int num_matches = -1;
4417 int todo = count;
4418 int advance;
4419 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004420 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004421 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004422 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4423 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004424
4425 // When user complete function return -1 for findstart which is next
4426 // time of 'always', compl_shown_match become NULL.
4427 if (compl_shown_match == NULL)
4428 return -1;
4429
glepnira218cc62024-06-03 19:32:39 +02004430 if (compl_leader != NULL
4431 && !match_at_original_text(compl_shown_match)
4432 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004433 // Update "compl_shown_match" to the actually shown match
4434 ins_compl_update_shown_match();
4435
4436 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004437 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004438 // Delete old text to be replaced
4439 ins_compl_delete();
4440
4441 // When finding the longest common text we stick at the original text,
4442 // don't let CTRL-N or CTRL-P move to the first match.
4443 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4444
4445 // When restarting the search don't insert the first match either.
4446 if (compl_restarting)
4447 {
4448 advance = FALSE;
4449 compl_restarting = FALSE;
4450 }
4451
4452 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4453 // around.
4454 if (find_next_completion_match(allow_get_expansion, todo, advance,
4455 &num_matches) == -1)
4456 return -1;
4457
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004458 if (curbuf != orig_curbuf)
4459 {
4460 // In case some completion function switched buffer, don't want to
4461 // insert the completion elsewhere.
4462 return -1;
4463 }
4464
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004465 // Insert the text of the new completion, or the compl_leader.
4466 if (compl_no_insert && !started)
4467 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004468 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004469 compl_used_match = FALSE;
4470 }
4471 else if (insert_match)
4472 {
4473 if (!compl_get_longest || compl_used_match)
4474 ins_compl_insert(in_compl_func);
4475 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004476 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004477 }
4478 else
4479 compl_used_match = FALSE;
4480
4481 if (!allow_get_expansion)
4482 {
4483 // may undisplay the popup menu first
4484 ins_compl_upd_pum();
4485
4486 if (pum_enough_matches())
4487 // Will display the popup menu, don't redraw yet to avoid flicker.
4488 pum_call_update_screen();
4489 else
4490 // Not showing the popup menu yet, redraw to show the user what was
4491 // inserted.
4492 update_screen(0);
4493
4494 // display the updated popup menu
4495 ins_compl_show_pum();
4496#ifdef FEAT_GUI
4497 if (gui.in_use)
4498 {
4499 // Show the cursor after the match, not after the redrawn text.
4500 setcursor();
4501 out_flush_cursor(FALSE, FALSE);
4502 }
4503#endif
4504
4505 // Delete old text to be replaced, since we're still searching and
4506 // don't want to match ourselves!
4507 ins_compl_delete();
4508 }
4509
4510 // Enter will select a match when the match wasn't inserted and the popup
4511 // menu is visible.
4512 if (compl_no_insert && !started)
4513 compl_enter_selects = TRUE;
4514 else
4515 compl_enter_selects = !insert_match && compl_match_array != NULL;
4516
4517 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004518 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004519 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004520
4521 return num_matches;
4522}
4523
4524/*
4525 * Call this while finding completions, to check whether the user has hit a key
4526 * that should change the currently displayed completion, or exit completion
4527 * mode. Also, when compl_pending is not zero, show a completion as soon as
4528 * possible. -- webb
4529 * "frequency" specifies out of how many calls we actually check.
4530 * "in_compl_func" is TRUE when called from complete_check(), don't set
4531 * compl_curr_match.
4532 */
4533 void
4534ins_compl_check_keys(int frequency, int in_compl_func)
4535{
4536 static int count = 0;
4537 int c;
4538
4539 // Don't check when reading keys from a script, :normal or feedkeys().
4540 // That would break the test scripts. But do check for keys when called
4541 // from complete_check().
4542 if (!in_compl_func && (using_script() || ex_normal_busy))
4543 return;
4544
4545 // Only do this at regular intervals
4546 if (++count < frequency)
4547 return;
4548 count = 0;
4549
4550 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4551 // can't do its work correctly.
4552 c = vpeekc_any();
4553 if (c != NUL)
4554 {
4555 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4556 {
4557 c = safe_vgetc(); // Eat the character
4558 compl_shows_dir = ins_compl_key2dir(c);
4559 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4560 c != K_UP && c != K_DOWN, in_compl_func);
4561 }
4562 else
4563 {
4564 // Need to get the character to have KeyTyped set. We'll put it
4565 // back with vungetc() below. But skip K_IGNORE.
4566 c = safe_vgetc();
4567 if (c != K_IGNORE)
4568 {
4569 // Don't interrupt completion when the character wasn't typed,
4570 // e.g., when doing @q to replay keys.
4571 if (c != Ctrl_R && KeyTyped)
4572 compl_interrupted = TRUE;
4573
4574 vungetc(c);
4575 }
4576 }
4577 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004578 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004579 {
4580 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4581
4582 compl_pending = 0;
4583 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4584 }
4585}
4586
4587/*
4588 * Decide the direction of Insert mode complete from the key typed.
4589 * Returns BACKWARD or FORWARD.
4590 */
4591 static int
4592ins_compl_key2dir(int c)
4593{
4594 if (c == Ctrl_P || c == Ctrl_L
4595 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4596 return BACKWARD;
4597 return FORWARD;
4598}
4599
4600/*
4601 * Return TRUE for keys that are used for completion only when the popup menu
4602 * is visible.
4603 */
4604 static int
4605ins_compl_pum_key(int c)
4606{
4607 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4608 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4609 || c == K_UP || c == K_DOWN);
4610}
4611
4612/*
4613 * Decide the number of completions to move forward.
4614 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4615 */
4616 static int
4617ins_compl_key2count(int c)
4618{
4619 int h;
4620
4621 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4622 {
4623 h = pum_get_height();
4624 if (h > 3)
4625 h -= 2; // keep some context
4626 return h;
4627 }
4628 return 1;
4629}
4630
4631/*
4632 * Return TRUE if completion with "c" should insert the match, FALSE if only
4633 * to change the currently selected completion.
4634 */
4635 static int
4636ins_compl_use_match(int c)
4637{
4638 switch (c)
4639 {
4640 case K_UP:
4641 case K_DOWN:
4642 case K_PAGEDOWN:
4643 case K_KPAGEDOWN:
4644 case K_S_DOWN:
4645 case K_PAGEUP:
4646 case K_KPAGEUP:
4647 case K_S_UP:
4648 return FALSE;
4649 }
4650 return TRUE;
4651}
4652
4653/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004654 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4655 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004656 * Sets the global variables: compl_col, compl_length, compl_pattern and
4657 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004658 * Uses the global variables: compl_cont_status and ctrl_x_mode
4659 */
4660 static int
4661get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4662{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004663 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004664 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004665 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004666 {
4667 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4668 ;
4669 compl_col += ++startcol;
4670 compl_length = curs_col - startcol;
4671 }
4672 if (p_ic)
4673 compl_pattern = str_foldcase(line + compl_col,
4674 compl_length, NULL, 0);
4675 else
4676 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4677 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004678 {
4679 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004680 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004681 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004682 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004683 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004684 {
4685 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004686 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004687
4688 // we need up to 2 extra chars for the prefix
4689 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004690 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004691 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004692 {
4693 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004694 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004695 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004696 if (!vim_iswordp(line + compl_col)
4697 || (compl_col > 0
4698 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004699 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004700 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004701 prefixlen = 0;
4702 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004703 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004704 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004705 line + compl_col, compl_length);
4706 }
4707 else if (--startcol < 0
4708 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4709 {
4710 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004711 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004712 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004713 {
4714 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004715 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004716 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004717 compl_col += curs_col;
4718 compl_length = 0;
4719 }
4720 else
4721 {
4722 // Search the point of change class of multibyte character
4723 // or not a word single byte character backward.
4724 if (has_mbyte)
4725 {
4726 int base_class;
4727 int head_off;
4728
4729 startcol -= (*mb_head_off)(line, line + startcol);
4730 base_class = mb_get_class(line + startcol);
4731 while (--startcol >= 0)
4732 {
4733 head_off = (*mb_head_off)(line, line + startcol);
4734 if (base_class != mb_get_class(line + startcol
4735 - head_off))
4736 break;
4737 startcol -= head_off;
4738 }
4739 }
4740 else
4741 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4742 ;
4743 compl_col += ++startcol;
4744 compl_length = (int)curs_col - startcol;
4745 if (compl_length == 1)
4746 {
4747 // Only match word with at least two chars -- webb
4748 // there's no need to call quote_meta,
4749 // alloc(7) is enough -- Acevedo
4750 compl_pattern = alloc(7);
4751 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004752 {
4753 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004754 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004755 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004756 STRCPY((char *)compl_pattern, "\\<");
4757 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4758 STRCAT((char *)compl_pattern, "\\k");
4759 }
4760 else
4761 {
4762 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4763 compl_length) + 2);
4764 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004765 {
4766 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004767 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004768 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004769 STRCPY((char *)compl_pattern, "\\<");
4770 (void)quote_meta(compl_pattern + 2, line + compl_col,
4771 compl_length);
4772 }
4773 }
4774
John Marriott8c85a2a2024-05-20 19:18:26 +02004775 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004776 return OK;
4777}
4778
4779/*
4780 * Get the pattern, column and length for whole line completion or for the
4781 * complete() function.
4782 * Sets the global variables: compl_col, compl_length and compl_pattern.
4783 */
4784 static int
4785get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4786{
4787 compl_col = (colnr_T)getwhitecols(line);
4788 compl_length = (int)curs_col - (int)compl_col;
4789 if (compl_length < 0) // cursor in indent: empty pattern
4790 compl_length = 0;
4791 if (p_ic)
4792 compl_pattern = str_foldcase(line + compl_col, compl_length,
4793 NULL, 0);
4794 else
4795 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4796 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004797 {
4798 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004799 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004800 }
4801
4802 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004803
4804 return OK;
4805}
4806
4807/*
4808 * Get the pattern, column and length for filename completion.
4809 * Sets the global variables: compl_col, compl_length and compl_pattern.
4810 */
4811 static int
4812get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4813{
4814 // Go back to just before the first filename character.
4815 if (startcol > 0)
4816 {
4817 char_u *p = line + startcol;
4818
4819 MB_PTR_BACK(line, p);
4820 while (p > line && vim_isfilec(PTR2CHAR(p)))
4821 MB_PTR_BACK(line, p);
4822 if (p == line && vim_isfilec(PTR2CHAR(p)))
4823 startcol = 0;
4824 else
4825 startcol = (int)(p - line) + 1;
4826 }
4827
4828 compl_col += startcol;
4829 compl_length = (int)curs_col - startcol;
4830 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4831 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004832 {
4833 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004834 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004835 }
4836
4837 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004838
4839 return OK;
4840}
4841
4842/*
4843 * Get the pattern, column and length for command-line completion.
4844 * Sets the global variables: compl_col, compl_length and compl_pattern.
4845 */
4846 static int
4847get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4848{
4849 compl_pattern = vim_strnsave(line, curs_col);
4850 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004851 {
4852 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004853 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004854 }
4855 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004856 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004857 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004858 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4859 || compl_xp.xp_context == EXPAND_NOTHING)
4860 // No completion possible, use an empty pattern to get a
4861 // "pattern not found" message.
4862 compl_col = curs_col;
4863 else
4864 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4865 compl_length = curs_col - compl_col;
4866
4867 return OK;
4868}
4869
4870/*
4871 * Get the pattern, column and length for user defined completion ('omnifunc',
4872 * 'completefunc' and 'thesaurusfunc')
4873 * Sets the global variables: compl_col, compl_length and compl_pattern.
4874 * Uses the global variable: spell_bad_len
4875 */
4876 static int
4877get_userdefined_compl_info(colnr_T curs_col UNUSED)
4878{
4879 int ret = FAIL;
4880
4881#ifdef FEAT_COMPL_FUNC
4882 // Call user defined function 'completefunc' with "a:findstart"
4883 // set to 1 to obtain the length of text to use for completion.
4884 char_u *line;
4885 typval_T args[3];
4886 int col;
4887 char_u *funcname;
4888 pos_T pos;
4889 int save_State = State;
4890 callback_T *cb;
4891
4892 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4893 // length as a string
4894 funcname = get_complete_funcname(ctrl_x_mode);
4895 if (*funcname == NUL)
4896 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004897 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004898 ? "completefunc" : "omnifunc");
4899 return FAIL;
4900 }
4901
4902 args[0].v_type = VAR_NUMBER;
4903 args[0].vval.v_number = 1;
4904 args[1].v_type = VAR_STRING;
4905 args[1].vval.v_string = (char_u *)"";
4906 args[2].v_type = VAR_UNKNOWN;
4907 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004908 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004909 cb = get_insert_callback(ctrl_x_mode);
4910 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004911 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004912
4913 State = save_State;
4914 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004915 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004916 validate_cursor();
4917 if (!EQUAL_POS(curwin->w_cursor, pos))
4918 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004919 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004920 return FAIL;
4921 }
4922
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004923 // Return value -2 means the user complete function wants to cancel the
4924 // complete without an error, do the same if the function did not execute
4925 // successfully.
4926 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004927 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004928 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004929 if (col == -3)
4930 {
4931 ctrl_x_mode = CTRL_X_NORMAL;
4932 edit_submode = NULL;
4933 if (!shortmess(SHM_COMPLETIONMENU))
4934 msg_clr_cmdline();
4935 return FAIL;
4936 }
4937
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004938 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004939 // completion.
4940 compl_opt_refresh_always = FALSE;
4941 compl_opt_suppress_empty = FALSE;
4942
4943 if (col < 0)
4944 col = curs_col;
4945 compl_col = col;
4946 if (compl_col > curs_col)
4947 compl_col = curs_col;
4948
4949 // Setup variables for completion. Need to obtain "line" again,
4950 // it may have become invalid.
4951 line = ml_get(curwin->w_cursor.lnum);
4952 compl_length = curs_col - compl_col;
4953 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4954 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004955 {
4956 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004957 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004958 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004959
John Marriott8c85a2a2024-05-20 19:18:26 +02004960 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004961 ret = OK;
4962#endif
4963
4964 return ret;
4965}
4966
4967/*
4968 * Get the pattern, column and length for spell completion.
4969 * Sets the global variables: compl_col, compl_length and compl_pattern.
4970 * Uses the global variable: spell_bad_len
4971 */
4972 static int
4973get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4974{
4975 int ret = FAIL;
4976#ifdef FEAT_SPELL
4977 char_u *line;
4978
4979 if (spell_bad_len > 0)
4980 compl_col = curs_col - spell_bad_len;
4981 else
4982 compl_col = spell_word_start(startcol);
4983 if (compl_col >= (colnr_T)startcol)
4984 {
4985 compl_length = 0;
4986 compl_col = curs_col;
4987 }
4988 else
4989 {
4990 spell_expand_check_cap(compl_col);
4991 compl_length = (int)curs_col - compl_col;
4992 }
4993 // Need to obtain "line" again, it may have become invalid.
4994 line = ml_get(curwin->w_cursor.lnum);
4995 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4996 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004997 {
4998 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004999 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005000 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005001
John Marriott8c85a2a2024-05-20 19:18:26 +02005002 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005003 ret = OK;
5004#endif
5005
5006 return ret;
5007}
5008
5009/*
5010 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005011 * "startcol" - start column number of the completion pattern/text
5012 * "cur_col" - current cursor column
5013 * On return, "line_invalid" is set to TRUE, if the current line may have
5014 * become invalid and needs to be fetched again.
5015 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005016 */
5017 static int
5018compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5019{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005020 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005021 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5022 && !thesaurus_func_complete(ctrl_x_mode)))
5023 {
5024 return get_normal_compl_info(line, startcol, curs_col);
5025 }
5026 else if (ctrl_x_mode_line_or_eval())
5027 {
5028 return get_wholeline_compl_info(line, curs_col);
5029 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005030 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005031 {
5032 return get_filename_compl_info(line, startcol, curs_col);
5033 }
5034 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5035 {
5036 return get_cmdline_compl_info(line, curs_col);
5037 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005038 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005039 || thesaurus_func_complete(ctrl_x_mode))
5040 {
5041 if (get_userdefined_compl_info(curs_col) == FAIL)
5042 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005043 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005044 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005045 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005046 {
5047 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5048 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005049 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005050 }
5051 else
5052 {
5053 internal_error("ins_complete()");
5054 return FAIL;
5055 }
5056
5057 return OK;
5058}
5059
5060/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005061 * Continue an interrupted completion mode search in "line".
5062 *
5063 * If this same ctrl_x_mode has been interrupted use the text from
5064 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5065 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5066 * the same line as the cursor then fix it (the line has been split because it
5067 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5068 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005069 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005070 static void
5071ins_compl_continue_search(char_u *line)
5072{
5073 // it is a continued search
5074 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005075 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5076 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005077 {
5078 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5079 {
5080 // line (probably) wrapped, set compl_startpos to the
5081 // first non_blank in the line, if it is not a wordchar
5082 // include it to get a better pattern, but then we don't
5083 // want the "\\<" prefix, check it below
5084 compl_col = (colnr_T)getwhitecols(line);
5085 compl_startpos.col = compl_col;
5086 compl_startpos.lnum = curwin->w_cursor.lnum;
5087 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5088 }
5089 else
5090 {
5091 // S_IPOS was set when we inserted a word that was at the
5092 // beginning of the line, which means that we'll go to SOL
5093 // mode but first we need to redefine compl_startpos
5094 if (compl_cont_status & CONT_S_IPOS)
5095 {
5096 compl_cont_status |= CONT_SOL;
5097 compl_startpos.col = (colnr_T)(skipwhite(
5098 line + compl_length
5099 + compl_startpos.col) - line);
5100 }
5101 compl_col = compl_startpos.col;
5102 }
5103 compl_length = curwin->w_cursor.col - (int)compl_col;
5104 // IObuff is used to add a "word from the next line" would we
5105 // have enough space? just being paranoid
5106#define MIN_SPACE 75
5107 if (compl_length > (IOSIZE - MIN_SPACE))
5108 {
5109 compl_cont_status &= ~CONT_SOL;
5110 compl_length = (IOSIZE - MIN_SPACE);
5111 compl_col = curwin->w_cursor.col - compl_length;
5112 }
5113 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5114 if (compl_length < 1)
5115 compl_cont_status &= CONT_LOCAL;
5116 }
5117 else if (ctrl_x_mode_line_or_eval())
5118 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5119 else
5120 compl_cont_status = 0;
5121}
5122
5123/*
5124 * start insert mode completion
5125 */
5126 static int
5127ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005128{
5129 char_u *line;
5130 int startcol = 0; // column where searched text starts
5131 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005132 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005133 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005134 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005135
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005136 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005137
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005138 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005139 did_si = FALSE;
5140 can_si = FALSE;
5141 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005142 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005143 return FAIL;
5144
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005145 line = ml_get(curwin->w_cursor.lnum);
5146 curs_col = curwin->w_cursor.col;
5147 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005148
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005149 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5150 && compl_cont_mode == ctrl_x_mode)
5151 // this same ctrl-x_mode was interrupted previously. Continue the
5152 // completion.
5153 ins_compl_continue_search(line);
5154 else
5155 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005156
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005157 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005158 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005159 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005160 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005161 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5162 compl_cont_status = 0;
5163 compl_cont_status |= CONT_N_ADDS;
5164 compl_startpos = curwin->w_cursor;
5165 startcol = (int)curs_col;
5166 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005167 }
5168
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005169 // Work out completion pattern and original text -- webb
5170 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5171 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005172 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5173 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005174 // restore did_ai, so that adding comment leader works
5175 did_ai = save_did_ai;
5176 return FAIL;
5177 }
5178 // If "line" was changed while getting completion info get it again.
5179 if (line_invalid)
5180 line = ml_get(curwin->w_cursor.lnum);
5181
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005182 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005183 {
5184 edit_submode_pre = (char_u *)_(" Adding");
5185 if (ctrl_x_mode_line_or_eval())
5186 {
5187 // Insert a new line, keep indentation but ignore 'comments'.
5188 char_u *old = curbuf->b_p_com;
5189
5190 curbuf->b_p_com = (char_u *)"";
5191 compl_startpos.lnum = curwin->w_cursor.lnum;
5192 compl_startpos.col = compl_col;
5193 ins_eol('\r');
5194 curbuf->b_p_com = old;
5195 compl_length = 0;
5196 compl_col = curwin->w_cursor.col;
5197 }
5198 }
5199 else
5200 {
5201 edit_submode_pre = NULL;
5202 compl_startpos.col = compl_col;
5203 }
5204
5205 if (compl_cont_status & CONT_LOCAL)
5206 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5207 else
5208 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5209
5210 // If any of the original typed text has been changed we need to fix
5211 // the redo buffer.
5212 ins_compl_fixRedoBufForLeader(NULL);
5213
5214 // Always add completion for the original text.
5215 vim_free(compl_orig_text);
5216 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5217 if (p_ic)
5218 flags |= CP_ICASE;
5219 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
glepnir508e7852024-07-25 21:39:08 +02005220 -1, NULL, NULL, NULL, 0, flags, FALSE, -1) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005221 {
5222 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005223 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005224 VIM_CLEAR(compl_orig_text);
5225 return FAIL;
5226 }
5227
5228 // showmode might reset the internal line pointers, so it must
5229 // be called before line = ml_get(), or when this address is no
5230 // longer needed. -- Acevedo.
5231 edit_submode_extra = (char_u *)_("-- Searching...");
5232 edit_submode_highl = HLF_COUNT;
5233 showmode();
5234 edit_submode_extra = NULL;
5235 out_flush();
5236
5237 return OK;
5238}
5239
5240/*
5241 * display the completion status message
5242 */
5243 static void
5244ins_compl_show_statusmsg(void)
5245{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005246 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005247 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005248 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005249 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005250 ? (char_u *)_("Hit end of paragraph")
5251 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005252 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005253 }
5254
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005255 if (edit_submode_extra == NULL)
5256 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005257 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005258 {
5259 edit_submode_extra = (char_u *)_("Back at original");
5260 edit_submode_highl = HLF_W;
5261 }
5262 else if (compl_cont_status & CONT_S_IPOS)
5263 {
5264 edit_submode_extra = (char_u *)_("Word from other line");
5265 edit_submode_highl = HLF_COUNT;
5266 }
5267 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5268 {
5269 edit_submode_extra = (char_u *)_("The only match");
5270 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005271 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005272 }
5273 else
5274 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005275#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005276 // Update completion sequence number when needed.
5277 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005278 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005279#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005280 // The match should always have a sequence number now, this is
5281 // just a safety check.
5282 if (compl_curr_match->cp_number != -1)
5283 {
5284 // Space for 10 text chars. + 2x10-digit no.s = 31.
5285 // Translations may need more than twice that.
5286 static char_u match_ref[81];
5287
5288 if (compl_matches > 0)
5289 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005290 _("match %d of %d"),
5291 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005292 else
5293 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005294 _("match %d"),
5295 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005296 edit_submode_extra = match_ref;
5297 edit_submode_highl = HLF_R;
5298 if (dollar_vcol >= 0)
5299 curs_columns(FALSE);
5300 }
5301 }
5302 }
5303
5304 // Show a message about what (completion) mode we're in.
5305 if (!compl_opt_suppress_empty)
5306 {
5307 showmode();
5308 if (!shortmess(SHM_COMPLETIONMENU))
5309 {
5310 if (edit_submode_extra != NULL)
5311 {
5312 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005313 {
5314 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005315 msg_attr((char *)edit_submode_extra,
5316 edit_submode_highl < HLF_COUNT
5317 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005318 msg_hist_off = FALSE;
5319 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005320 }
5321 else
5322 msg_clr_cmdline(); // necessary for "noshowmode"
5323 }
5324 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005325}
5326
5327/*
5328 * Do Insert mode completion.
5329 * Called when character "c" was typed, which has a meaning for completion.
5330 * Returns OK if completion was done, FAIL if something failed (out of mem).
5331 */
5332 int
5333ins_complete(int c, int enable_pum)
5334{
5335 int n;
5336 int save_w_wrow;
5337 int save_w_leftcol;
5338 int insert_match;
5339
5340 compl_direction = ins_compl_key2dir(c);
5341 insert_match = ins_compl_use_match(c);
5342
5343 if (!compl_started)
5344 {
5345 if (ins_compl_start() == FAIL)
5346 return FAIL;
5347 }
5348 else if (insert_match && stop_arrow() == FAIL)
5349 return FAIL;
5350
5351 compl_shown_match = compl_curr_match;
5352 compl_shows_dir = compl_direction;
5353
5354 // Find next match (and following matches).
5355 save_w_wrow = curwin->w_wrow;
5356 save_w_leftcol = curwin->w_leftcol;
5357 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5358
5359 // may undisplay the popup menu
5360 ins_compl_upd_pum();
5361
5362 if (n > 1) // all matches have been found
5363 compl_matches = n;
5364 compl_curr_match = compl_shown_match;
5365 compl_direction = compl_shows_dir;
5366
5367 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5368 // mode.
5369 if (got_int && !global_busy)
5370 {
5371 (void)vgetc();
5372 got_int = FALSE;
5373 }
5374
5375 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005376 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005377 {
5378 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5379 // because we couldn't expand anything at first place, but if we used
5380 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5381 // (such as M in M'exico) if not tried already. -- Acevedo
5382 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005383 || compl_status_adding()
5384 || (ctrl_x_mode_not_default()
5385 && !ctrl_x_mode_path_patterns()
5386 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005387 compl_cont_status &= ~CONT_N_ADDS;
5388 }
5389
5390 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5391 compl_cont_status |= CONT_S_IPOS;
5392 else
5393 compl_cont_status &= ~CONT_S_IPOS;
5394
5395 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005396
5397 // Show the popup menu, unless we got interrupted.
5398 if (enable_pum && !compl_interrupted)
5399 show_pum(save_w_wrow, save_w_leftcol);
5400
5401 compl_was_interrupted = compl_interrupted;
5402 compl_interrupted = FALSE;
5403
5404 return OK;
5405}
5406
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005407/*
5408 * Remove (if needed) and show the popup menu
5409 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005410 static void
5411show_pum(int prev_w_wrow, int prev_w_leftcol)
5412{
5413 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005414 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005415 RedrawingDisabled = 0;
5416
5417 // If the cursor moved or the display scrolled we need to remove the pum
5418 // first.
5419 setcursor();
5420 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5421 ins_compl_del_pum();
5422
5423 ins_compl_show_pum();
5424 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005425
5426 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005427}
5428
5429/*
5430 * Looks in the first "len" chars. of "src" for search-metachars.
5431 * If dest is not NULL the chars. are copied there quoting (with
5432 * a backslash) the metachars, and dest would be NUL terminated.
5433 * Returns the length (needed) of dest
5434 */
5435 static unsigned
5436quote_meta(char_u *dest, char_u *src, int len)
5437{
5438 unsigned m = (unsigned)len + 1; // one extra for the NUL
5439
5440 for ( ; --len >= 0; src++)
5441 {
5442 switch (*src)
5443 {
5444 case '.':
5445 case '*':
5446 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005447 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005448 break;
5449 // FALLTHROUGH
5450 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005451 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005452 break;
5453 // FALLTHROUGH
5454 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005455 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005456 break;
5457 // FALLTHROUGH
5458 case '^': // currently it's not needed.
5459 case '$':
5460 m++;
5461 if (dest != NULL)
5462 *dest++ = '\\';
5463 break;
5464 }
5465 if (dest != NULL)
5466 *dest++ = *src;
5467 // Copy remaining bytes of a multibyte character.
5468 if (has_mbyte)
5469 {
5470 int i, mb_len;
5471
5472 mb_len = (*mb_ptr2len)(src) - 1;
5473 if (mb_len > 0 && len >= mb_len)
5474 for (i = 0; i < mb_len; ++i)
5475 {
5476 --len;
5477 ++src;
5478 if (dest != NULL)
5479 *dest++ = *src;
5480 }
5481 }
5482 }
5483 if (dest != NULL)
5484 *dest = NUL;
5485
5486 return m;
5487}
5488
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005489#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005490 void
5491free_insexpand_stuff(void)
5492{
5493 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005494# ifdef FEAT_EVAL
5495 free_callback(&cfu_cb);
5496 free_callback(&ofu_cb);
5497 free_callback(&tsrfu_cb);
5498# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005499}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005500#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005501
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005502#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005503/*
5504 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5505 * spelled word, if there is one.
5506 */
5507 static void
5508spell_back_to_badword(void)
5509{
5510 pos_T tpos = curwin->w_cursor;
5511
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005512 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005513 if (curwin->w_cursor.col != tpos.col)
5514 start_arrow(&tpos);
5515}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005516#endif