blob: 6bc5075cbd84fff9db4fcf3406c9e03d59a4692b [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020061 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010062 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010091 * Structure used to store one match for insert completion.
92 */
93typedef struct compl_S compl_T;
94struct compl_S
95{
96 compl_T *cp_next;
97 compl_T *cp_prev;
John Marriott5e6ea922024-11-23 14:01:57 +010098 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +020099 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100100#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100101 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100102#endif
glepnir0fe17f82024-10-08 22:26:44 +0200103 char_u *cp_fname; // file containing the match, allocated when
104 // cp_flags has CP_FREE_FNAME
105 int cp_flags; // CP_ values
106 int cp_number; // sequence number
107 int cp_score; // fuzzy match score
glepnir7baa0142024-10-09 20:19:25 +0200108 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200109 int cp_user_kind_hlattr; // highlight attribute for kind
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100110};
111
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200112// values for cp_flags
113# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
114# define CP_FREE_FNAME 2 // cp_fname is allocated
115# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
116# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
117# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200118# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100119
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100120/*
121 * All the current matches are stored in a list.
122 * "compl_first_match" points to the start of the list.
123 * "compl_curr_match" points to the currently selected entry.
124 * "compl_shown_match" is different from compl_curr_match during
125 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000126 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100127 */
128static compl_T *compl_first_match = NULL;
129static compl_T *compl_curr_match = NULL;
130static compl_T *compl_shown_match = NULL;
131static compl_T *compl_old_match = NULL;
132
133// After using a cursor key <Enter> selects a match in the popup menu,
134// otherwise it inserts a line break.
135static int compl_enter_selects = FALSE;
136
137// When "compl_leader" is not NULL only matches that start with this string
138// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100139static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100140
141static int compl_get_longest = FALSE; // put longest common string
142 // in compl_leader
143
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100144// Selected one of the matches. When FALSE the match was edited or using the
145// longest common string.
146static int compl_used_match;
147
148// didn't finish finding completions.
149static int compl_was_interrupted = FALSE;
150
151// Set when character typed while looking for matches and it means we should
152// stop looking for matches.
153static int compl_interrupted = FALSE;
154
155static int compl_restarting = FALSE; // don't insert match
156
157// When the first completion is done "compl_started" is set. When it's
158// FALSE the word to be completed must be located.
159static int compl_started = FALSE;
160
161// Which Ctrl-X mode are we in?
162static int ctrl_x_mode = CTRL_X_NORMAL;
163
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000164static int compl_matches = 0; // number of completion matches
John Marriott5e6ea922024-11-23 14:01:57 +0100165static string_T compl_pattern = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100166static int compl_direction = FORWARD;
167static int compl_shows_dir = FORWARD;
168static int compl_pending = 0; // > 1 for postponed CTRL-N
169static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000170// Length in bytes of the text being completed (this is deleted to be replaced
171// by the match.)
172static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100173static colnr_T compl_col = 0; // column where the text starts
174 // that is being completed
John Marriott5e6ea922024-11-23 14:01:57 +0100175static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100176 // completion started
177static int compl_cont_mode = 0;
178static expand_T compl_xp;
179
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000180// List of flags for method of completion.
181static int compl_cont_status = 0;
182# define CONT_ADDING 1 // "normal" or "adding" expansion
183# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
184 // it's set only iff N_ADDS is set
185# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
186# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
187 // if so, word-wise-expansion will set SOL
188# define CONT_SOL 16 // pattern includes start of line, just for
189 // word-wise expansion, not set for ^X^L
190# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
191 // expansion, (eg use complete=.)
192
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100193static int compl_opt_refresh_always = FALSE;
194static int compl_opt_suppress_empty = FALSE;
195
glepnira218cc62024-06-03 19:32:39 +0200196static int compl_selected_item = -1;
197
glepnir8159fb12024-07-17 20:32:54 +0200198static int *compl_fuzzy_scores;
199
glepnir5c66e232024-11-15 19:58:27 +0100200static 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 *extra_hl);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100201static void ins_compl_longest_match(compl_T *match);
202static void ins_compl_del_pum(void);
203static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
204static char_u *find_line_end(char_u *ptr);
205static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100206static int ins_compl_need_restart(void);
207static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000208static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100209static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100210static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100211static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
212# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
213static void ins_compl_add_list(list_T *list);
214static void ins_compl_add_dict(dict_T *dict);
215# endif
216static int ins_compl_key2dir(int c);
217static int ins_compl_pum_key(int c);
218static int ins_compl_key2count(int c);
219static void show_pum(int prev_w_wrow, int prev_w_leftcol);
220static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100221
222#ifdef FEAT_SPELL
223static void spell_back_to_badword(void);
224static int spell_bad_len = 0; // length of located bad word
225#endif
226
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100227/*
228 * CTRL-X pressed in Insert mode.
229 */
230 void
231ins_ctrl_x(void)
232{
zeertzjqdca29d92021-08-31 19:12:51 +0200233 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100234 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000235 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100236 if (compl_cont_status & CONT_N_ADDS)
237 compl_cont_status |= CONT_INTRPT;
238 else
239 compl_cont_status = 0;
240 // We're not sure which CTRL-X mode it will be yet
241 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
242 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
243 edit_submode_pre = NULL;
244 showmode();
245 }
zeertzjqdca29d92021-08-31 19:12:51 +0200246 else
247 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
248 // CTRL-V look like CTRL-N
249 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100250
LemonBoy2bf52dd2022-04-09 18:17:34 +0100251 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100252}
253
254/*
255 * Functions to check the current CTRL-X mode.
256 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000257int ctrl_x_mode_none(void)
258 { return ctrl_x_mode == 0; }
259int ctrl_x_mode_normal(void)
260 { return ctrl_x_mode == CTRL_X_NORMAL; }
261int ctrl_x_mode_scroll(void)
262 { return ctrl_x_mode == CTRL_X_SCROLL; }
263int ctrl_x_mode_whole_line(void)
264 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
265int ctrl_x_mode_files(void)
266 { return ctrl_x_mode == CTRL_X_FILES; }
267int ctrl_x_mode_tags(void)
268 { return ctrl_x_mode == CTRL_X_TAGS; }
269int ctrl_x_mode_path_patterns(void)
270 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
271int ctrl_x_mode_path_defines(void)
272 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
273int ctrl_x_mode_dictionary(void)
274 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
275int ctrl_x_mode_thesaurus(void)
276 { return ctrl_x_mode == CTRL_X_THESAURUS; }
277int ctrl_x_mode_cmdline(void)
278 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200279 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000280int ctrl_x_mode_function(void)
281 { return ctrl_x_mode == CTRL_X_FUNCTION; }
282int ctrl_x_mode_omni(void)
283 { return ctrl_x_mode == CTRL_X_OMNI; }
284int ctrl_x_mode_spell(void)
285 { return ctrl_x_mode == CTRL_X_SPELL; }
286static int ctrl_x_mode_eval(void)
287 { return ctrl_x_mode == CTRL_X_EVAL; }
288int ctrl_x_mode_line_or_eval(void)
289 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100290
291/*
292 * Whether other than default completion has been selected.
293 */
294 int
295ctrl_x_mode_not_default(void)
296{
297 return ctrl_x_mode != CTRL_X_NORMAL;
298}
299
300/*
zeertzjqdca29d92021-08-31 19:12:51 +0200301 * Whether CTRL-X was typed without a following character,
302 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100303 */
304 int
305ctrl_x_mode_not_defined_yet(void)
306{
307 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
308}
309
310/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000311 * Return TRUE if currently in "normal" or "adding" insert completion matches
312 * state
313 */
314 int
315compl_status_adding(void)
316{
317 return compl_cont_status & CONT_ADDING;
318}
319
320/*
321 * Return TRUE if the completion pattern includes start of line, just for
322 * word-wise expansion.
323 */
324 int
325compl_status_sol(void)
326{
327 return compl_cont_status & CONT_SOL;
328}
329
330/*
331 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
332 */
333 int
334compl_status_local(void)
335{
336 return compl_cont_status & CONT_LOCAL;
337}
338
339/*
340 * Clear the completion status flags
341 */
342 void
343compl_status_clear(void)
344{
345 compl_cont_status = 0;
346}
347
348/*
349 * Return TRUE if completion is using the forward direction matches
350 */
351 static int
352compl_dir_forward(void)
353{
354 return compl_direction == FORWARD;
355}
356
357/*
358 * Return TRUE if currently showing forward completion matches
359 */
360 static int
361compl_shows_dir_forward(void)
362{
363 return compl_shows_dir == FORWARD;
364}
365
366/*
367 * Return TRUE if currently showing backward completion matches
368 */
369 static int
370compl_shows_dir_backward(void)
371{
372 return compl_shows_dir == BACKWARD;
373}
374
375/*
376 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100377 */
378 int
379has_compl_option(int dict_opt)
380{
381 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200382#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100383 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200384#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100385 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100386 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
387#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100388 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100389#endif
390 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100391 {
392 ctrl_x_mode = CTRL_X_NORMAL;
393 edit_submode = NULL;
394 msg_attr(dict_opt ? _("'dictionary' option is empty")
395 : _("'thesaurus' option is empty"),
396 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100397 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100398 {
399 vim_beep(BO_COMPL);
400 setcursor();
401 out_flush();
402#ifdef FEAT_EVAL
403 if (!get_vim_var_nr(VV_TESTING))
404#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100405 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100406 }
407 return FALSE;
408 }
409 return TRUE;
410}
411
412/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000413 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100414 * This depends on the current mode.
415 */
416 int
417vim_is_ctrl_x_key(int c)
418{
419 // Always allow ^R - let its results then be checked
420 if (c == Ctrl_R)
421 return TRUE;
422
423 // Accept <PageUp> and <PageDown> if the popup menu is visible.
424 if (ins_compl_pum_key(c))
425 return TRUE;
426
427 switch (ctrl_x_mode)
428 {
429 case 0: // Not in any CTRL-X mode
430 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
431 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200432 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100433 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
434 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
435 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
436 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
437 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200438 || c == Ctrl_S || c == Ctrl_K || c == 's'
439 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100440 case CTRL_X_SCROLL:
441 return (c == Ctrl_Y || c == Ctrl_E);
442 case CTRL_X_WHOLE_LINE:
443 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
444 case CTRL_X_FILES:
445 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
446 case CTRL_X_DICTIONARY:
447 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
448 case CTRL_X_THESAURUS:
449 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
450 case CTRL_X_TAGS:
451 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
452#ifdef FEAT_FIND_ID
453 case CTRL_X_PATH_PATTERNS:
454 return (c == Ctrl_P || c == Ctrl_N);
455 case CTRL_X_PATH_DEFINES:
456 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
457#endif
458 case CTRL_X_CMDLINE:
459 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
460 || c == Ctrl_X);
461#ifdef FEAT_COMPL_FUNC
462 case CTRL_X_FUNCTION:
463 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
464 case CTRL_X_OMNI:
465 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
466#endif
467 case CTRL_X_SPELL:
468 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
469 case CTRL_X_EVAL:
470 return (c == Ctrl_P || c == Ctrl_N);
471 }
472 internal_error("vim_is_ctrl_x_key()");
473 return FALSE;
474}
475
476/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000477 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000478 */
479 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000480match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000481{
482 return match->cp_flags & CP_ORIGINAL_TEXT;
483}
484
485/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000486 * Returns TRUE if "match" is the first match in the completion list.
487 */
488 static int
489is_first_match(compl_T *match)
490{
491 return match == compl_first_match;
492}
493
494/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100495 * Return TRUE when character "c" is part of the item currently being
496 * completed. Used to decide whether to abandon complete mode when the menu
497 * is visible.
498 */
499 int
500ins_compl_accept_char(int c)
501{
502 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
503 // When expanding an identifier only accept identifier chars.
504 return vim_isIDc(c);
505
506 switch (ctrl_x_mode)
507 {
508 case CTRL_X_FILES:
509 // When expanding file name only accept file name chars. But not
510 // path separators, so that "proto/<Tab>" expands files in
511 // "proto", not "proto/" as a whole
512 return vim_isfilec(c) && !vim_ispathsep(c);
513
514 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200515 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100516 case CTRL_X_OMNI:
517 // Command line and Omni completion can work with just about any
518 // printable character, but do stop at white space.
519 return vim_isprintc(c) && !VIM_ISWHITE(c);
520
521 case CTRL_X_WHOLE_LINE:
522 // For while line completion a space can be part of the line.
523 return vim_isprintc(c);
524 }
525 return vim_iswordc(c);
526}
527
528/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000529 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100530 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000531 */
532 static char_u *
533ins_compl_infercase_gettext(
534 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100535 int char_len,
536 int compl_char_len,
537 int min_len,
538 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000539{
540 int *wca; // Wide character array.
541 char_u *p;
542 int i, c;
543 int has_lower = FALSE;
544 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100545 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000546
547 IObuff[0] = NUL;
548
549 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100550 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000551 if (wca == NULL)
552 return IObuff;
553
554 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100555 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000556 if (has_mbyte)
557 wca[i] = mb_ptr2char_adv(&p);
558 else
559 wca[i] = *(p++);
560
561 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100562 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000563 for (i = 0; i < min_len; ++i)
564 {
565 if (has_mbyte)
566 c = mb_ptr2char_adv(&p);
567 else
568 c = *(p++);
569 if (MB_ISLOWER(c))
570 {
571 has_lower = TRUE;
572 if (MB_ISUPPER(wca[i]))
573 {
574 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100575 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000576 wca[i] = MB_TOLOWER(wca[i]);
577 break;
578 }
579 }
580 }
581
582 // Rule 2: No lower case, 2nd consecutive letter converted to
583 // upper case.
584 if (!has_lower)
585 {
John Marriott5e6ea922024-11-23 14:01:57 +0100586 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000587 for (i = 0; i < min_len; ++i)
588 {
589 if (has_mbyte)
590 c = mb_ptr2char_adv(&p);
591 else
592 c = *(p++);
593 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
594 {
595 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100596 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000597 wca[i] = MB_TOUPPER(wca[i]);
598 break;
599 }
600 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
601 }
602 }
603
604 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100605 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000606 for (i = 0; i < min_len; ++i)
607 {
608 if (has_mbyte)
609 c = mb_ptr2char_adv(&p);
610 else
611 c = *(p++);
612 if (MB_ISLOWER(c))
613 wca[i] = MB_TOLOWER(wca[i]);
614 else if (MB_ISUPPER(c))
615 wca[i] = MB_TOUPPER(wca[i]);
616 }
617
618 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000619 p = IObuff;
620 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100621 ga_init2(&gap, 1, 500);
622 while (i < char_len)
623 {
624 if (gap.ga_data != NULL)
625 {
626 if (ga_grow(&gap, 10) == FAIL)
627 {
628 ga_clear(&gap);
629 return (char_u *)"[failed]";
630 }
631 p = (char_u *)gap.ga_data + gap.ga_len;
632 if (has_mbyte)
633 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
634 else
635 {
636 *p = wca[i++];
637 ++gap.ga_len;
638 }
639 }
640 else if ((p - IObuff) + 6 >= IOSIZE)
641 {
642 // Multi-byte characters can occupy up to five bytes more than
643 // ASCII characters, and we also need one byte for NUL, so when
644 // getting to six bytes from the edge of IObuff switch to using a
645 // growarray. Add the character in the next round.
646 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100647 {
648 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100649 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100650 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100651 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100652 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100653 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100654 }
655 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000656 p += (*mb_char2bytes)(wca[i++], p);
657 else
658 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100659 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000660 vim_free(wca);
661
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100662 if (gap.ga_data != NULL)
663 {
664 *tofree = gap.ga_data;
665 return gap.ga_data;
666 }
667
668 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000669 return IObuff;
670}
671
672/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100673 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
674 * case of the originally typed text is used, and the case of the completed
675 * text is inferred, ie this tries to work out what case you probably wanted
676 * the rest of the word to be in -- webb
677 */
678 int
679ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200680 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100681 int len,
682 int icase,
683 char_u *fname,
684 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200685 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100686{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200687 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100688 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100689 int char_len; // count multi-byte characters
690 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100691 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200692 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100693 int res;
694 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100695
696 if (p_ic && curbuf->b_p_inf && len > 0)
697 {
698 // Infer case of completed part.
699
700 // Find actual length of completion.
701 if (has_mbyte)
702 {
703 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100704 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100705 while (*p != NUL)
706 {
707 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100708 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100709 }
710 }
711 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100712 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100713
714 // Find actual length of original text.
715 if (has_mbyte)
716 {
John Marriott5e6ea922024-11-23 14:01:57 +0100717 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100718 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719 while (*p != NUL)
720 {
721 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100722 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100723 }
724 }
725 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100726 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100727
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100728 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100729 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100730 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100731
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100732 str = ins_compl_infercase_gettext(str, char_len,
733 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100734 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200735 if (cont_s_ipos)
736 flags |= CP_CONT_S_IPOS;
737 if (icase)
738 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200739
glepnir5c66e232024-11-15 19:58:27 +0100740 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100741 vim_free(tofree);
742 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100743}
744
745/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000746 * Add a match to the list of matches. The arguments are:
747 * str - text of the match to add
748 * len - length of "str". If -1, then the length of "str" is
749 * computed.
750 * fname - file name to associate with this match.
751 * cptext - list of strings to use with this match (for abbr, menu, info
752 * and kind)
753 * user_data - user supplied data (any vim type) for this match
754 * cdir - match direction. If 0, use "compl_direction".
755 * flags_arg - match flags (cp_flags)
756 * adup - accept this match even if it is already present.
glepnir5c66e232024-11-15 19:58:27 +0100757 * *extra_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000758 * If "cdir" is FORWARD, then the match is added after the current match.
759 * Otherwise, it is added before the current match.
760 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100761 * If the given string is already in the list of completions, then return
762 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
763 * maybe because alloc() returns NULL, then FAIL is returned.
764 */
765 static int
766ins_compl_add(
767 char_u *str,
768 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100769 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100770 char_u **cptext, // extra text for popup menu or NULL
771 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100772 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200773 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200774 int adup, // accept duplicate match
glepnir5c66e232024-11-15 19:58:27 +0100775 int *extra_hl) // user abbr/kind hlattr
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100776{
777 compl_T *match;
778 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200779 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780
Bram Moolenaarceb06192021-04-04 15:05:22 +0200781 if (flags & CP_FAST)
782 fast_breakcheck();
783 else
784 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100785 if (got_int)
786 return FAIL;
787 if (len < 0)
788 len = (int)STRLEN(str);
789
790 // If the same match is already present, don't add it.
791 if (compl_first_match != NULL && !adup)
792 {
793 match = compl_first_match;
794 do
795 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000796 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100797 && STRNCMP(match->cp_str.string, str, len) == 0
798 && ((int)match->cp_str.length <= len
799 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100800 return NOTDONE;
801 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000802 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100803 }
804
805 // Remove any popup menu before changing the list of matches.
806 ins_compl_del_pum();
807
808 // Allocate a new match structure.
809 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200810 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100811 if (match == NULL)
812 return FAIL;
813 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200814 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100815 match->cp_number = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100816 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100817 {
818 vim_free(match);
819 return FAIL;
820 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100821
John Marriott5e6ea922024-11-23 14:01:57 +0100822 match->cp_str.length = len;
823
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100824 // match-fname is:
825 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200826 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100827 // - NULL otherwise. --Acevedo
828 if (fname != NULL
829 && compl_curr_match != NULL
830 && compl_curr_match->cp_fname != NULL
831 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
832 match->cp_fname = compl_curr_match->cp_fname;
833 else if (fname != NULL)
834 {
835 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200836 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100837 }
838 else
839 match->cp_fname = NULL;
840 match->cp_flags = flags;
glepnir5c66e232024-11-15 19:58:27 +0100841 match->cp_user_abbr_hlattr = extra_hl ? extra_hl[0] : -1;
842 match->cp_user_kind_hlattr = extra_hl ? extra_hl[1] : -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100843
844 if (cptext != NULL)
845 {
846 int i;
847
848 for (i = 0; i < CPT_COUNT; ++i)
849 if (cptext[i] != NULL && *cptext[i] != NUL)
850 match->cp_text[i] = vim_strsave(cptext[i]);
851 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100852#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100853 if (user_data != NULL)
854 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100855#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000857 // Link the new match structure after (FORWARD) or before (BACKWARD) the
858 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859 if (compl_first_match == NULL)
860 match->cp_next = match->cp_prev = NULL;
861 else if (dir == FORWARD)
862 {
863 match->cp_next = compl_curr_match->cp_next;
864 match->cp_prev = compl_curr_match;
865 }
866 else // BACKWARD
867 {
868 match->cp_next = compl_curr_match;
869 match->cp_prev = compl_curr_match->cp_prev;
870 }
871 if (match->cp_next)
872 match->cp_next->cp_prev = match;
873 if (match->cp_prev)
874 match->cp_prev->cp_next = match;
875 else // if there's nothing before, it is the first match
876 compl_first_match = match;
877 compl_curr_match = match;
878
879 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200880 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881 ins_compl_longest_match(match);
882
883 return OK;
884}
885
886/*
887 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 */
890 static int
891ins_compl_equal(compl_T *match, char_u *str, int len)
892{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200893 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200894 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200895 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100896 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
897 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100898}
899
900/*
901 * Reduce the longest common string for match "match".
902 */
903 static void
904ins_compl_longest_match(compl_T *match)
905{
906 char_u *p, *s;
907 int c1, c2;
908 int had_match;
909
John Marriott5e6ea922024-11-23 14:01:57 +0100910 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100911 {
912 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +0100913 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
914 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000915 return;
916
John Marriott5e6ea922024-11-23 14:01:57 +0100917 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000918 had_match = (curwin->w_cursor.col > compl_col);
919 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +0100920 ins_bytes(compl_leader.string + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000921 ins_redraw(FALSE);
922
923 // When the match isn't there (to avoid matching itself) remove it
924 // again after redrawing.
925 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100927 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000928
929 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100930 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000931
932 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +0100933 p = compl_leader.string;
934 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000935 while (*p != NUL)
936 {
937 if (has_mbyte)
938 {
939 c1 = mb_ptr2char(p);
940 c2 = mb_ptr2char(s);
941 }
942 else
943 {
944 c1 = *p;
945 c2 = *s;
946 }
947 if ((match->cp_flags & CP_ICASE)
948 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
949 break;
950 if (has_mbyte)
951 {
952 MB_PTR_ADV(p);
953 MB_PTR_ADV(s);
954 }
955 else
956 {
957 ++p;
958 ++s;
959 }
960 }
961
962 if (*p != NUL)
963 {
964 // Leader was shortened, need to change the inserted text.
965 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +0100966 compl_leader.length = (size_t)(p - compl_leader.string);
967
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000968 had_match = (curwin->w_cursor.col > compl_col);
969 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +0100970 ins_bytes(compl_leader.string + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000971 ins_redraw(FALSE);
972
973 // When the match isn't there (to avoid matching itself) remove it
974 // again after redrawing.
975 if (!had_match)
976 ins_compl_delete();
977 }
978
979 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100980}
981
982/*
983 * Add an array of matches to the list of matches.
984 * Frees matches[].
985 */
986 static void
987ins_compl_add_matches(
988 int num_matches,
989 char_u **matches,
990 int icase)
991{
992 int i;
993 int add_r = OK;
994 int dir = compl_direction;
995
996 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100997 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnir5c66e232024-11-15 19:58:27 +0100998 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100999 // if dir was BACKWARD then honor it just once
1000 dir = FORWARD;
1001 FreeWild(num_matches, matches);
1002}
1003
1004/*
1005 * Make the completion list cyclic.
1006 * Return the number of matches (excluding the original).
1007 */
1008 static int
1009ins_compl_make_cyclic(void)
1010{
1011 compl_T *match;
1012 int count = 0;
1013
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001014 if (compl_first_match == NULL)
1015 return 0;
1016
1017 // Find the end of the list.
1018 match = compl_first_match;
1019 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001020 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001021 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001022 match = match->cp_next;
1023 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001024 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001025 match->cp_next = compl_first_match;
1026 compl_first_match->cp_prev = match;
1027
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001028 return count;
1029}
1030
1031/*
1032 * Return whether there currently is a shown match.
1033 */
1034 int
1035ins_compl_has_shown_match(void)
1036{
1037 return compl_shown_match == NULL
1038 || compl_shown_match != compl_shown_match->cp_next;
1039}
1040
1041/*
1042 * Return whether the shown match is long enough.
1043 */
1044 int
1045ins_compl_long_shown_match(void)
1046{
John Marriott5e6ea922024-11-23 14:01:57 +01001047 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001048 > curwin->w_cursor.col - compl_col;
1049}
1050
1051/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001052 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001053 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001054 unsigned int
1055get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001056{
zeertzjq529b9ad2024-06-05 20:27:06 +02001057 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001058}
1059
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001060
1061// "compl_match_array" points the currently displayed list of entries in the
1062// popup menu. It is NULL when there is no popup menu.
1063static pumitem_T *compl_match_array = NULL;
1064static int compl_match_arraysize;
1065
1066/*
1067 * Update the screen and when there is any scrolling remove the popup menu.
1068 */
1069 static void
1070ins_compl_upd_pum(void)
1071{
1072 int h;
1073
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001074 if (compl_match_array == NULL)
1075 return;
1076
1077 h = curwin->w_cline_height;
1078 // Update the screen later, before drawing the popup menu over it.
1079 pum_call_update_screen();
1080 if (h != curwin->w_cline_height)
1081 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001082}
1083
1084/*
1085 * Remove any popup menu.
1086 */
1087 static void
1088ins_compl_del_pum(void)
1089{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001090 if (compl_match_array == NULL)
1091 return;
1092
1093 pum_undisplay();
1094 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001095}
1096
1097/*
1098 * Return TRUE if the popup menu should be displayed.
1099 */
1100 int
1101pum_wanted(void)
1102{
1103 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001104 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001105 return FALSE;
1106
1107 // The display looks bad on a B&W display.
1108 if (t_colors < 8
1109#ifdef FEAT_GUI
1110 && !gui.in_use
1111#endif
1112 )
1113 return FALSE;
1114 return TRUE;
1115}
1116
1117/*
1118 * Return TRUE if there are two or more matches to be shown in the popup menu.
1119 * One if 'completopt' contains "menuone".
1120 */
1121 static int
1122pum_enough_matches(void)
1123{
1124 compl_T *compl;
1125 int i;
1126
1127 // Don't display the popup menu if there are no matches or there is only
1128 // one (ignoring the original text).
1129 compl = compl_first_match;
1130 i = 0;
1131 do
1132 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001133 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134 break;
1135 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001136 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001137
zeertzjq529b9ad2024-06-05 20:27:06 +02001138 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001139 return (i >= 1);
1140 return (i >= 2);
1141}
1142
Bram Moolenaar3075a452021-11-17 15:51:52 +00001143#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001144/*
1145 * Allocate Dict for the completed item.
1146 * { word, abbr, menu, kind, info }
1147 */
1148 static dict_T *
1149ins_compl_dict_alloc(compl_T *match)
1150{
1151 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1152
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001153 if (dict == NULL)
1154 return NULL;
1155
John Marriott5e6ea922024-11-23 14:01:57 +01001156 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001157 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1158 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1159 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1160 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1161 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1162 dict_add_string(dict, "user_data", (char_u *)"");
1163 else
1164 dict_add_tv(dict, "user_data", &match->cp_user_data);
1165
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001166 return dict;
1167}
1168
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001169/*
1170 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1171 * completion menu is changed.
1172 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001173 static void
1174trigger_complete_changed_event(int cur)
1175{
1176 dict_T *v_event;
1177 dict_T *item;
1178 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001179 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001180
1181 if (recursive)
1182 return;
1183
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001184 if (cur < 0)
1185 item = dict_alloc();
1186 else
1187 item = ins_compl_dict_alloc(compl_curr_match);
1188 if (item == NULL)
1189 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001190 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001191 dict_add_dict(v_event, "completed_item", item);
1192 pum_set_event_info(v_event);
1193 dict_set_items_ro(v_event);
1194
1195 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001196 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001197 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001198 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001199 recursive = FALSE;
1200
Bram Moolenaar3075a452021-11-17 15:51:52 +00001201 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001202}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001203#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001204
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001205/*
glepnira218cc62024-06-03 19:32:39 +02001206 * pumitem qsort compare func
1207 */
1208 static int
zeertzjq8e567472024-06-14 20:04:42 +02001209ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001210{
1211 const int sa = (*(pumitem_T *)a).pum_score;
1212 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001213 const int ia = (*(pumitem_T *)a).pum_idx;
1214 const int ib = (*(pumitem_T *)b).pum_idx;
1215 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001216}
1217
1218/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001219 * Build a popup menu to show the completion matches.
1220 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1221 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001222 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001223 static int
1224ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001225{
1226 compl_T *compl;
1227 compl_T *shown_compl = NULL;
1228 int did_find_shown_match = FALSE;
1229 int shown_match_ok = FALSE;
1230 int i;
1231 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001232 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001233 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001234 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1235 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001236
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001237 // Need to build the popup menu list.
1238 compl_match_arraysize = 0;
1239 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001240
1241 do
1242 {
zeertzjq551d8c32024-06-05 19:53:32 +02001243 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1244 // set the cp_score for later comparisons.
John Marriott5e6ea922024-11-23 14:01:57 +01001245 if (compl_fuzzy_match && compl_leader.string != NULL && compl_leader.length > 0)
1246 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001247
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001248 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001249 && (compl_leader.string == NULL
1250 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02001251 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001252 ++compl_match_arraysize;
1253 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001254 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001255
1256 if (compl_match_arraysize == 0)
1257 return -1;
1258
1259 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1260 if (compl_match_array == NULL)
1261 return -1;
1262
1263 // If the current match is the original text don't find the first
1264 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001265 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001266 shown_match_ok = TRUE;
1267
John Marriott5e6ea922024-11-23 14:01:57 +01001268 if (compl_leader.string != NULL
1269 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
glepnir53387c52024-05-27 15:11:01 +02001270 && shown_match_ok == FALSE)
1271 compl_shown_match = compl_no_select ? compl_first_match
1272 : compl_first_match->cp_next;
1273
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001274 i = 0;
1275 compl = compl_first_match;
1276 do
1277 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001278 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001279 && (compl_leader.string == NULL
1280 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02001281 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001282 {
glepnira218cc62024-06-03 19:32:39 +02001283 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001284 {
1285 if (compl == compl_shown_match || did_find_shown_match)
1286 {
1287 // This item is the shown match or this is the
1288 // first displayed item after the shown match.
1289 compl_shown_match = compl;
1290 did_find_shown_match = TRUE;
1291 shown_match_ok = TRUE;
1292 }
1293 else
1294 // Remember this displayed match for when the
1295 // shown match is just below it.
1296 shown_compl = compl;
1297 cur = i;
1298 }
glepnira218cc62024-06-03 19:32:39 +02001299 else if (compl_fuzzy_match)
1300 {
glepnirf94c9c42024-06-14 21:11:56 +02001301 if (i == 0)
glepnir105f7412024-06-15 15:32:22 +02001302 shown_compl = compl;
glepnirdca57fb2024-06-04 22:01:21 +02001303 // Update the maximum fuzzy score and the shown match
1304 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001305 if (compl->cp_score > max_fuzzy_score)
1306 {
1307 did_find_shown_match = TRUE;
1308 max_fuzzy_score = compl->cp_score;
glepnir753794b2024-08-20 19:58:44 +02001309 if (!compl_no_select)
1310 compl_shown_match = compl;
glepnir65407ce2024-07-06 16:09:19 +02001311 }
1312
1313 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1314 {
1315 cur = i;
glepnira218cc62024-06-03 19:32:39 +02001316 shown_match_ok = TRUE;
1317 }
1318
glepnirdca57fb2024-06-04 22:01:21 +02001319 // If there is no "no select" condition and the max fuzzy
1320 // score is positive, or there is no completion leader or the
1321 // leader length is zero, mark the shown match as valid and
1322 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001323 if (!compl_no_select
1324 && (max_fuzzy_score > 0
John Marriott5e6ea922024-11-23 14:01:57 +01001325 || (compl_leader.string == NULL || compl_leader.length == 0)))
glepnira218cc62024-06-03 19:32:39 +02001326 {
glepnirf94c9c42024-06-14 21:11:56 +02001327 if (match_at_original_text(compl_shown_match))
glepnir105f7412024-06-15 15:32:22 +02001328 compl_shown_match = shown_compl;
glepnira218cc62024-06-03 19:32:39 +02001329 }
1330 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001331
1332 if (compl->cp_text[CPT_ABBR] != NULL)
glepnir6a89c942024-10-01 20:32:12 +02001333 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR];
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001334 else
John Marriott5e6ea922024-11-23 14:01:57 +01001335 compl_match_array[i].pum_text = compl->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001336 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1337 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001338 compl_match_array[i].pum_score = compl->cp_score;
glepnir0fe17f82024-10-08 22:26:44 +02001339 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
glepnir38f99a12024-08-23 18:31:06 +02001340 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001341 if (compl->cp_text[CPT_MENU] != NULL)
1342 compl_match_array[i++].pum_extra =
1343 compl->cp_text[CPT_MENU];
1344 else
1345 compl_match_array[i++].pum_extra = compl->cp_fname;
1346 }
1347
glepnira218cc62024-06-03 19:32:39 +02001348 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001349 {
1350 did_find_shown_match = TRUE;
1351
1352 // When the original text is the shown match don't set
1353 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001354 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001355 shown_match_ok = TRUE;
1356
1357 if (!shown_match_ok && shown_compl != NULL)
1358 {
1359 // The shown match isn't displayed, set it to the
1360 // previously displayed match.
1361 compl_shown_match = shown_compl;
1362 shown_match_ok = TRUE;
1363 }
1364 }
1365 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001366 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001367
John Marriott5e6ea922024-11-23 14:01:57 +01001368 if (compl_fuzzy_match && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001369 {
1370 for (i = 0; i < compl_match_arraysize; i++)
1371 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001372 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001373 qsort(compl_match_array, (size_t)compl_match_arraysize,
1374 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001375 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001376 }
glepnira218cc62024-06-03 19:32:39 +02001377
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001378 if (!shown_match_ok) // no displayed match at all
1379 cur = -1;
1380
1381 return cur;
1382}
1383
1384/*
1385 * Show the popup menu for the list of matches.
1386 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1387 */
1388 void
1389ins_compl_show_pum(void)
1390{
1391 int i;
1392 int cur = -1;
1393 colnr_T col;
1394
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001395 if (!pum_wanted() || !pum_enough_matches())
1396 return;
1397
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001398 // Update the screen later, before drawing the popup menu over it.
1399 pum_call_update_screen();
1400
1401 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001402 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001403 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001404 else
1405 {
1406 // popup menu already exists, only need to find the current item.
1407 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001408 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001409 || compl_match_array[i].pum_text
1410 == compl_shown_match->cp_text[CPT_ABBR])
1411 {
1412 cur = i;
1413 break;
1414 }
1415 }
1416
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001417 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001418 {
1419#ifdef FEAT_EVAL
1420 if (compl_started && has_completechanged())
1421 trigger_complete_changed_event(cur);
1422#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001423 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001424 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001425
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001426 // In Replace mode when a $ is displayed at the end of the line only
1427 // part of the screen would be updated. We do need to redraw here.
1428 dollar_vcol = -1;
1429
1430 // Compute the screen column of the start of the completed text.
1431 // Use the cursor to get all wrapping and other settings right.
1432 col = curwin->w_cursor.col;
1433 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001434 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001435 pum_display(compl_match_array, compl_match_arraysize, cur);
1436 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001437
glepnircbb46b42024-02-03 18:11:13 +01001438 // After adding leader, set the current match to shown match.
1439 if (compl_started && compl_curr_match != compl_shown_match)
1440 compl_curr_match = compl_shown_match;
1441
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001442#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001443 if (has_completechanged())
1444 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001445#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001446}
1447
1448#define DICT_FIRST (1) // use just first element in "dict"
1449#define DICT_EXACT (2) // "dict" is the exact name of a file
1450
1451/*
glepnir40c1c332024-06-11 19:37:04 +02001452 * Get current completion leader
1453 */
1454 char_u *
1455ins_compl_leader(void)
1456{
John Marriott5e6ea922024-11-23 14:01:57 +01001457 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1458}
1459
1460/*
1461 * Get current completion leader length
1462 */
1463 size_t
1464ins_compl_leader_len(void)
1465{
1466 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001467}
1468
1469/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001470 * Add any identifiers that match the given pattern "pat" in the list of
1471 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001472 */
1473 static void
1474ins_compl_dictionaries(
1475 char_u *dict_start,
1476 char_u *pat,
1477 int flags, // DICT_FIRST and/or DICT_EXACT
1478 int thesaurus) // Thesaurus completion
1479{
1480 char_u *dict = dict_start;
1481 char_u *ptr;
1482 char_u *buf;
1483 regmatch_T regmatch;
1484 char_u **files;
1485 int count;
1486 int save_p_scs;
1487 int dir = compl_direction;
1488
1489 if (*dict == NUL)
1490 {
1491#ifdef FEAT_SPELL
1492 // When 'dictionary' is empty and spell checking is enabled use
1493 // "spell".
1494 if (!thesaurus && curwin->w_p_spell)
1495 dict = (char_u *)"spell";
1496 else
1497#endif
1498 return;
1499 }
1500
1501 buf = alloc(LSIZE);
1502 if (buf == NULL)
1503 return;
1504 regmatch.regprog = NULL; // so that we can goto theend
1505
1506 // If 'infercase' is set, don't use 'smartcase' here
1507 save_p_scs = p_scs;
1508 if (curbuf->b_p_inf)
1509 p_scs = FALSE;
1510
1511 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1512 // to only match at the start of a line. Otherwise just match the
1513 // pattern. Also need to double backslashes.
1514 if (ctrl_x_mode_line_or_eval())
1515 {
1516 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1517 size_t len;
1518
1519 if (pat_esc == NULL)
1520 goto theend;
1521 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001522 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001523 if (ptr == NULL)
1524 {
1525 vim_free(pat_esc);
1526 goto theend;
1527 }
1528 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1529 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1530 vim_free(pat_esc);
1531 vim_free(ptr);
1532 }
1533 else
1534 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001535 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001536 if (regmatch.regprog == NULL)
1537 goto theend;
1538 }
1539
1540 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1541 regmatch.rm_ic = ignorecase(pat);
1542 while (*dict != NUL && !got_int && !compl_interrupted)
1543 {
1544 // copy one dictionary file name into buf
1545 if (flags == DICT_EXACT)
1546 {
1547 count = 1;
1548 files = &dict;
1549 }
1550 else
1551 {
1552 // Expand wildcards in the dictionary name, but do not allow
1553 // backticks (for security, the 'dict' option may have been set in
1554 // a modeline).
1555 copy_option_part(&dict, buf, LSIZE, ",");
1556# ifdef FEAT_SPELL
1557 if (!thesaurus && STRCMP(buf, "spell") == 0)
1558 count = -1;
1559 else
1560# endif
1561 if (vim_strchr(buf, '`') != NULL
1562 || expand_wildcards(1, &buf, &count, &files,
1563 EW_FILE|EW_SILENT) != OK)
1564 count = 0;
1565 }
1566
1567# ifdef FEAT_SPELL
1568 if (count == -1)
1569 {
1570 // Complete from active spelling. Skip "\<" in the pattern, we
1571 // don't use it as a RE.
1572 if (pat[0] == '\\' && pat[1] == '<')
1573 ptr = pat + 2;
1574 else
1575 ptr = pat;
1576 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1577 }
1578 else
1579# endif
1580 if (count > 0) // avoid warning for using "files" uninit
1581 {
1582 ins_compl_files(count, files, thesaurus, flags,
1583 &regmatch, buf, &dir);
1584 if (flags != DICT_EXACT)
1585 FreeWild(count, files);
1586 }
1587 if (flags != 0)
1588 break;
1589 }
1590
1591theend:
1592 p_scs = save_p_scs;
1593 vim_regfree(regmatch.regprog);
1594 vim_free(buf);
1595}
1596
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001597/*
1598 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1599 * skipping the word at 'skip_word'. Returns OK on success.
1600 */
1601 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001602thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001603 char_u *fname,
1604 char_u **buf_arg,
1605 int dir,
1606 char_u *skip_word)
1607{
1608 int status = OK;
1609 char_u *ptr;
1610 char_u *wstart;
1611
1612 // Add the other matches on the line
1613 ptr = *buf_arg;
1614 while (!got_int)
1615 {
1616 // Find start of the next word. Skip white
1617 // space and punctuation.
1618 ptr = find_word_start(ptr);
1619 if (*ptr == NUL || *ptr == NL)
1620 break;
1621 wstart = ptr;
1622
1623 // Find end of the word.
1624 if (has_mbyte)
1625 // Japanese words may have characters in
1626 // different classes, only separate words
1627 // with single-byte non-word characters.
1628 while (*ptr != NUL)
1629 {
1630 int l = (*mb_ptr2len)(ptr);
1631
1632 if (l < 2 && !vim_iswordc(*ptr))
1633 break;
1634 ptr += l;
1635 }
1636 else
1637 ptr = find_word_end(ptr);
1638
1639 // Add the word. Skip the regexp match.
1640 if (wstart != skip_word)
1641 {
1642 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1643 fname, dir, FALSE);
1644 if (status == FAIL)
1645 break;
1646 }
1647 }
1648
1649 *buf_arg = ptr;
1650 return status;
1651}
1652
1653/*
1654 * Process "count" dictionary/thesaurus "files" and add the text matching
1655 * "regmatch".
1656 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001657 static void
1658ins_compl_files(
1659 int count,
1660 char_u **files,
1661 int thesaurus,
1662 int flags,
1663 regmatch_T *regmatch,
1664 char_u *buf,
1665 int *dir)
1666{
1667 char_u *ptr;
1668 int i;
1669 FILE *fp;
1670 int add_r;
1671
1672 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1673 {
1674 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001675 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001676 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001677 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001678 vim_snprintf((char *)IObuff, IOSIZE,
1679 _("Scanning dictionary: %s"), (char *)files[i]);
1680 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1681 }
1682
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001683 if (fp == NULL)
1684 continue;
1685
1686 // Read dictionary file line by line.
1687 // Check each line for a match.
1688 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001689 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001690 ptr = buf;
1691 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001692 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001693 ptr = regmatch->startp[0];
1694 if (ctrl_x_mode_line_or_eval())
1695 ptr = find_line_end(ptr);
1696 else
1697 ptr = find_word_end(ptr);
1698 add_r = ins_compl_add_infercase(regmatch->startp[0],
1699 (int)(ptr - regmatch->startp[0]),
1700 p_ic, files[i], *dir, FALSE);
1701 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001702 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001703 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001704 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001705 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001706 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001707 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001708 if (add_r == OK)
1709 // if dir was BACKWARD then honor it just once
1710 *dir = FORWARD;
1711 else if (add_r == FAIL)
1712 break;
1713 // avoid expensive call to vim_regexec() when at end
1714 // of line
1715 if (*ptr == '\n' || got_int)
1716 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001717 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001718 line_breakcheck();
1719 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001720 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001721 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001722 }
1723}
1724
1725/*
1726 * Find the start of the next word.
1727 * Returns a pointer to the first char of the word. Also stops at a NUL.
1728 */
1729 char_u *
1730find_word_start(char_u *ptr)
1731{
1732 if (has_mbyte)
1733 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1734 ptr += (*mb_ptr2len)(ptr);
1735 else
1736 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1737 ++ptr;
1738 return ptr;
1739}
1740
1741/*
1742 * Find the end of the word. Assumes it starts inside a word.
1743 * Returns a pointer to just after the word.
1744 */
1745 char_u *
1746find_word_end(char_u *ptr)
1747{
1748 int start_class;
1749
1750 if (has_mbyte)
1751 {
1752 start_class = mb_get_class(ptr);
1753 if (start_class > 1)
1754 while (*ptr != NUL)
1755 {
1756 ptr += (*mb_ptr2len)(ptr);
1757 if (mb_get_class(ptr) != start_class)
1758 break;
1759 }
1760 }
1761 else
1762 while (vim_iswordc(*ptr))
1763 ++ptr;
1764 return ptr;
1765}
1766
1767/*
1768 * Find the end of the line, omitting CR and NL at the end.
1769 * Returns a pointer to just after the line.
1770 */
1771 static char_u *
1772find_line_end(char_u *ptr)
1773{
1774 char_u *s;
1775
1776 s = ptr + STRLEN(ptr);
1777 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1778 --s;
1779 return s;
1780}
1781
1782/*
1783 * Free the list of completions
1784 */
1785 static void
1786ins_compl_free(void)
1787{
1788 compl_T *match;
1789 int i;
1790
John Marriott5e6ea922024-11-23 14:01:57 +01001791 VIM_CLEAR_STRING(compl_pattern);
1792 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001793
1794 if (compl_first_match == NULL)
1795 return;
1796
1797 ins_compl_del_pum();
1798 pum_clear();
1799
1800 compl_curr_match = compl_first_match;
1801 do
1802 {
1803 match = compl_curr_match;
1804 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001805 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001806 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001807 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001808 vim_free(match->cp_fname);
1809 for (i = 0; i < CPT_COUNT; ++i)
1810 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001811#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001812 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001813#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001814 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001815 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001816 compl_first_match = compl_curr_match = NULL;
1817 compl_shown_match = NULL;
1818 compl_old_match = NULL;
1819}
1820
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001821/*
1822 * Reset/clear the completion state.
1823 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001824 void
1825ins_compl_clear(void)
1826{
1827 compl_cont_status = 0;
1828 compl_started = FALSE;
1829 compl_matches = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001830 VIM_CLEAR_STRING(compl_pattern);
1831 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001832 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001833 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001834 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001835#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001836 // clear v:completed_item
1837 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001838#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001839}
1840
1841/*
1842 * Return TRUE when Insert completion is active.
1843 */
1844 int
1845ins_compl_active(void)
1846{
1847 return compl_started;
1848}
1849
1850/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001851 * Selected one of the matches. When FALSE the match was edited or using the
1852 * longest common string.
1853 */
1854 int
1855ins_compl_used_match(void)
1856{
1857 return compl_used_match;
1858}
1859
1860/*
1861 * Initialize get longest common string.
1862 */
1863 void
1864ins_compl_init_get_longest(void)
1865{
1866 compl_get_longest = FALSE;
1867}
1868
1869/*
1870 * Returns TRUE when insert completion is interrupted.
1871 */
1872 int
1873ins_compl_interrupted(void)
1874{
1875 return compl_interrupted;
1876}
1877
1878/*
1879 * Returns TRUE if the <Enter> key selects a match in the completion popup
1880 * menu.
1881 */
1882 int
1883ins_compl_enter_selects(void)
1884{
1885 return compl_enter_selects;
1886}
1887
1888/*
1889 * Return the column where the text starts that is being completed
1890 */
1891 colnr_T
1892ins_compl_col(void)
1893{
1894 return compl_col;
1895}
1896
1897/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001898 * Return the length in bytes of the text being completed
1899 */
1900 int
1901ins_compl_len(void)
1902{
1903 return compl_length;
1904}
1905
1906/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001907 * Delete one character before the cursor and show the subset of the matches
1908 * that match the word that is now before the cursor.
1909 * Returns the character to be used, NUL if the work is done and another char
1910 * to be got from the user.
1911 */
1912 int
1913ins_compl_bs(void)
1914{
1915 char_u *line;
1916 char_u *p;
1917
1918 line = ml_get_curline();
1919 p = line + curwin->w_cursor.col;
1920 MB_PTR_BACK(line, p);
1921
1922 // Stop completion when the whole word was deleted. For Omni completion
1923 // allow the word to be deleted, we won't match everything.
1924 // Respect the 'backspace' option.
1925 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001926 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1927 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001928 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1929 - compl_length < 0))
1930 return K_BS;
1931
1932 // Deleted more than what was used to find matches or didn't finish
1933 // finding all matches: need to look for matches all over again.
1934 if (curwin->w_cursor.col <= compl_col + compl_length
1935 || ins_compl_need_restart())
1936 ins_compl_restart();
1937
John Marriott5e6ea922024-11-23 14:01:57 +01001938 VIM_CLEAR_STRING(compl_leader);
1939 compl_leader.length = (size_t)((p - line) - compl_col);
1940 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
1941 if (compl_leader.string == NULL)
1942 {
1943 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001944 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01001945 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001946
1947 ins_compl_new_leader();
1948 if (compl_shown_match != NULL)
1949 // Make sure current match is not a hidden item.
1950 compl_curr_match = compl_shown_match;
1951 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001952}
1953
1954/*
1955 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1956 * be called.
1957 */
1958 static int
1959ins_compl_need_restart(void)
1960{
1961 // Return TRUE if we didn't complete finding matches or when the
1962 // 'completefunc' returned "always" in the "refresh" dictionary item.
1963 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001964 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001965 && compl_opt_refresh_always);
1966}
1967
1968/*
1969 * Called after changing "compl_leader".
1970 * Show the popup menu with a different set of matches.
1971 * May also search for matches again if the previous search was interrupted.
1972 */
1973 static void
1974ins_compl_new_leader(void)
1975{
1976 ins_compl_del_pum();
1977 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01001978 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001979 compl_used_match = FALSE;
1980
1981 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01001982 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001983 else
1984 {
1985#ifdef FEAT_SPELL
1986 spell_bad_len = 0; // need to redetect bad word
1987#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001988 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001989 // the popup menu display the changed text before the cursor. Set
1990 // "compl_restarting" to avoid that the first match is inserted.
1991 pum_call_update_screen();
1992#ifdef FEAT_GUI
1993 if (gui.in_use)
1994 {
1995 // Show the cursor after the match, not after the redrawn text.
1996 setcursor();
1997 out_flush_cursor(FALSE, FALSE);
1998 }
1999#endif
2000 compl_restarting = TRUE;
2001 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2002 compl_cont_status = 0;
2003 compl_restarting = FALSE;
2004 }
2005
2006 compl_enter_selects = !compl_used_match;
2007
2008 // Show the popup menu with a different set of matches.
2009 ins_compl_show_pum();
2010
2011 // Don't let Enter select the original text when there is no popup menu.
2012 if (compl_match_array == NULL)
2013 compl_enter_selects = FALSE;
2014}
2015
2016/*
2017 * Return the length of the completion, from the completion start column to
2018 * the cursor column. Making sure it never goes below zero.
2019 */
2020 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002021get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002022{
2023 int off = (int)curwin->w_cursor.col - (int)compl_col;
2024
2025 if (off < 0)
2026 return 0;
2027 return off;
2028}
2029
2030/*
2031 * Append one character to the match leader. May reduce the number of
2032 * matches.
2033 */
2034 void
2035ins_compl_addleader(int c)
2036{
2037 int cc;
2038
2039 if (stop_arrow() == FAIL)
2040 return;
2041 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2042 {
2043 char_u buf[MB_MAXBYTES + 1];
2044
2045 (*mb_char2bytes)(c, buf);
2046 buf[cc] = NUL;
2047 ins_char_bytes(buf, cc);
2048 if (compl_opt_refresh_always)
2049 AppendToRedobuff(buf);
2050 }
2051 else
2052 {
2053 ins_char(c);
2054 if (compl_opt_refresh_always)
2055 AppendCharToRedobuff(c);
2056 }
2057
2058 // If we didn't complete finding matches we must search again.
2059 if (ins_compl_need_restart())
2060 ins_compl_restart();
2061
2062 // When 'always' is set, don't reset compl_leader. While completing,
2063 // cursor doesn't point original position, changing compl_leader would
2064 // break redo.
2065 if (!compl_opt_refresh_always)
2066 {
John Marriott5e6ea922024-11-23 14:01:57 +01002067 VIM_CLEAR_STRING(compl_leader);
2068 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2069 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2070 compl_leader.length);
2071 if (compl_leader.string == NULL)
2072 {
2073 compl_leader.length = 0;
2074 return;
2075 }
2076
2077 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002078 }
2079}
2080
2081/*
2082 * Setup for finding completions again without leaving CTRL-X mode. Used when
2083 * BS or a key was typed while still searching for matches.
2084 */
2085 static void
2086ins_compl_restart(void)
2087{
2088 ins_compl_free();
2089 compl_started = FALSE;
2090 compl_matches = 0;
2091 compl_cont_status = 0;
2092 compl_cont_mode = 0;
2093}
2094
2095/*
2096 * Set the first match, the original text.
2097 */
2098 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002099ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002100{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002101 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002102 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2103 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002104 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002105 {
John Marriott5e6ea922024-11-23 14:01:57 +01002106 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002107 if (p != NULL)
2108 {
John Marriott5e6ea922024-11-23 14:01:57 +01002109 VIM_CLEAR_STRING(compl_first_match->cp_str);
2110 compl_first_match->cp_str.string = p;
2111 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002112 }
2113 }
2114 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002115 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002116 {
John Marriott5e6ea922024-11-23 14:01:57 +01002117 char_u *p = vim_strnsave(str, len);
2118 if (p != NULL)
2119 {
2120 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2121 compl_first_match->cp_prev->cp_str.string = p;
2122 compl_first_match->cp_prev->cp_str.length = len;
2123 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002124 }
2125}
2126
2127/*
2128 * Append one character to the match leader. May reduce the number of
2129 * matches.
2130 */
2131 void
2132ins_compl_addfrommatch(void)
2133{
2134 char_u *p;
2135 int len = (int)curwin->w_cursor.col - (int)compl_col;
2136 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002137
John Marriott5e6ea922024-11-23 14:01:57 +01002138 p = compl_shown_match->cp_str.string;
2139 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002140 {
John Marriott5e6ea922024-11-23 14:01:57 +01002141 size_t plen;
2142 compl_T *cp;
2143
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002144 // When still at the original match use the first entry that matches
2145 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002146 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002147 return;
2148
2149 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002150 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002151 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002152 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002153 {
John Marriott5e6ea922024-11-23 14:01:57 +01002154 if (compl_leader.string == NULL
2155 || ins_compl_equal(cp, compl_leader.string,
2156 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002157 {
John Marriott5e6ea922024-11-23 14:01:57 +01002158 p = cp->cp_str.string;
2159 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002160 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002161 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002162 }
John Marriott5e6ea922024-11-23 14:01:57 +01002163 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002164 return;
2165 }
2166 p += len;
2167 c = PTR2CHAR(p);
2168 ins_compl_addleader(c);
2169}
2170
2171/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002172 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002173 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2174 * compl_cont_mode and compl_cont_status.
2175 * Returns TRUE when the character is not to be inserted.
2176 */
2177 static int
2178set_ctrl_x_mode(int c)
2179{
2180 int retval = FALSE;
2181
2182 switch (c)
2183 {
2184 case Ctrl_E:
2185 case Ctrl_Y:
2186 // scroll the window one line up or down
2187 ctrl_x_mode = CTRL_X_SCROLL;
2188 if (!(State & REPLACE_FLAG))
2189 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2190 else
2191 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2192 edit_submode_pre = NULL;
2193 showmode();
2194 break;
2195 case Ctrl_L:
2196 // complete whole line
2197 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2198 break;
2199 case Ctrl_F:
2200 // complete filenames
2201 ctrl_x_mode = CTRL_X_FILES;
2202 break;
2203 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002204 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002205 ctrl_x_mode = CTRL_X_DICTIONARY;
2206 break;
2207 case Ctrl_R:
2208 // Register insertion without exiting CTRL-X mode
2209 // Simply allow ^R to happen without affecting ^X mode
2210 break;
2211 case Ctrl_T:
2212 // complete words from a thesaurus
2213 ctrl_x_mode = CTRL_X_THESAURUS;
2214 break;
2215#ifdef FEAT_COMPL_FUNC
2216 case Ctrl_U:
2217 // user defined completion
2218 ctrl_x_mode = CTRL_X_FUNCTION;
2219 break;
2220 case Ctrl_O:
2221 // omni completion
2222 ctrl_x_mode = CTRL_X_OMNI;
2223 break;
2224#endif
2225 case 's':
2226 case Ctrl_S:
2227 // complete spelling suggestions
2228 ctrl_x_mode = CTRL_X_SPELL;
2229#ifdef FEAT_SPELL
2230 ++emsg_off; // Avoid getting the E756 error twice.
2231 spell_back_to_badword();
2232 --emsg_off;
2233#endif
2234 break;
2235 case Ctrl_RSB:
2236 // complete tag names
2237 ctrl_x_mode = CTRL_X_TAGS;
2238 break;
2239#ifdef FEAT_FIND_ID
2240 case Ctrl_I:
2241 case K_S_TAB:
2242 // complete keywords from included files
2243 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2244 break;
2245 case Ctrl_D:
2246 // complete definitions from included files
2247 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2248 break;
2249#endif
2250 case Ctrl_V:
2251 case Ctrl_Q:
2252 // complete vim commands
2253 ctrl_x_mode = CTRL_X_CMDLINE;
2254 break;
2255 case Ctrl_Z:
2256 // stop completion
2257 ctrl_x_mode = CTRL_X_NORMAL;
2258 edit_submode = NULL;
2259 showmode();
2260 retval = TRUE;
2261 break;
2262 case Ctrl_P:
2263 case Ctrl_N:
2264 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2265 // just started ^X mode, or there were enough ^X's to cancel
2266 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2267 // do normal expansion when interrupting a different mode (say
2268 // ^X^F^X^P or ^P^X^X^P, see below)
2269 // nothing changes if interrupting mode 0, (eg, the flag
2270 // doesn't change when going to ADDING mode -- Acevedo
2271 if (!(compl_cont_status & CONT_INTRPT))
2272 compl_cont_status |= CONT_LOCAL;
2273 else if (compl_cont_mode != 0)
2274 compl_cont_status &= ~CONT_LOCAL;
2275 // FALLTHROUGH
2276 default:
2277 // If we have typed at least 2 ^X's... for modes != 0, we set
2278 // compl_cont_status = 0 (eg, as if we had just started ^X
2279 // mode).
2280 // For mode 0, we set "compl_cont_mode" to an impossible
2281 // value, in both cases ^X^X can be used to restart the same
2282 // mode (avoiding ADDING mode).
2283 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2284 // 'complete' and local ^P expansions respectively.
2285 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2286 // mode -- Acevedo
2287 if (c == Ctrl_X)
2288 {
2289 if (compl_cont_mode != 0)
2290 compl_cont_status = 0;
2291 else
2292 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2293 }
2294 ctrl_x_mode = CTRL_X_NORMAL;
2295 edit_submode = NULL;
2296 showmode();
2297 break;
2298 }
2299
2300 return retval;
2301}
2302
2303/*
2304 * Stop insert completion mode
2305 */
2306 static int
2307ins_compl_stop(int c, int prev_mode, int retval)
2308{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002309 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002310
2311 // Get here when we have finished typing a sequence of ^N and
2312 // ^P or other completion characters in CTRL-X mode. Free up
2313 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002314 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002315 {
John Marriott5e6ea922024-11-23 14:01:57 +01002316 char_u *ptr;
2317
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002318 // If any of the original typed text has been changed, eg when
2319 // ignorecase is set, we must add back-spaces to the redo
2320 // buffer. We add as few as necessary to delete just the part
2321 // of the original text that has changed.
2322 // When using the longest match, edited the match or used
2323 // CTRL-E then don't use the current match.
2324 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002325 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002326 else
2327 ptr = NULL;
2328 ins_compl_fixRedoBufForLeader(ptr);
2329 }
2330
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002331 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002332
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002333 // When completing whole lines: fix indent for 'cindent'.
2334 // Otherwise, break line if it's too long.
2335 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2336 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002337 // re-indent the current line
2338 if (want_cindent)
2339 {
2340 do_c_expr_indent();
2341 want_cindent = FALSE; // don't do it again
2342 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002343 }
2344 else
2345 {
2346 int prev_col = curwin->w_cursor.col;
2347
2348 // put the cursor on the last char, for 'tw' formatting
2349 if (prev_col > 0)
2350 dec_cursor();
2351 // only format when something was inserted
2352 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2353 insertchar(NUL, 0, -1);
2354 if (prev_col > 0
2355 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2356 inc_cursor();
2357 }
2358
2359 // If the popup menu is displayed pressing CTRL-Y means accepting
2360 // the selection without inserting anything. When
2361 // compl_enter_selects is set the Enter key does the same.
2362 if ((c == Ctrl_Y || (compl_enter_selects
2363 && (c == CAR || c == K_KENTER || c == NL)))
2364 && pum_visible())
2365 retval = TRUE;
2366
2367 // CTRL-E means completion is Ended, go back to the typed text.
2368 // but only do this, if the Popup is still visible
2369 if (c == Ctrl_E)
2370 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002371 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002372 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002373
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002374 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002375 if (compl_leader.string != NULL)
2376 {
2377 p = compl_leader.string;
2378 plen = compl_leader.length;
2379 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002380 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002381 {
2382 p = compl_orig_text.string;
2383 plen = compl_orig_text.length;
2384 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002385 if (p != NULL)
2386 {
2387 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002388
John Marriott5e6ea922024-11-23 14:01:57 +01002389 if ((int)plen > compl_len)
2390 ins_bytes_len(p + compl_len, (int)(plen - compl_len));
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002391 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002392 retval = TRUE;
2393 }
2394
2395 auto_format(FALSE, TRUE);
2396
2397 // Trigger the CompleteDonePre event to give scripts a chance to
2398 // act upon the completion before clearing the info, and restore
2399 // ctrl_x_mode, so that complete_info() can be used.
2400 ctrl_x_mode = prev_mode;
2401 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2402
2403 ins_compl_free();
2404 compl_started = FALSE;
2405 compl_matches = 0;
2406 if (!shortmess(SHM_COMPLETIONMENU))
2407 msg_clr_cmdline(); // necessary for "noshowmode"
2408 ctrl_x_mode = CTRL_X_NORMAL;
2409 compl_enter_selects = FALSE;
2410 if (edit_submode != NULL)
2411 {
2412 edit_submode = NULL;
2413 showmode();
2414 }
2415
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002416 if (c == Ctrl_C && cmdwin_type != 0)
2417 // Avoid the popup menu remains displayed when leaving the
2418 // command line window.
2419 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002420 // Indent now if a key was typed that is in 'cinkeys'.
2421 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2422 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002423 // Trigger the CompleteDone event to give scripts a chance to act
2424 // upon the end of completion.
2425 ins_apply_autocmds(EVENT_COMPLETEDONE);
2426
2427 return retval;
2428}
2429
2430/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002431 * Prepare for Insert mode completion, or stop it.
2432 * Called just after typing a character in Insert mode.
2433 * Returns TRUE when the character is not to be inserted;
2434 */
2435 int
2436ins_compl_prep(int c)
2437{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002438 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002439 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002440
2441 // Forget any previous 'special' messages if this is actually
2442 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2443 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2444 edit_submode_extra = NULL;
2445
zeertzjq440d4cb2023-03-02 17:51:32 +00002446 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002447 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002448 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002449 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002450 return retval;
2451
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002452#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002453 // Ignore mouse events in a popup window
2454 if (is_mouse_key(c))
2455 {
2456 // Ignore drag and release events, the position does not need to be in
2457 // the popup and it may have just closed.
2458 if (c == K_LEFTRELEASE
2459 || c == K_LEFTRELEASE_NM
2460 || c == K_MIDDLERELEASE
2461 || c == K_RIGHTRELEASE
2462 || c == K_X1RELEASE
2463 || c == K_X2RELEASE
2464 || c == K_LEFTDRAG
2465 || c == K_MIDDLEDRAG
2466 || c == K_RIGHTDRAG
2467 || c == K_X1DRAG
2468 || c == K_X2DRAG)
2469 return retval;
2470 if (popup_visible)
2471 {
2472 int row = mouse_row;
2473 int col = mouse_col;
2474 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2475
2476 if (wp != NULL && WIN_IS_POPUP(wp))
2477 return retval;
2478 }
2479 }
2480#endif
2481
zeertzjqdca29d92021-08-31 19:12:51 +02002482 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2483 {
2484 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2485 || !vim_is_ctrl_x_key(c))
2486 {
2487 // Not starting another completion mode.
2488 ctrl_x_mode = CTRL_X_CMDLINE;
2489
2490 // CTRL-X CTRL-Z should stop completion without inserting anything
2491 if (c == Ctrl_Z)
2492 retval = TRUE;
2493 }
2494 else
2495 {
2496 ctrl_x_mode = CTRL_X_CMDLINE;
2497
2498 // Other CTRL-X keys first stop completion, then start another
2499 // completion mode.
2500 ins_compl_prep(' ');
2501 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2502 }
2503 }
2504
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002505 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002506 if (ctrl_x_mode_not_defined_yet()
2507 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002508 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002509 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002510 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002511 }
2512
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002513 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002514 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2515 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002516 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002517 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002518 {
2519 // We're already in CTRL-X mode, do we stay in it?
2520 if (!vim_is_ctrl_x_key(c))
2521 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002522 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002523 ctrl_x_mode = CTRL_X_NORMAL;
2524 else
2525 ctrl_x_mode = CTRL_X_FINISHED;
2526 edit_submode = NULL;
2527 }
2528 showmode();
2529 }
2530
2531 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2532 {
2533 // Show error message from attempted keyword completion (probably
2534 // 'Pattern not found') until another key is hit, then go back to
2535 // showing what mode we are in.
2536 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002537 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002538 && c != Ctrl_R && !ins_compl_pum_key(c))
2539 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002540 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002541 }
2542 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2543 // Trigger the CompleteDone event to give scripts a chance to act
2544 // upon the (possibly failed) completion.
2545 ins_apply_autocmds(EVENT_COMPLETEDONE);
2546
LemonBoy2bf52dd2022-04-09 18:17:34 +01002547 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002548
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002549 // reset continue_* if we left expansion-mode, if we stay they'll be
2550 // (re)set properly in ins_complete()
2551 if (!vim_is_ctrl_x_key(c))
2552 {
2553 compl_cont_status = 0;
2554 compl_cont_mode = 0;
2555 }
2556
2557 return retval;
2558}
2559
2560/*
2561 * Fix the redo buffer for the completion leader replacing some of the typed
2562 * text. This inserts backspaces and appends the changed text.
2563 * "ptr" is the known leader text or NUL.
2564 */
2565 static void
2566ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2567{
John Marriott5e6ea922024-11-23 14:01:57 +01002568 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002569 char_u *p;
2570 char_u *ptr = ptr_arg;
2571
2572 if (ptr == NULL)
2573 {
John Marriott5e6ea922024-11-23 14:01:57 +01002574 if (compl_leader.string != NULL)
2575 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002576 else
2577 return; // nothing to do
2578 }
John Marriott5e6ea922024-11-23 14:01:57 +01002579 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002580 {
John Marriott5e6ea922024-11-23 14:01:57 +01002581 p = compl_orig_text.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002582 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2583 ;
2584 if (len > 0)
2585 len -= (*mb_head_off)(p, p + len);
2586 for (p += len; *p != NUL; MB_PTR_ADV(p))
2587 AppendCharToRedobuff(K_BS);
2588 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002589 if (ptr != NULL)
2590 AppendToRedobuffLit(ptr + len, -1);
2591}
2592
2593/*
2594 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2595 * (depending on flag) starting from buf and looking for a non-scanned
2596 * buffer (other than curbuf). curbuf is special, if it is called with
2597 * buf=curbuf then it has to be the first call for a given flag/expansion.
2598 *
2599 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2600 */
2601 static buf_T *
2602ins_compl_next_buf(buf_T *buf, int flag)
2603{
2604 static win_T *wp = NULL;
2605
2606 if (flag == 'w') // just windows
2607 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002608 if (buf == curbuf || !win_valid(wp))
2609 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002610 wp = curwin;
2611 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2612 && wp->w_buffer->b_scanned)
2613 ;
2614 buf = wp->w_buffer;
2615 }
2616 else
2617 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2618 // (unlisted buffers)
2619 // When completing whole lines skip unloaded buffers.
2620 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2621 && ((flag == 'U'
2622 ? buf->b_p_bl
2623 : (!buf->b_p_bl
2624 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2625 || buf->b_scanned))
2626 ;
2627 return buf;
2628}
2629
2630#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002631
2632# ifdef FEAT_EVAL
2633static callback_T cfu_cb; // 'completefunc' callback function
2634static callback_T ofu_cb; // 'omnifunc' callback function
2635static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2636# endif
2637
2638/*
2639 * Copy a global callback function to a buffer local callback.
2640 */
2641 static void
2642copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2643{
2644 free_callback(bufcb);
2645 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2646 copy_callback(bufcb, globcb);
2647}
2648
2649/*
2650 * Parse the 'completefunc' option value and set the callback function.
2651 * Invoked when the 'completefunc' option is set. The option value can be a
2652 * name of a function (string), or function(<name>) or funcref(<name>) or a
2653 * lambda expression.
2654 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002655 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002656did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002657{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002658 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2659 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002660
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002661 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002662
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002663 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002664}
2665
2666/*
2667 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002668 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002669 */
2670 void
2671set_buflocal_cfu_callback(buf_T *buf UNUSED)
2672{
2673# ifdef FEAT_EVAL
2674 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2675# endif
2676}
2677
2678/*
2679 * Parse the 'omnifunc' option value and set the callback function.
2680 * Invoked when the 'omnifunc' option is set. The option value can be a
2681 * name of a function (string), or function(<name>) or funcref(<name>) or a
2682 * lambda expression.
2683 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002684 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002685did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002686{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002687 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2688 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002689
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002690 set_buflocal_ofu_callback(curbuf);
2691 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002692}
2693
2694/*
2695 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002696 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002697 */
2698 void
2699set_buflocal_ofu_callback(buf_T *buf UNUSED)
2700{
2701# ifdef FEAT_EVAL
2702 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2703# endif
2704}
2705
2706/*
2707 * Parse the 'thesaurusfunc' option value and set the callback function.
2708 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2709 * name of a function (string), or function(<name>) or funcref(<name>) or a
2710 * lambda expression.
2711 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002712 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002713did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002714{
2715 int retval;
2716
zeertzjq6eda2692024-11-03 09:23:33 +01002717 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002718 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002719 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2720 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002721 else
2722 {
2723 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002724 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002725 // when using :set, free the local callback
2726 if (!(args->os_flags & OPT_GLOBAL))
2727 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002728 }
2729
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002730 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002731}
2732
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002733/*
2734 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002735 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002736 */
2737 int
2738set_ref_in_insexpand_funcs(int copyID)
2739{
2740 int abort = FALSE;
2741
2742 abort = set_ref_in_callback(&cfu_cb, copyID);
2743 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2744 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2745
2746 return abort;
2747}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002748
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002749/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002750 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002751 */
2752 static char_u *
2753get_complete_funcname(int type)
2754{
2755 switch (type)
2756 {
2757 case CTRL_X_FUNCTION:
2758 return curbuf->b_p_cfu;
2759 case CTRL_X_OMNI:
2760 return curbuf->b_p_ofu;
2761 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002762 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002763 default:
2764 return (char_u *)"";
2765 }
2766}
2767
2768/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002769 * Get the callback to use for insert mode completion.
2770 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002771 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002772get_insert_callback(int type)
2773{
2774 if (type == CTRL_X_FUNCTION)
2775 return &curbuf->b_cfu_cb;
2776 if (type == CTRL_X_OMNI)
2777 return &curbuf->b_ofu_cb;
2778 // CTRL_X_THESAURUS
2779 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2780}
2781
2782/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002783 * Execute user defined complete function 'completefunc', 'omnifunc' or
2784 * 'thesaurusfunc', and get matches in "matches".
2785 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002786 */
2787 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002788expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002789{
2790 list_T *matchlist = NULL;
2791 dict_T *matchdict = NULL;
2792 typval_T args[3];
2793 char_u *funcname;
2794 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002795 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002796 typval_T rettv;
2797 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002798 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002799
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002800 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002801 if (*funcname == NUL)
2802 return;
2803
2804 // Call 'completefunc' to obtain the list of matches.
2805 args[0].v_type = VAR_NUMBER;
2806 args[0].vval.v_number = 0;
2807 args[1].v_type = VAR_STRING;
2808 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2809 args[2].v_type = VAR_UNKNOWN;
2810
2811 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002812 // Lock the text to avoid weird things from happening. Also disallow
2813 // switching to another window, it should not be needed and may end up in
2814 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002815 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002816
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002817 cb = get_insert_callback(type);
2818 retval = call_callback(cb, 0, &rettv, 2, args);
2819
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002820 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002821 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002822 {
2823 switch (rettv.v_type)
2824 {
2825 case VAR_LIST:
2826 matchlist = rettv.vval.v_list;
2827 break;
2828 case VAR_DICT:
2829 matchdict = rettv.vval.v_dict;
2830 break;
2831 case VAR_SPECIAL:
2832 if (rettv.vval.v_number == VVAL_NONE)
2833 compl_opt_suppress_empty = TRUE;
2834 // FALLTHROUGH
2835 default:
2836 // TODO: Give error message?
2837 clear_tv(&rettv);
2838 break;
2839 }
2840 }
zeertzjqcfe45652022-05-27 17:26:55 +01002841 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002842
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002843 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002844 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002845 validate_cursor();
2846 if (!EQUAL_POS(curwin->w_cursor, pos))
2847 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002848 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002849 goto theend;
2850 }
2851
2852 if (matchlist != NULL)
2853 ins_compl_add_list(matchlist);
2854 else if (matchdict != NULL)
2855 ins_compl_add_dict(matchdict);
2856
2857theend:
2858 // Restore State, it might have been changed.
2859 State = save_State;
2860
2861 if (matchdict != NULL)
2862 dict_unref(matchdict);
2863 if (matchlist != NULL)
2864 list_unref(matchlist);
2865}
2866#endif // FEAT_COMPL_FUNC
2867
2868#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02002869
2870 static inline int
2871get_user_highlight_attr(char_u *hlname)
2872{
2873 if (hlname != NULL && *hlname != NUL)
2874 return syn_name2attr(hlname);
2875 return -1;
2876}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002877/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002878 * Add a match to the list of matches from a typeval_T.
2879 * If the given string is already in the list of completions, then return
2880 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2881 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002882 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002883 */
2884 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002885ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002886{
2887 char_u *word;
2888 int dup = FALSE;
2889 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002890 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002891 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002892 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002893 int status;
glepnir0fe17f82024-10-08 22:26:44 +02002894 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02002895 char_u *user_kind_hlname;
glepnir5c66e232024-11-15 19:58:27 +01002896 int extra_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002897
Bram Moolenaar08928322020-01-04 14:32:48 +01002898 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002899 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2900 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002901 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2902 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2903 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2904 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2905 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02002906
glepnir0fe17f82024-10-08 22:26:44 +02002907 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir5c66e232024-11-15 19:58:27 +01002908 extra_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02002909
2910 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir5c66e232024-11-15 19:58:27 +01002911 extra_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02002912
Bram Moolenaard61efa52022-07-23 09:52:04 +01002913 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2914 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2915 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002916 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002917 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2918 dup = dict_get_number(tv->vval.v_dict, "dup");
2919 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2920 empty = dict_get_number(tv->vval.v_dict, "empty");
2921 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2922 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002923 flags |= CP_EQUAL;
2924 }
2925 else
2926 {
2927 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002928 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002929 }
2930 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002931 {
2932 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002933 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002934 }
glepnir508e7852024-07-25 21:39:08 +02002935 status = ins_compl_add(word, -1, NULL, cptext,
glepnir5c66e232024-11-15 19:58:27 +01002936 &user_data, dir, flags, dup, extra_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002937 if (status != OK)
2938 clear_tv(&user_data);
2939 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002940}
2941
2942/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002943 * Add completions from a list.
2944 */
2945 static void
2946ins_compl_add_list(list_T *list)
2947{
2948 listitem_T *li;
2949 int dir = compl_direction;
2950
2951 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002952 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002953 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002954 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002955 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002956 // if dir was BACKWARD then honor it just once
2957 dir = FORWARD;
2958 else if (did_emsg)
2959 break;
2960 }
2961}
2962
2963/*
2964 * Add completions from a dict.
2965 */
2966 static void
2967ins_compl_add_dict(dict_T *dict)
2968{
2969 dictitem_T *di_refresh;
2970 dictitem_T *di_words;
2971
2972 // Check for optional "refresh" item.
2973 compl_opt_refresh_always = FALSE;
2974 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2975 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2976 {
2977 char_u *v = di_refresh->di_tv.vval.v_string;
2978
2979 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2980 compl_opt_refresh_always = TRUE;
2981 }
2982
2983 // Add completions from a "words" list.
2984 di_words = dict_find(dict, (char_u *)"words", 5);
2985 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2986 ins_compl_add_list(di_words->di_tv.vval.v_list);
2987}
2988
2989/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002990 * Start completion for the complete() function.
2991 * "startcol" is where the matched text starts (1 is first column).
2992 * "list" is the list of matches.
2993 */
2994 static void
2995set_completion(colnr_T startcol, list_T *list)
2996{
2997 int save_w_wrow = curwin->w_wrow;
2998 int save_w_leftcol = curwin->w_leftcol;
2999 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003000 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003001 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3002 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3003 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003004
3005 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003006 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003007 ins_compl_prep(' ');
3008 ins_compl_clear();
3009 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003010 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003011
3012 compl_direction = FORWARD;
3013 if (startcol > curwin->w_cursor.col)
3014 startcol = curwin->w_cursor.col;
3015 compl_col = startcol;
3016 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3017 // compl_pattern doesn't need to be set
John Marriott5e6ea922024-11-23 14:01:57 +01003018 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col, (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003019 if (p_ic)
3020 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003021 if (compl_orig_text.string == NULL)
3022 {
3023 compl_orig_text.length = 0;
3024 return;
3025 }
3026 compl_orig_text.length = (size_t)compl_length;
3027 if (ins_compl_add(compl_orig_text.string,
3028 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3029 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003030 return;
3031
3032 ctrl_x_mode = CTRL_X_EVAL;
3033
3034 ins_compl_add_list(list);
3035 compl_matches = ins_compl_make_cyclic();
3036 compl_started = TRUE;
3037 compl_used_match = TRUE;
3038 compl_cont_status = 0;
3039
3040 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003041 int no_select = compl_no_select || compl_longest;
3042 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003043 {
3044 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003045 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003046 // Down/Up has no real effect.
3047 ins_complete(K_UP, FALSE);
3048 }
3049 else
3050 ins_complete(Ctrl_N, FALSE);
3051 compl_enter_selects = compl_no_insert;
3052
3053 // Lazily show the popup menu, unless we got interrupted.
3054 if (!compl_interrupted)
3055 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003056 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003057 out_flush();
3058}
3059
3060/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003061 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003062 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003063 void
3064f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003065{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003066 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003067
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003068 if (in_vim9script()
3069 && (check_for_number_arg(argvars, 0) == FAIL
3070 || check_for_list_arg(argvars, 1) == FAIL))
3071 return;
3072
Bram Moolenaar24959102022-05-07 20:01:16 +01003073 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003074 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003075 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003076 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003077 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003078
3079 // Check for undo allowed here, because if something was already inserted
3080 // the line was already saved for undo and this check isn't done.
3081 if (!undo_allowed())
3082 return;
3083
Bram Moolenaard83392a2022-09-01 12:22:46 +01003084 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003085 {
3086 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3087 if (startcol > 0)
3088 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003089 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003090}
3091
3092/*
3093 * "complete_add()" function
3094 */
3095 void
3096f_complete_add(typval_T *argvars, typval_T *rettv)
3097{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003098 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003099 return;
3100
Bram Moolenaar440cf092021-04-03 20:13:30 +02003101 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003102}
3103
3104/*
3105 * "complete_check()" function
3106 */
3107 void
3108f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3109{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003110 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003111 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003112
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003113 ins_compl_check_keys(0, TRUE);
3114 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003115
3116 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003117}
3118
3119/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003120 * Return Insert completion mode name string
3121 */
3122 static char_u *
3123ins_compl_mode(void)
3124{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003125 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003126 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3127
3128 return (char_u *)"";
3129}
3130
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003131/*
3132 * Assign the sequence number to all the completion matches which don't have
3133 * one assigned yet.
3134 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003135 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003136ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003137{
3138 int number = 0;
3139 compl_T *match;
3140
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003141 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003142 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003143 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003144 // This should normally succeed already at the first loop
3145 // cycle, so it's fast!
3146 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003147 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003148 if (match->cp_number != -1)
3149 {
3150 number = match->cp_number;
3151 break;
3152 }
3153 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003154 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003155 for (match = match->cp_next;
3156 match != NULL && match->cp_number == -1;
3157 match = match->cp_next)
3158 match->cp_number = ++number;
3159 }
3160 else // BACKWARD
3161 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003162 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003163 // number. This should normally succeed already at the
3164 // first loop cycle, so it's fast!
3165 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003166 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003167 if (match->cp_number != -1)
3168 {
3169 number = match->cp_number;
3170 break;
3171 }
3172 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003173 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003174 for (match = match->cp_prev; match
3175 && match->cp_number == -1;
3176 match = match->cp_prev)
3177 match->cp_number = ++number;
3178 }
3179}
3180
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003181/*
3182 * Get complete information
3183 */
3184 static void
3185get_complete_info(list_T *what_list, dict_T *retdict)
3186{
3187 int ret = OK;
3188 listitem_T *item;
3189#define CI_WHAT_MODE 0x01
3190#define CI_WHAT_PUM_VISIBLE 0x02
3191#define CI_WHAT_ITEMS 0x04
3192#define CI_WHAT_SELECTED 0x08
3193#define CI_WHAT_INSERTED 0x10
3194#define CI_WHAT_ALL 0xff
3195 int what_flag;
3196
3197 if (what_list == NULL)
3198 what_flag = CI_WHAT_ALL;
3199 else
3200 {
3201 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003202 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003203 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003204 {
3205 char_u *what = tv_get_string(&item->li_tv);
3206
3207 if (STRCMP(what, "mode") == 0)
3208 what_flag |= CI_WHAT_MODE;
3209 else if (STRCMP(what, "pum_visible") == 0)
3210 what_flag |= CI_WHAT_PUM_VISIBLE;
3211 else if (STRCMP(what, "items") == 0)
3212 what_flag |= CI_WHAT_ITEMS;
3213 else if (STRCMP(what, "selected") == 0)
3214 what_flag |= CI_WHAT_SELECTED;
3215 else if (STRCMP(what, "inserted") == 0)
3216 what_flag |= CI_WHAT_INSERTED;
3217 }
3218 }
3219
3220 if (ret == OK && (what_flag & CI_WHAT_MODE))
3221 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3222
3223 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3224 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3225
Girish Palya8950bf72024-03-20 20:07:29 +01003226 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003227 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003228 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003229 dict_T *di;
3230 compl_T *match;
3231 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003232
Girish Palya8950bf72024-03-20 20:07:29 +01003233 if (what_flag & CI_WHAT_ITEMS)
3234 {
3235 li = list_alloc();
3236 if (li == NULL)
3237 return;
3238 ret = dict_add_list(retdict, "items", li);
3239 }
3240 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3241 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3242 ins_compl_update_sequence_numbers();
3243 if (ret == OK && compl_first_match != NULL)
3244 {
3245 int list_idx = 0;
3246 match = compl_first_match;
3247 do
3248 {
3249 if (!match_at_original_text(match))
3250 {
3251 if (what_flag & CI_WHAT_ITEMS)
3252 {
3253 di = dict_alloc();
3254 if (di == NULL)
3255 return;
3256 ret = list_append_dict(li, di);
3257 if (ret != OK)
3258 return;
John Marriott5e6ea922024-11-23 14:01:57 +01003259 dict_add_string(di, "word", match->cp_str.string);
Girish Palya8950bf72024-03-20 20:07:29 +01003260 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3261 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3262 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3263 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3264 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3265 // Add an empty string for backwards compatibility
3266 dict_add_string(di, "user_data", (char_u *)"");
3267 else
3268 dict_add_tv(di, "user_data", &match->cp_user_data);
3269 }
3270 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3271 selected_idx = list_idx;
3272 list_idx += 1;
3273 }
3274 match = match->cp_next;
3275 }
3276 while (match != NULL && !is_first_match(match));
3277 }
3278 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3279 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003280 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003281
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003282 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3283 {
3284 // TODO
3285 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003286}
3287
3288/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003289 * "complete_info()" function
3290 */
3291 void
3292f_complete_info(typval_T *argvars, typval_T *rettv)
3293{
3294 list_T *what_list = NULL;
3295
Bram Moolenaar93a10962022-06-16 11:42:09 +01003296 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003297 return;
3298
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003299 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3300 return;
3301
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003302 if (argvars[0].v_type != VAR_UNKNOWN)
3303 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003304 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003305 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003306 what_list = argvars[0].vval.v_list;
3307 }
3308 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003309}
3310#endif
3311
3312/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003313 * Returns TRUE when using a user-defined function for thesaurus completion.
3314 */
3315 static int
3316thesaurus_func_complete(int type UNUSED)
3317{
3318#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003319 return type == CTRL_X_THESAURUS
3320 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003321#else
3322 return FALSE;
3323#endif
3324}
3325
3326/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003327 * Return value of process_next_cpt_value()
3328 */
3329enum
3330{
3331 INS_COMPL_CPT_OK = 1,
3332 INS_COMPL_CPT_CONT,
3333 INS_COMPL_CPT_END
3334};
3335
3336/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003337 * state information used for getting the next set of insert completion
3338 * matches.
3339 */
3340typedef struct
3341{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003342 char_u *e_cpt_copy; // copy of 'complete'
3343 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003344 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003345 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003346 pos_T prev_match_pos; // previous match position
3347 int set_match_pos; // save first_match_pos/last_match_pos
3348 pos_T first_match_pos; // first match position
3349 pos_T last_match_pos; // last match position
3350 int found_all; // found all matches of a certain type.
3351 char_u *dict; // dictionary file to search
3352 int dict_f; // "dict" is an exact file name or not
3353} ins_compl_next_state_T;
3354
3355/*
3356 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003357 *
3358 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003359 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003360 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003361 * st->found_all - all matches of this type are found
3362 * st->ins_buf - search for completions in this buffer
3363 * st->first_match_pos - position of the first completion match
3364 * st->last_match_pos - position of the last completion match
3365 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003366 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003367 * st->dict - name of the dictionary or thesaurus file to search
3368 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003369 *
3370 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003371 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3372 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003373 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003374 */
3375 static int
3376process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003377 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003378 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003379 pos_T *start_match_pos,
3380 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003381{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003382 int compl_type = -1;
3383 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003384
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003385 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003386
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003387 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3388 st->e_cpt++;
3389
3390 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003391 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003392 st->ins_buf = curbuf;
3393 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394 // Move the cursor back one character so that ^N can match the
3395 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003396 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003397 {
3398 // Move the cursor to after the last character in the
3399 // buffer, so that word at start of buffer is found
3400 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003401 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003402 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003403 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003404 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003405 compl_type = 0;
3406
3407 // Remember the first match so that the loop stops when we
3408 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003409 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003410 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003411 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003412 && (st->ins_buf = ins_compl_next_buf(
3413 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003414 {
3415 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003416 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003417 {
3418 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003419 st->first_match_pos.col = st->last_match_pos.col = 0;
3420 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3421 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003422 compl_type = 0;
3423 }
3424 else // unloaded buffer, scan like dictionary
3425 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003426 st->found_all = TRUE;
3427 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003428 {
3429 status = INS_COMPL_CPT_CONT;
3430 goto done;
3431 }
3432 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003433 st->dict = st->ins_buf->b_fname;
3434 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003435 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003436 if (!shortmess(SHM_COMPLETIONSCAN))
3437 {
3438 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3439 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3440 st->ins_buf->b_fname == NULL
3441 ? buf_spname(st->ins_buf)
3442 : st->ins_buf->b_sfname == NULL
3443 ? st->ins_buf->b_fname
3444 : st->ins_buf->b_sfname);
3445 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3446 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003447 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003448 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003449 status = INS_COMPL_CPT_END;
3450 else
3451 {
3452 if (ctrl_x_mode_line_or_eval())
3453 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003454 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003455 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003456 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003457 compl_type = CTRL_X_DICTIONARY;
3458 else
3459 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003460 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003461 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003462 st->dict = st->e_cpt;
3463 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003464 }
3465 }
3466#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003467 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003468 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003469 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003470 compl_type = CTRL_X_PATH_DEFINES;
3471#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003472 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003473 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003474 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003475 if (!shortmess(SHM_COMPLETIONSCAN))
3476 {
3477 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3478 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3479 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3480 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003481 }
3482 else
3483 compl_type = -1;
3484
3485 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003486 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003487
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003488 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003489 if (compl_type == -1)
3490 status = INS_COMPL_CPT_CONT;
3491 }
3492
3493done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003494 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003495 return status;
3496}
3497
3498#ifdef FEAT_FIND_ID
3499/*
3500 * Get the next set of identifiers or defines matching "compl_pattern" in
3501 * included files.
3502 */
3503 static void
3504get_next_include_file_completion(int compl_type)
3505{
John Marriott5e6ea922024-11-23 14:01:57 +01003506 find_pattern_in_path(compl_pattern.string, compl_direction,
3507 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003508 (compl_type == CTRL_X_PATH_DEFINES
3509 && !(compl_cont_status & CONT_SOL))
3510 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003511 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003512}
3513#endif
3514
3515/*
3516 * Get the next set of words matching "compl_pattern" in dictionary or
3517 * thesaurus files.
3518 */
3519 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003520get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003521{
3522#ifdef FEAT_COMPL_FUNC
3523 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003524 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003525 else
3526#endif
3527 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003528 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003529 : (compl_type == CTRL_X_THESAURUS
3530 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3531 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003532 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003533 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003534 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003535}
3536
3537/*
3538 * Get the next set of tag names matching "compl_pattern".
3539 */
3540 static void
3541get_next_tag_completion(void)
3542{
3543 int save_p_ic;
3544 char_u **matches;
3545 int num_matches;
3546
3547 // set p_ic according to p_ic, p_scs and pat for find_tags().
3548 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003549 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003550
3551 // Find up to TAG_MANY matches. Avoids that an enormous number
3552 // of matches is found when compl_pattern is empty
3553 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003554 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003555 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003556 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003557 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3558 ins_compl_add_matches(num_matches, matches, p_ic);
3559 g_tag_at_cursor = FALSE;
3560 p_ic = save_p_ic;
3561}
3562
3563/*
glepnir8159fb12024-07-17 20:32:54 +02003564 * Compare function for qsort
3565 */
3566static int compare_scores(const void *a, const void *b)
3567{
3568 int idx_a = *(const int *)a;
3569 int idx_b = *(const int *)b;
3570 int score_a = compl_fuzzy_scores[idx_a];
3571 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003572 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3573 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003574}
3575
3576/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003577 * Get the next set of filename matching "compl_pattern".
3578 */
3579 static void
3580get_next_filename_completion(void)
3581{
3582 char_u **matches;
3583 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003584 char_u *ptr;
3585 garray_T fuzzy_indices;
3586 int i;
3587 int score;
3588 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003589 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003590 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3591 char_u **sorted_matches;
3592 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003593 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003594
glepnirb9de1a02024-08-02 19:14:38 +02003595#ifdef BACKSLASH_IN_FILENAME
3596 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3597 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3598#else
3599 char pathsep = PATHSEP;
3600#endif
3601
glepnir8159fb12024-07-17 20:32:54 +02003602 if (in_fuzzy)
3603 {
glepnirb9de1a02024-08-02 19:14:38 +02003604#ifdef BACKSLASH_IN_FILENAME
3605 if (curbuf->b_p_csl[0] == 's')
3606 {
John Marriott5e6ea922024-11-23 14:01:57 +01003607 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003608 {
3609 if (leader[i] == '\\')
3610 leader[i] = '/';
3611 }
3612 }
3613 else if (curbuf->b_p_csl[0] == 'b')
3614 {
John Marriott5e6ea922024-11-23 14:01:57 +01003615 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003616 {
3617 if (leader[i] == '/')
3618 leader[i] = '\\';
3619 }
3620 }
3621#endif
3622 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003623 if (last_sep == NULL)
3624 {
3625 // No path separator or separator is the last character,
3626 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003627 VIM_CLEAR_STRING(compl_pattern);
3628 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3629 if (compl_pattern.string == NULL)
3630 return;
3631 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003632 }
3633 else if (*(last_sep + 1) == '\0')
3634 in_fuzzy = FALSE;
3635 else
3636 {
3637 // Split leader into path and file parts
3638 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003639 char_u *path_with_wildcard;
3640
3641 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003642 if (path_with_wildcard != NULL)
3643 {
John Marriott5e6ea922024-11-23 14:01:57 +01003644 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3645 VIM_CLEAR_STRING(compl_pattern);
3646 compl_pattern.string = path_with_wildcard;
3647 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003648
3649 // Move leader to the file part
3650 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003651 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003652 }
3653 }
glepnir8159fb12024-07-17 20:32:54 +02003654 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003655
John Marriott5e6ea922024-11-23 14:01:57 +01003656 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003657 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3658 return;
3659
3660 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003661 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003662#ifdef BACKSLASH_IN_FILENAME
3663 if (curbuf->b_p_csl[0] != NUL)
3664 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003665 for (i = 0; i < num_matches; ++i)
3666 {
glepnir8159fb12024-07-17 20:32:54 +02003667 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003668 while (*ptr != NUL)
3669 {
3670 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3671 *ptr = '/';
3672 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3673 *ptr = '\\';
3674 ptr += (*mb_ptr2len)(ptr);
3675 }
3676 }
3677 }
3678#endif
glepnir8159fb12024-07-17 20:32:54 +02003679
3680 if (in_fuzzy)
3681 {
3682 ga_init2(&fuzzy_indices, sizeof(int), 10);
3683 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3684
3685 for (i = 0; i < num_matches; i++)
3686 {
3687 ptr = matches[i];
3688 score = fuzzy_match_str(ptr, leader);
3689 if (score > 0)
3690 {
3691 if (ga_grow(&fuzzy_indices, 1) == OK)
3692 {
3693 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3694 compl_fuzzy_scores[i] = score;
3695 fuzzy_indices.ga_len++;
3696 }
3697 }
3698 }
3699
Christian Brabandt220474d2024-07-20 13:26:44 +02003700 // prevent qsort from deref NULL pointer
3701 if (fuzzy_indices.ga_len > 0)
3702 {
3703 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3704 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003705
Christian Brabandt220474d2024-07-20 13:26:44 +02003706 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3707 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3708 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003709
Christian Brabandt220474d2024-07-20 13:26:44 +02003710 FreeWild(num_matches, matches);
3711 matches = sorted_matches;
3712 num_matches = fuzzy_indices.ga_len;
3713 }
glepnir6b6280c2024-07-27 16:25:45 +02003714 else if (leader_len > 0)
3715 {
3716 FreeWild(num_matches, matches);
3717 num_matches = 0;
3718 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003719
glepnir8159fb12024-07-17 20:32:54 +02003720 vim_free(compl_fuzzy_scores);
3721 ga_clear(&fuzzy_indices);
3722 }
3723
glepnir6b6280c2024-07-27 16:25:45 +02003724 if (num_matches > 0)
3725 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003726}
3727
3728/*
3729 * Get the next set of command-line completions matching "compl_pattern".
3730 */
3731 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003732get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003733{
3734 char_u **matches;
3735 int num_matches;
3736
John Marriott5e6ea922024-11-23 14:01:57 +01003737 if (expand_cmdline(&compl_xp, compl_pattern.string,
3738 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003739 ins_compl_add_matches(num_matches, matches, FALSE);
3740}
3741
3742/*
3743 * Get the next set of spell suggestions matching "compl_pattern".
3744 */
3745 static void
3746get_next_spell_completion(linenr_T lnum UNUSED)
3747{
3748#ifdef FEAT_SPELL
3749 char_u **matches;
3750 int num_matches;
3751
John Marriott5e6ea922024-11-23 14:01:57 +01003752 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003753 if (num_matches > 0)
3754 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003755 else
3756 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003757#endif
3758}
3759
3760/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003761 * Return the next word or line from buffer "ins_buf" at position
3762 * "cur_match_pos" for completion. The length of the match is set in "len".
3763 */
3764 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003765ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003766 buf_T *ins_buf, // buffer being scanned
3767 pos_T *cur_match_pos, // current match position
3768 int *match_len,
3769 int *cont_s_ipos) // next ^X<> will set initial_pos
3770{
3771 char_u *ptr;
3772 int len;
3773
3774 *match_len = 0;
3775 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3776 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003777 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003778 if (ctrl_x_mode_line_or_eval())
3779 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003780 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003781 {
3782 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3783 return NULL;
3784 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003785 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003786 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003787 {
3788 char_u *tmp_ptr = ptr;
3789
3790 ptr = skipwhite(tmp_ptr);
3791 len -= (int)(ptr - tmp_ptr);
3792 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003793 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003794 }
3795 else
3796 {
3797 char_u *tmp_ptr = ptr;
3798
John Marriott5e6ea922024-11-23 14:01:57 +01003799 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003800 {
3801 tmp_ptr += compl_length;
3802 // Skip if already inside a word.
3803 if (vim_iswordp(tmp_ptr))
3804 return NULL;
3805 // Find start of next word.
3806 tmp_ptr = find_word_start(tmp_ptr);
3807 }
3808 // Find end of this word.
3809 tmp_ptr = find_word_end(tmp_ptr);
3810 len = (int)(tmp_ptr - ptr);
3811
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003812 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003813 {
3814 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3815 {
3816 // Try next line, if any. the new word will be
3817 // "join" as if the normal command "J" was used.
3818 // IOSIZE is always greater than
3819 // compl_length, so the next STRNCPY always
3820 // works -- Acevedo
3821 STRNCPY(IObuff, ptr, len);
3822 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3823 tmp_ptr = ptr = skipwhite(ptr);
3824 // Find start of next word.
3825 tmp_ptr = find_word_start(tmp_ptr);
3826 // Find end of next word.
3827 tmp_ptr = find_word_end(tmp_ptr);
3828 if (tmp_ptr > ptr)
3829 {
3830 if (*ptr != ')' && IObuff[len - 1] != TAB)
3831 {
3832 if (IObuff[len - 1] != ' ')
3833 IObuff[len++] = ' ';
3834 // IObuf =~ "\k.* ", thus len >= 2
3835 if (p_js
3836 && (IObuff[len - 2] == '.'
3837 || (vim_strchr(p_cpo, CPO_JOINSP)
3838 == NULL
3839 && (IObuff[len - 2] == '?'
3840 || IObuff[len - 2] == '!'))))
3841 IObuff[len++] = ' ';
3842 }
3843 // copy as much as possible of the new word
3844 if (tmp_ptr - ptr >= IOSIZE - len)
3845 tmp_ptr = ptr + IOSIZE - len - 1;
3846 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3847 len += (int)(tmp_ptr - ptr);
3848 *cont_s_ipos = TRUE;
3849 }
3850 IObuff[len] = NUL;
3851 ptr = IObuff;
3852 }
3853 if (len == compl_length)
3854 return NULL;
3855 }
3856 }
3857
3858 *match_len = len;
3859 return ptr;
3860}
3861
3862/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003863 * Get the next set of words matching "compl_pattern" for default completion(s)
3864 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003865 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3866 * position "st->start_pos" in the "compl_direction" direction. If
3867 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3868 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003869 * Returns OK if a new next match is found, otherwise returns FAIL.
3870 */
3871 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003872get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003873{
3874 int found_new_match = FAIL;
3875 int save_p_scs;
3876 int save_p_ws;
3877 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003878 char_u *ptr = NULL;
3879 int len = 0;
3880 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3881 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003882
3883 // If 'infercase' is set, don't use 'smartcase' here
3884 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003885 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003886 p_scs = FALSE;
3887
3888 // Buffers other than curbuf are scanned from the beginning or the
3889 // end but never from the middle, thus setting nowrapscan in this
3890 // buffer is a good idea, on the other hand, we always set
3891 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3892 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003893 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003894 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003895 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003896 p_ws = TRUE;
3897 looped_around = FALSE;
3898 for (;;)
3899 {
3900 int cont_s_ipos = FALSE;
3901
3902 ++msg_silent; // Don't want messages for wrapscan.
3903
3904 // ctrl_x_mode_line_or_eval() || word-wise search that
3905 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003906 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003907 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01003908 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02003909 else if (in_fuzzy)
3910 found_new_match = search_for_fuzzy_match(st->ins_buf,
3911 st->cur_match_pos, leader, compl_direction,
3912 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003913 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003914 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01003915 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02003916 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003917 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003918 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003919 {
3920 // set "compl_started" even on fail
3921 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003922 st->first_match_pos = *st->cur_match_pos;
3923 st->last_match_pos = *st->cur_match_pos;
3924 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003925 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003926 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3927 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003928 {
3929 found_new_match = FAIL;
3930 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003931 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003932 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3933 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3934 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003935 {
3936 if (looped_around)
3937 found_new_match = FAIL;
3938 else
3939 looped_around = TRUE;
3940 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003941 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003942 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3943 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3944 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003945 {
3946 if (looped_around)
3947 found_new_match = FAIL;
3948 else
3949 looped_around = TRUE;
3950 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003951 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003952 if (found_new_match == FAIL)
3953 break;
3954
3955 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003956 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003957 && start_pos->lnum == st->cur_match_pos->lnum
3958 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003959 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003960
glepnir8159fb12024-07-17 20:32:54 +02003961 if (!in_fuzzy)
3962 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3963 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003964 if (ptr == NULL)
3965 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003966
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003967 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003968 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003969 0, cont_s_ipos) != NOTDONE)
3970 {
3971 found_new_match = OK;
3972 break;
3973 }
3974 }
3975 p_scs = save_p_scs;
3976 p_ws = save_p_ws;
3977
3978 return found_new_match;
3979}
3980
3981/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003982 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003983 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003984 */
3985 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003986get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003987{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003988 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003989
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003990 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003991 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003992 case -1:
3993 break;
3994#ifdef FEAT_FIND_ID
3995 case CTRL_X_PATH_PATTERNS:
3996 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003997 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003998 break;
3999#endif
4000
4001 case CTRL_X_DICTIONARY:
4002 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004003 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4004 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004005 break;
4006
4007 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004008 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004009 break;
4010
4011 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004012 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004013 break;
4014
4015 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004016 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004017 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004018 break;
4019
4020#ifdef FEAT_COMPL_FUNC
4021 case CTRL_X_FUNCTION:
4022 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004023 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004024 break;
4025#endif
4026
4027 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004028 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004029 break;
4030
4031 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004032 found_new_match = get_next_default_completion(st, ini);
4033 if (found_new_match == FAIL && st->ins_buf == curbuf)
4034 st->found_all = TRUE;
4035 }
4036
4037 // check if compl_curr_match has changed, (e.g. other type of
4038 // expansion added something)
4039 if (type != 0 && compl_curr_match != compl_old_match)
4040 found_new_match = OK;
4041
4042 return found_new_match;
4043}
4044
4045/*
4046 * Get the next expansion(s), using "compl_pattern".
4047 * The search starts at position "ini" in curbuf and in the direction
4048 * compl_direction.
4049 * When "compl_started" is FALSE start at that position, otherwise continue
4050 * where we stopped searching before.
4051 * This may return before finding all the matches.
4052 * Return the total number of matches or -1 if still unknown -- Acevedo
4053 */
4054 static int
4055ins_compl_get_exp(pos_T *ini)
4056{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004057 static ins_compl_next_state_T st;
4058 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004059 int i;
4060 int found_new_match;
4061 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004062 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004063
4064 if (!compl_started)
4065 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004066 buf_T *buf;
4067
4068 FOR_ALL_BUFFERS(buf)
4069 buf->b_scanned = 0;
4070 if (!st_cleared)
4071 {
4072 CLEAR_FIELD(st);
4073 st_cleared = TRUE;
4074 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004075 st.found_all = FALSE;
4076 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004077 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004078 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004079 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4080 ? (char_u *)"." : curbuf->b_p_cpt);
4081 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004082 st.last_match_pos = st.first_match_pos = *ini;
4083 }
4084 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4085 st.ins_buf = curbuf; // In case the buffer was wiped out.
4086
4087 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004088 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004089 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004090
4091 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4092 for (;;)
4093 {
4094 found_new_match = FAIL;
4095 st.set_match_pos = FALSE;
4096
4097 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4098 // or if found_all says this entry is done. For ^X^L only use the
4099 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004100 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004101 && (!compl_started || st.found_all))
4102 {
glepnir8159fb12024-07-17 20:32:54 +02004103 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004104
4105 if (status == INS_COMPL_CPT_END)
4106 break;
4107 if (status == INS_COMPL_CPT_CONT)
4108 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004109 }
4110
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004111 // If complete() was called then compl_pattern has been reset. The
4112 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004113 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004114 break;
4115
4116 // get the next set of completion matches
4117 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004118
4119 // break the loop for specialized modes (use 'complete' just for the
4120 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4121 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004122 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4123 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004124 {
4125 if (got_int)
4126 break;
4127 // Fill the popup menu as soon as possible.
4128 if (type != -1)
4129 ins_compl_check_keys(0, FALSE);
4130
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004131 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004132 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4133 break;
4134 compl_started = TRUE;
4135 }
4136 else
4137 {
4138 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004139 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004140 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004141
4142 compl_started = FALSE;
4143 }
4144 }
4145 compl_started = TRUE;
4146
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004147 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004148 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004149 found_new_match = FAIL;
4150
4151 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004152 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004153 && !ctrl_x_mode_line_or_eval()))
4154 i = ins_compl_make_cyclic();
4155
4156 if (compl_old_match != NULL)
4157 {
4158 // If several matches were added (FORWARD) or the search failed and has
4159 // just been made cyclic then we have to move compl_curr_match to the
4160 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004161 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004162 : compl_old_match->cp_prev;
4163 if (compl_curr_match == NULL)
4164 compl_curr_match = compl_old_match;
4165 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004166 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004167
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004168 return i;
4169}
4170
4171/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004172 * Update "compl_shown_match" to the actually shown match, it may differ when
4173 * "compl_leader" is used to omit some of the matches.
4174 */
4175 static void
4176ins_compl_update_shown_match(void)
4177{
4178 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004179 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004180 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004181 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004182 compl_shown_match = compl_shown_match->cp_next;
4183
4184 // If we didn't find it searching forward, and compl_shows_dir is
4185 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004186 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004187 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004188 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004189 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004190 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004191 {
4192 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004193 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004194 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004195 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004196 compl_shown_match = compl_shown_match->cp_prev;
4197 }
4198}
4199
4200/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004201 * Delete the old text being completed.
4202 */
4203 void
4204ins_compl_delete(void)
4205{
4206 int col;
4207
4208 // In insert mode: Delete the typed part.
4209 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004210 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004211 if ((int)curwin->w_cursor.col > col)
4212 {
4213 if (stop_arrow() == FAIL)
4214 return;
4215 backspace_until_column(col);
4216 }
4217
4218 // TODO: is this sufficient for redrawing? Redrawing everything causes
4219 // flicker, thus we can't do that.
4220 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004221#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004222 // clear v:completed_item
4223 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004224#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004225}
4226
4227/*
4228 * Insert the new text being completed.
4229 * "in_compl_func" is TRUE when called from complete_check().
4230 */
4231 void
4232ins_compl_insert(int in_compl_func)
4233{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004234 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004235
4236 // Make sure we don't go over the end of the string, this can happen with
4237 // illegal bytes.
John Marriott5e6ea922024-11-23 14:01:57 +01004238 if (compl_len < (int)compl_shown_match->cp_str.length)
4239 ins_bytes(compl_shown_match->cp_str.string + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004240 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004241 compl_used_match = FALSE;
4242 else
4243 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004244#ifdef FEAT_EVAL
4245 {
4246 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4247
4248 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4249 }
4250#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004251 if (!in_compl_func)
4252 compl_curr_match = compl_shown_match;
4253}
4254
4255/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004256 * show the file name for the completion match (if any). Truncate the file
4257 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004258 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004259 static void
4260ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004261{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004262 char *lead = _("match in file");
4263 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4264 char_u *s;
4265 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004266
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004267 if (space <= 0)
4268 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004269
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004270 // We need the tail that fits. With double-byte encoding going
4271 // back from the end is very slow, thus go from the start and keep
4272 // the text that fits in "space" between "s" and "e".
4273 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004274 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004275 space -= ptr2cells(e);
4276 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004277 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004278 space += ptr2cells(s);
4279 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004280 }
4281 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004282 msg_hist_off = TRUE;
4283 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4284 s > compl_shown_match->cp_fname ? "<" : "", s);
4285 msg((char *)IObuff);
4286 msg_hist_off = FALSE;
4287 redraw_cmdline = FALSE; // don't overwrite!
4288}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004289
glepnirdca57fb2024-06-04 22:01:21 +02004290/*
zeertzjq551d8c32024-06-05 19:53:32 +02004291 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004292 */
glepnira218cc62024-06-03 19:32:39 +02004293 static compl_T *
4294find_comp_when_fuzzy(void)
4295{
4296 int score;
4297 char_u* str;
4298 int target_idx = -1;
4299 int is_forward = compl_shows_dir_forward();
4300 int is_backward = compl_shows_dir_backward();
4301 compl_T *comp = NULL;
4302
glepnir43eef882024-06-19 20:20:48 +02004303 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004304 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004305 return compl_first_match != compl_shown_match ? compl_first_match :
4306 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004307
4308 if (is_forward)
4309 target_idx = compl_selected_item + 1;
4310 else if (is_backward)
4311 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004312 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004313
4314 score = compl_match_array[target_idx].pum_score;
4315 str = compl_match_array[target_idx].pum_text;
4316
4317 comp = compl_first_match;
4318 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004319 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004320 return comp;
4321 comp = comp->cp_next;
4322 } while (comp != NULL && !is_first_match(comp));
4323
4324 return NULL;
4325}
4326
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004327/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004328 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004329 * times. The number of matches found is returned in 'num_matches'.
4330 *
4331 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4332 * get more completions. If it is FALSE, then do nothing when there are no more
4333 * completions in the given direction.
4334 *
4335 * If "advance" is TRUE, then completion will move to the first match.
4336 * Otherwise, the original text will be shown.
4337 *
4338 * Returns OK on success and -1 if the number of matches are unknown.
4339 */
4340 static int
4341find_next_completion_match(
4342 int allow_get_expansion,
4343 int todo, // repeat completion this many times
4344 int advance,
4345 int *num_matches)
4346{
4347 int found_end = FALSE;
4348 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004349 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004350 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4351 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004352
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004353 while (--todo >= 0)
4354 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004355 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004356 {
glepniraced8c22024-06-15 15:13:05 +02004357 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4358 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004359 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004360 && (is_first_match(compl_shown_match->cp_next)
4361 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004362 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004363 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004364 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004365 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004366 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004367 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4368 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004369 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004370 }
4371 else
4372 {
4373 if (!allow_get_expansion)
4374 {
4375 if (advance)
4376 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004377 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004378 compl_pending -= todo + 1;
4379 else
4380 compl_pending += todo + 1;
4381 }
4382 return -1;
4383 }
4384
4385 if (!compl_no_select && advance)
4386 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004387 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004388 --compl_pending;
4389 else
4390 ++compl_pending;
4391 }
4392
4393 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004394 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004395
4396 // handle any pending completions
4397 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004398 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004399 {
4400 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4401 {
4402 compl_shown_match = compl_shown_match->cp_next;
4403 --compl_pending;
4404 }
4405 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4406 {
4407 compl_shown_match = compl_shown_match->cp_prev;
4408 ++compl_pending;
4409 }
4410 else
4411 break;
4412 }
4413 found_end = FALSE;
4414 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004415 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004416 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004417 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004418 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004419 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004420 ++todo;
4421 else
4422 // Remember a matching item.
4423 found_compl = compl_shown_match;
4424
4425 // Stop at the end of the list when we found a usable match.
4426 if (found_end)
4427 {
4428 if (found_compl != NULL)
4429 {
4430 compl_shown_match = found_compl;
4431 break;
4432 }
4433 todo = 1; // use first usable match after wrapping around
4434 }
4435 }
4436
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004437 return OK;
4438}
4439
4440/*
4441 * Fill in the next completion in the current direction.
4442 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4443 * get more completions. If it is FALSE, then we just do nothing when there
4444 * are no more completions in a given direction. The latter case is used when
4445 * we are still in the middle of finding completions, to allow browsing
4446 * through the ones found so far.
4447 * Return the total number of matches, or -1 if still unknown -- webb.
4448 *
4449 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4450 * compl_shown_match here.
4451 *
4452 * Note that this function may be called recursively once only. First with
4453 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4454 * calls this function with "allow_get_expansion" FALSE.
4455 */
4456 static int
4457ins_compl_next(
4458 int allow_get_expansion,
4459 int count, // repeat completion this many times; should
4460 // be at least 1
4461 int insert_match, // Insert the newly selected match
4462 int in_compl_func) // called from complete_check()
4463{
4464 int num_matches = -1;
4465 int todo = count;
4466 int advance;
4467 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004468 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004469 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004470 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4471 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004472
4473 // When user complete function return -1 for findstart which is next
4474 // time of 'always', compl_shown_match become NULL.
4475 if (compl_shown_match == NULL)
4476 return -1;
4477
John Marriott5e6ea922024-11-23 14:01:57 +01004478 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004479 && !match_at_original_text(compl_shown_match)
4480 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004481 // Update "compl_shown_match" to the actually shown match
4482 ins_compl_update_shown_match();
4483
4484 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004485 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004486 // Delete old text to be replaced
4487 ins_compl_delete();
4488
4489 // When finding the longest common text we stick at the original text,
4490 // don't let CTRL-N or CTRL-P move to the first match.
4491 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4492
4493 // When restarting the search don't insert the first match either.
4494 if (compl_restarting)
4495 {
4496 advance = FALSE;
4497 compl_restarting = FALSE;
4498 }
4499
4500 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4501 // around.
4502 if (find_next_completion_match(allow_get_expansion, todo, advance,
4503 &num_matches) == -1)
4504 return -1;
4505
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004506 if (curbuf != orig_curbuf)
4507 {
4508 // In case some completion function switched buffer, don't want to
4509 // insert the completion elsewhere.
4510 return -1;
4511 }
4512
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004513 // Insert the text of the new completion, or the compl_leader.
4514 if (compl_no_insert && !started)
4515 {
John Marriott5e6ea922024-11-23 14:01:57 +01004516 ins_bytes(compl_orig_text.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004517 compl_used_match = FALSE;
4518 }
4519 else if (insert_match)
4520 {
4521 if (!compl_get_longest || compl_used_match)
4522 ins_compl_insert(in_compl_func);
4523 else
John Marriott5e6ea922024-11-23 14:01:57 +01004524 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004525 }
4526 else
4527 compl_used_match = FALSE;
4528
4529 if (!allow_get_expansion)
4530 {
4531 // may undisplay the popup menu first
4532 ins_compl_upd_pum();
4533
4534 if (pum_enough_matches())
4535 // Will display the popup menu, don't redraw yet to avoid flicker.
4536 pum_call_update_screen();
4537 else
4538 // Not showing the popup menu yet, redraw to show the user what was
4539 // inserted.
4540 update_screen(0);
4541
4542 // display the updated popup menu
4543 ins_compl_show_pum();
4544#ifdef FEAT_GUI
4545 if (gui.in_use)
4546 {
4547 // Show the cursor after the match, not after the redrawn text.
4548 setcursor();
4549 out_flush_cursor(FALSE, FALSE);
4550 }
4551#endif
4552
4553 // Delete old text to be replaced, since we're still searching and
4554 // don't want to match ourselves!
4555 ins_compl_delete();
4556 }
4557
4558 // Enter will select a match when the match wasn't inserted and the popup
4559 // menu is visible.
4560 if (compl_no_insert && !started)
4561 compl_enter_selects = TRUE;
4562 else
4563 compl_enter_selects = !insert_match && compl_match_array != NULL;
4564
4565 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004566 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004567 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004568
4569 return num_matches;
4570}
4571
4572/*
4573 * Call this while finding completions, to check whether the user has hit a key
4574 * that should change the currently displayed completion, or exit completion
4575 * mode. Also, when compl_pending is not zero, show a completion as soon as
4576 * possible. -- webb
4577 * "frequency" specifies out of how many calls we actually check.
4578 * "in_compl_func" is TRUE when called from complete_check(), don't set
4579 * compl_curr_match.
4580 */
4581 void
4582ins_compl_check_keys(int frequency, int in_compl_func)
4583{
4584 static int count = 0;
4585 int c;
4586
4587 // Don't check when reading keys from a script, :normal or feedkeys().
4588 // That would break the test scripts. But do check for keys when called
4589 // from complete_check().
4590 if (!in_compl_func && (using_script() || ex_normal_busy))
4591 return;
4592
4593 // Only do this at regular intervals
4594 if (++count < frequency)
4595 return;
4596 count = 0;
4597
4598 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4599 // can't do its work correctly.
4600 c = vpeekc_any();
4601 if (c != NUL)
4602 {
4603 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4604 {
4605 c = safe_vgetc(); // Eat the character
4606 compl_shows_dir = ins_compl_key2dir(c);
4607 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4608 c != K_UP && c != K_DOWN, in_compl_func);
4609 }
4610 else
4611 {
4612 // Need to get the character to have KeyTyped set. We'll put it
4613 // back with vungetc() below. But skip K_IGNORE.
4614 c = safe_vgetc();
4615 if (c != K_IGNORE)
4616 {
4617 // Don't interrupt completion when the character wasn't typed,
4618 // e.g., when doing @q to replay keys.
4619 if (c != Ctrl_R && KeyTyped)
4620 compl_interrupted = TRUE;
4621
4622 vungetc(c);
4623 }
4624 }
4625 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004626 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004627 {
4628 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4629
4630 compl_pending = 0;
4631 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4632 }
4633}
4634
4635/*
4636 * Decide the direction of Insert mode complete from the key typed.
4637 * Returns BACKWARD or FORWARD.
4638 */
4639 static int
4640ins_compl_key2dir(int c)
4641{
4642 if (c == Ctrl_P || c == Ctrl_L
4643 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4644 return BACKWARD;
4645 return FORWARD;
4646}
4647
4648/*
4649 * Return TRUE for keys that are used for completion only when the popup menu
4650 * is visible.
4651 */
4652 static int
4653ins_compl_pum_key(int c)
4654{
4655 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4656 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4657 || c == K_UP || c == K_DOWN);
4658}
4659
4660/*
4661 * Decide the number of completions to move forward.
4662 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4663 */
4664 static int
4665ins_compl_key2count(int c)
4666{
4667 int h;
4668
4669 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4670 {
4671 h = pum_get_height();
4672 if (h > 3)
4673 h -= 2; // keep some context
4674 return h;
4675 }
4676 return 1;
4677}
4678
4679/*
4680 * Return TRUE if completion with "c" should insert the match, FALSE if only
4681 * to change the currently selected completion.
4682 */
4683 static int
4684ins_compl_use_match(int c)
4685{
4686 switch (c)
4687 {
4688 case K_UP:
4689 case K_DOWN:
4690 case K_PAGEDOWN:
4691 case K_KPAGEDOWN:
4692 case K_S_DOWN:
4693 case K_PAGEUP:
4694 case K_KPAGEUP:
4695 case K_S_UP:
4696 return FALSE;
4697 }
4698 return TRUE;
4699}
4700
4701/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004702 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4703 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004704 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004705 * Uses the global variables: compl_cont_status and ctrl_x_mode
4706 */
4707 static int
4708get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4709{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004710 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004711 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004712 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004713 {
4714 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4715 ;
4716 compl_col += ++startcol;
4717 compl_length = curs_col - startcol;
4718 }
4719 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004720 {
John Marriott5e6ea922024-11-23 14:01:57 +01004721 compl_pattern.string = str_foldcase(line + compl_col,
4722 compl_length, NULL, 0);
4723 if (compl_pattern.string == NULL)
4724 {
4725 compl_pattern.length = 0;
4726 return FAIL;
4727 }
4728 compl_pattern.length = STRLEN(compl_pattern.string);
4729 }
4730 else
4731 {
4732 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4733 if (compl_pattern.string == NULL)
4734 {
4735 compl_pattern.length = 0;
4736 return FAIL;
4737 }
4738 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02004739 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004740 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004741 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004742 {
4743 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004744 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01004745 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004746
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004747 if (!vim_iswordp(line + compl_col)
4748 || (compl_col > 0
4749 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004750 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004751 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004752 prefixlen = 0;
4753 }
John Marriott5e6ea922024-11-23 14:01:57 +01004754
4755 // we need up to 2 extra chars for the prefix
4756 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
4757 compl_pattern.string = alloc(n);
4758 if (compl_pattern.string == NULL)
4759 {
4760 compl_pattern.length = 0;
4761 return FAIL;
4762 }
4763 STRCPY((char *)compl_pattern.string, prefix);
4764 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004765 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004766 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004767 }
4768 else if (--startcol < 0
4769 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4770 {
John Marriott5e6ea922024-11-23 14:01:57 +01004771 size_t len = STRLEN_LITERAL("\\<\\k\\k");
4772
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004773 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01004774 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
4775 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004776 {
John Marriott5e6ea922024-11-23 14:01:57 +01004777 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004778 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004779 }
John Marriott5e6ea922024-11-23 14:01:57 +01004780 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004781 compl_col += curs_col;
4782 compl_length = 0;
4783 }
4784 else
4785 {
4786 // Search the point of change class of multibyte character
4787 // or not a word single byte character backward.
4788 if (has_mbyte)
4789 {
4790 int base_class;
4791 int head_off;
4792
4793 startcol -= (*mb_head_off)(line, line + startcol);
4794 base_class = mb_get_class(line + startcol);
4795 while (--startcol >= 0)
4796 {
4797 head_off = (*mb_head_off)(line, line + startcol);
4798 if (base_class != mb_get_class(line + startcol
4799 - head_off))
4800 break;
4801 startcol -= head_off;
4802 }
4803 }
4804 else
4805 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4806 ;
4807 compl_col += ++startcol;
4808 compl_length = (int)curs_col - startcol;
4809 if (compl_length == 1)
4810 {
4811 // Only match word with at least two chars -- webb
4812 // there's no need to call quote_meta,
4813 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01004814 compl_pattern.string = alloc(7);
4815 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004816 {
John Marriott5e6ea922024-11-23 14:01:57 +01004817 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004818 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004819 }
John Marriott5e6ea922024-11-23 14:01:57 +01004820 STRCPY((char *)compl_pattern.string, "\\<");
4821 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
4822 STRCAT((char *)compl_pattern.string, "\\k");
4823 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004824 }
4825 else
4826 {
John Marriott5e6ea922024-11-23 14:01:57 +01004827 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
4828
4829 compl_pattern.string = alloc(n);
4830 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004831 {
John Marriott5e6ea922024-11-23 14:01:57 +01004832 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004833 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004834 }
John Marriott5e6ea922024-11-23 14:01:57 +01004835 STRCPY((char *)compl_pattern.string, "\\<");
4836 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004837 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004838 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004839 }
4840 }
4841
4842 return OK;
4843}
4844
4845/*
4846 * Get the pattern, column and length for whole line completion or for the
4847 * complete() function.
4848 * Sets the global variables: compl_col, compl_length and compl_pattern.
4849 */
4850 static int
4851get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4852{
4853 compl_col = (colnr_T)getwhitecols(line);
4854 compl_length = (int)curs_col - (int)compl_col;
4855 if (compl_length < 0) // cursor in indent: empty pattern
4856 compl_length = 0;
4857 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004858 {
John Marriott5e6ea922024-11-23 14:01:57 +01004859 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
4860 NULL, 0);
4861 if (compl_pattern.string == NULL)
4862 {
4863 compl_pattern.length = 0;
4864 return FAIL;
4865 }
4866 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02004867 }
John Marriott5e6ea922024-11-23 14:01:57 +01004868 else
4869 {
4870 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4871 if (compl_pattern.string == NULL)
4872 {
4873 compl_pattern.length = 0;
4874 return FAIL;
4875 }
4876 compl_pattern.length = (size_t)compl_length;
4877 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004878
4879 return OK;
4880}
4881
4882/*
4883 * Get the pattern, column and length for filename completion.
4884 * Sets the global variables: compl_col, compl_length and compl_pattern.
4885 */
4886 static int
4887get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4888{
4889 // Go back to just before the first filename character.
4890 if (startcol > 0)
4891 {
4892 char_u *p = line + startcol;
4893
4894 MB_PTR_BACK(line, p);
4895 while (p > line && vim_isfilec(PTR2CHAR(p)))
4896 MB_PTR_BACK(line, p);
4897 if (p == line && vim_isfilec(PTR2CHAR(p)))
4898 startcol = 0;
4899 else
4900 startcol = (int)(p - line) + 1;
4901 }
4902
4903 compl_col += startcol;
4904 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01004905 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
4906 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004907 {
John Marriott5e6ea922024-11-23 14:01:57 +01004908 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004909 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004910 }
4911
John Marriott5e6ea922024-11-23 14:01:57 +01004912 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004913
4914 return OK;
4915}
4916
4917/*
4918 * Get the pattern, column and length for command-line completion.
4919 * Sets the global variables: compl_col, compl_length and compl_pattern.
4920 */
4921 static int
4922get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4923{
John Marriott5e6ea922024-11-23 14:01:57 +01004924 compl_pattern.string = vim_strnsave(line, curs_col);
4925 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004926 {
John Marriott5e6ea922024-11-23 14:01:57 +01004927 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004928 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004929 }
John Marriott5e6ea922024-11-23 14:01:57 +01004930 compl_pattern.length = curs_col;
4931 set_cmd_context(&compl_xp, compl_pattern.string,
4932 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004933 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4934 || compl_xp.xp_context == EXPAND_NOTHING)
4935 // No completion possible, use an empty pattern to get a
4936 // "pattern not found" message.
4937 compl_col = curs_col;
4938 else
John Marriott5e6ea922024-11-23 14:01:57 +01004939 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004940 compl_length = curs_col - compl_col;
4941
4942 return OK;
4943}
4944
4945/*
4946 * Get the pattern, column and length for user defined completion ('omnifunc',
4947 * 'completefunc' and 'thesaurusfunc')
4948 * Sets the global variables: compl_col, compl_length and compl_pattern.
4949 * Uses the global variable: spell_bad_len
4950 */
4951 static int
4952get_userdefined_compl_info(colnr_T curs_col UNUSED)
4953{
4954 int ret = FAIL;
4955
4956#ifdef FEAT_COMPL_FUNC
4957 // Call user defined function 'completefunc' with "a:findstart"
4958 // set to 1 to obtain the length of text to use for completion.
4959 char_u *line;
4960 typval_T args[3];
4961 int col;
4962 char_u *funcname;
4963 pos_T pos;
4964 int save_State = State;
4965 callback_T *cb;
4966
4967 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4968 // length as a string
4969 funcname = get_complete_funcname(ctrl_x_mode);
4970 if (*funcname == NUL)
4971 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004972 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004973 ? "completefunc" : "omnifunc");
4974 return FAIL;
4975 }
4976
4977 args[0].v_type = VAR_NUMBER;
4978 args[0].vval.v_number = 1;
4979 args[1].v_type = VAR_STRING;
4980 args[1].vval.v_string = (char_u *)"";
4981 args[2].v_type = VAR_UNKNOWN;
4982 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004983 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004984 cb = get_insert_callback(ctrl_x_mode);
4985 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004986 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004987
4988 State = save_State;
4989 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004990 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004991 validate_cursor();
4992 if (!EQUAL_POS(curwin->w_cursor, pos))
4993 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004994 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004995 return FAIL;
4996 }
4997
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004998 // Return value -2 means the user complete function wants to cancel the
4999 // complete without an error, do the same if the function did not execute
5000 // successfully.
5001 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005002 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005003 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005004 if (col == -3)
5005 {
5006 ctrl_x_mode = CTRL_X_NORMAL;
5007 edit_submode = NULL;
5008 if (!shortmess(SHM_COMPLETIONMENU))
5009 msg_clr_cmdline();
5010 return FAIL;
5011 }
5012
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005013 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005014 // completion.
5015 compl_opt_refresh_always = FALSE;
5016 compl_opt_suppress_empty = FALSE;
5017
5018 if (col < 0)
5019 col = curs_col;
5020 compl_col = col;
5021 if (compl_col > curs_col)
5022 compl_col = curs_col;
5023
5024 // Setup variables for completion. Need to obtain "line" again,
5025 // it may have become invalid.
5026 line = ml_get(curwin->w_cursor.lnum);
5027 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005028 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5029 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005030 {
John Marriott5e6ea922024-11-23 14:01:57 +01005031 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005032 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005033 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005034
John Marriott5e6ea922024-11-23 14:01:57 +01005035 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005036 ret = OK;
5037#endif
5038
5039 return ret;
5040}
5041
5042/*
5043 * Get the pattern, column and length for spell completion.
5044 * Sets the global variables: compl_col, compl_length and compl_pattern.
5045 * Uses the global variable: spell_bad_len
5046 */
5047 static int
5048get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5049{
5050 int ret = FAIL;
5051#ifdef FEAT_SPELL
5052 char_u *line;
5053
5054 if (spell_bad_len > 0)
5055 compl_col = curs_col - spell_bad_len;
5056 else
5057 compl_col = spell_word_start(startcol);
5058 if (compl_col >= (colnr_T)startcol)
5059 {
5060 compl_length = 0;
5061 compl_col = curs_col;
5062 }
5063 else
5064 {
5065 spell_expand_check_cap(compl_col);
5066 compl_length = (int)curs_col - compl_col;
5067 }
5068 // Need to obtain "line" again, it may have become invalid.
5069 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005070 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5071 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005072 {
John Marriott5e6ea922024-11-23 14:01:57 +01005073 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005074 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005075 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005076
John Marriott5e6ea922024-11-23 14:01:57 +01005077 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005078 ret = OK;
5079#endif
5080
5081 return ret;
5082}
5083
5084/*
5085 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005086 * "startcol" - start column number of the completion pattern/text
5087 * "cur_col" - current cursor column
5088 * On return, "line_invalid" is set to TRUE, if the current line may have
5089 * become invalid and needs to be fetched again.
5090 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005091 */
5092 static int
5093compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5094{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005095 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005096 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5097 && !thesaurus_func_complete(ctrl_x_mode)))
5098 {
5099 return get_normal_compl_info(line, startcol, curs_col);
5100 }
5101 else if (ctrl_x_mode_line_or_eval())
5102 {
5103 return get_wholeline_compl_info(line, curs_col);
5104 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005105 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005106 {
5107 return get_filename_compl_info(line, startcol, curs_col);
5108 }
5109 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5110 {
5111 return get_cmdline_compl_info(line, curs_col);
5112 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005113 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005114 || thesaurus_func_complete(ctrl_x_mode))
5115 {
5116 if (get_userdefined_compl_info(curs_col) == FAIL)
5117 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005118 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005119 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005120 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005121 {
5122 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5123 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005124 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005125 }
5126 else
5127 {
5128 internal_error("ins_complete()");
5129 return FAIL;
5130 }
5131
5132 return OK;
5133}
5134
5135/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005136 * Continue an interrupted completion mode search in "line".
5137 *
5138 * If this same ctrl_x_mode has been interrupted use the text from
5139 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5140 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5141 * the same line as the cursor then fix it (the line has been split because it
5142 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5143 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005144 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005145 static void
5146ins_compl_continue_search(char_u *line)
5147{
5148 // it is a continued search
5149 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005150 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5151 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005152 {
5153 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5154 {
5155 // line (probably) wrapped, set compl_startpos to the
5156 // first non_blank in the line, if it is not a wordchar
5157 // include it to get a better pattern, but then we don't
5158 // want the "\\<" prefix, check it below
5159 compl_col = (colnr_T)getwhitecols(line);
5160 compl_startpos.col = compl_col;
5161 compl_startpos.lnum = curwin->w_cursor.lnum;
5162 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5163 }
5164 else
5165 {
5166 // S_IPOS was set when we inserted a word that was at the
5167 // beginning of the line, which means that we'll go to SOL
5168 // mode but first we need to redefine compl_startpos
5169 if (compl_cont_status & CONT_S_IPOS)
5170 {
5171 compl_cont_status |= CONT_SOL;
5172 compl_startpos.col = (colnr_T)(skipwhite(
5173 line + compl_length
5174 + compl_startpos.col) - line);
5175 }
5176 compl_col = compl_startpos.col;
5177 }
5178 compl_length = curwin->w_cursor.col - (int)compl_col;
5179 // IObuff is used to add a "word from the next line" would we
5180 // have enough space? just being paranoid
5181#define MIN_SPACE 75
5182 if (compl_length > (IOSIZE - MIN_SPACE))
5183 {
5184 compl_cont_status &= ~CONT_SOL;
5185 compl_length = (IOSIZE - MIN_SPACE);
5186 compl_col = curwin->w_cursor.col - compl_length;
5187 }
5188 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5189 if (compl_length < 1)
5190 compl_cont_status &= CONT_LOCAL;
5191 }
5192 else if (ctrl_x_mode_line_or_eval())
5193 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5194 else
5195 compl_cont_status = 0;
5196}
5197
5198/*
5199 * start insert mode completion
5200 */
5201 static int
5202ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005203{
5204 char_u *line;
5205 int startcol = 0; // column where searched text starts
5206 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005207 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005208 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005209 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005210
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005211 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005212
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005213 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005214 did_si = FALSE;
5215 can_si = FALSE;
5216 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005217 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005218 return FAIL;
5219
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005220 line = ml_get(curwin->w_cursor.lnum);
5221 curs_col = curwin->w_cursor.col;
5222 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005223
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005224 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5225 && compl_cont_mode == ctrl_x_mode)
5226 // this same ctrl-x_mode was interrupted previously. Continue the
5227 // completion.
5228 ins_compl_continue_search(line);
5229 else
5230 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005231
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005232 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005233 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005234 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005235 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005236 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5237 compl_cont_status = 0;
5238 compl_cont_status |= CONT_N_ADDS;
5239 compl_startpos = curwin->w_cursor;
5240 startcol = (int)curs_col;
5241 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005242 }
5243
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005244 // Work out completion pattern and original text -- webb
5245 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5246 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005247 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5248 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005249 // restore did_ai, so that adding comment leader works
5250 did_ai = save_did_ai;
5251 return FAIL;
5252 }
5253 // If "line" was changed while getting completion info get it again.
5254 if (line_invalid)
5255 line = ml_get(curwin->w_cursor.lnum);
5256
glepnir7cfe6932024-09-15 20:06:28 +02005257 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005258 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005259 {
5260 edit_submode_pre = (char_u *)_(" Adding");
5261 if (ctrl_x_mode_line_or_eval())
5262 {
5263 // Insert a new line, keep indentation but ignore 'comments'.
5264 char_u *old = curbuf->b_p_com;
5265
5266 curbuf->b_p_com = (char_u *)"";
5267 compl_startpos.lnum = curwin->w_cursor.lnum;
5268 compl_startpos.col = compl_col;
5269 ins_eol('\r');
5270 curbuf->b_p_com = old;
5271 compl_length = 0;
5272 compl_col = curwin->w_cursor.col;
5273 }
glepnir7cfe6932024-09-15 20:06:28 +02005274 else if (ctrl_x_mode_normal() && in_fuzzy)
5275 {
5276 compl_startpos = curwin->w_cursor;
5277 compl_cont_status &= CONT_S_IPOS;
5278 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005279 }
5280 else
5281 {
5282 edit_submode_pre = NULL;
5283 compl_startpos.col = compl_col;
5284 }
5285
5286 if (compl_cont_status & CONT_LOCAL)
5287 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5288 else
5289 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5290
5291 // If any of the original typed text has been changed we need to fix
5292 // the redo buffer.
5293 ins_compl_fixRedoBufForLeader(NULL);
5294
5295 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005296 VIM_CLEAR_STRING(compl_orig_text);
5297 compl_orig_text.length = (size_t)compl_length;
5298 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005299 if (p_ic)
5300 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005301 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5302 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005303 {
John Marriott5e6ea922024-11-23 14:01:57 +01005304 VIM_CLEAR_STRING(compl_pattern);
5305 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005306 return FAIL;
5307 }
5308
5309 // showmode might reset the internal line pointers, so it must
5310 // be called before line = ml_get(), or when this address is no
5311 // longer needed. -- Acevedo.
5312 edit_submode_extra = (char_u *)_("-- Searching...");
5313 edit_submode_highl = HLF_COUNT;
5314 showmode();
5315 edit_submode_extra = NULL;
5316 out_flush();
5317
5318 return OK;
5319}
5320
5321/*
5322 * display the completion status message
5323 */
5324 static void
5325ins_compl_show_statusmsg(void)
5326{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005327 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005328 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005329 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005330 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005331 ? (char_u *)_("Hit end of paragraph")
5332 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005333 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005334 }
5335
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005336 if (edit_submode_extra == NULL)
5337 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005338 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005339 {
5340 edit_submode_extra = (char_u *)_("Back at original");
5341 edit_submode_highl = HLF_W;
5342 }
5343 else if (compl_cont_status & CONT_S_IPOS)
5344 {
5345 edit_submode_extra = (char_u *)_("Word from other line");
5346 edit_submode_highl = HLF_COUNT;
5347 }
5348 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5349 {
5350 edit_submode_extra = (char_u *)_("The only match");
5351 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005352 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005353 }
5354 else
5355 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005356#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005357 // Update completion sequence number when needed.
5358 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005359 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005360#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005361 // The match should always have a sequence number now, this is
5362 // just a safety check.
5363 if (compl_curr_match->cp_number != -1)
5364 {
5365 // Space for 10 text chars. + 2x10-digit no.s = 31.
5366 // Translations may need more than twice that.
5367 static char_u match_ref[81];
5368
5369 if (compl_matches > 0)
5370 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005371 _("match %d of %d"),
5372 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005373 else
5374 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005375 _("match %d"),
5376 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005377 edit_submode_extra = match_ref;
5378 edit_submode_highl = HLF_R;
5379 if (dollar_vcol >= 0)
5380 curs_columns(FALSE);
5381 }
5382 }
5383 }
5384
5385 // Show a message about what (completion) mode we're in.
5386 if (!compl_opt_suppress_empty)
5387 {
5388 showmode();
5389 if (!shortmess(SHM_COMPLETIONMENU))
5390 {
5391 if (edit_submode_extra != NULL)
5392 {
5393 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005394 {
5395 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005396 msg_attr((char *)edit_submode_extra,
5397 edit_submode_highl < HLF_COUNT
5398 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005399 msg_hist_off = FALSE;
5400 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005401 }
5402 else
5403 msg_clr_cmdline(); // necessary for "noshowmode"
5404 }
5405 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005406}
5407
5408/*
5409 * Do Insert mode completion.
5410 * Called when character "c" was typed, which has a meaning for completion.
5411 * Returns OK if completion was done, FAIL if something failed (out of mem).
5412 */
5413 int
5414ins_complete(int c, int enable_pum)
5415{
5416 int n;
5417 int save_w_wrow;
5418 int save_w_leftcol;
5419 int insert_match;
5420
5421 compl_direction = ins_compl_key2dir(c);
5422 insert_match = ins_compl_use_match(c);
5423
5424 if (!compl_started)
5425 {
5426 if (ins_compl_start() == FAIL)
5427 return FAIL;
5428 }
5429 else if (insert_match && stop_arrow() == FAIL)
5430 return FAIL;
5431
5432 compl_shown_match = compl_curr_match;
5433 compl_shows_dir = compl_direction;
5434
5435 // Find next match (and following matches).
5436 save_w_wrow = curwin->w_wrow;
5437 save_w_leftcol = curwin->w_leftcol;
5438 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5439
5440 // may undisplay the popup menu
5441 ins_compl_upd_pum();
5442
5443 if (n > 1) // all matches have been found
5444 compl_matches = n;
5445 compl_curr_match = compl_shown_match;
5446 compl_direction = compl_shows_dir;
5447
5448 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5449 // mode.
5450 if (got_int && !global_busy)
5451 {
5452 (void)vgetc();
5453 got_int = FALSE;
5454 }
5455
5456 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005457 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005458 {
5459 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5460 // because we couldn't expand anything at first place, but if we used
5461 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5462 // (such as M in M'exico) if not tried already. -- Acevedo
5463 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005464 || compl_status_adding()
5465 || (ctrl_x_mode_not_default()
5466 && !ctrl_x_mode_path_patterns()
5467 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005468 compl_cont_status &= ~CONT_N_ADDS;
5469 }
5470
5471 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5472 compl_cont_status |= CONT_S_IPOS;
5473 else
5474 compl_cont_status &= ~CONT_S_IPOS;
5475
5476 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005477
5478 // Show the popup menu, unless we got interrupted.
5479 if (enable_pum && !compl_interrupted)
5480 show_pum(save_w_wrow, save_w_leftcol);
5481
5482 compl_was_interrupted = compl_interrupted;
5483 compl_interrupted = FALSE;
5484
5485 return OK;
5486}
5487
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005488/*
5489 * Remove (if needed) and show the popup menu
5490 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005491 static void
5492show_pum(int prev_w_wrow, int prev_w_leftcol)
5493{
5494 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005495 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005496 RedrawingDisabled = 0;
5497
5498 // If the cursor moved or the display scrolled we need to remove the pum
5499 // first.
5500 setcursor();
5501 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5502 ins_compl_del_pum();
5503
5504 ins_compl_show_pum();
5505 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005506
5507 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005508}
5509
5510/*
5511 * Looks in the first "len" chars. of "src" for search-metachars.
5512 * If dest is not NULL the chars. are copied there quoting (with
5513 * a backslash) the metachars, and dest would be NUL terminated.
5514 * Returns the length (needed) of dest
5515 */
5516 static unsigned
5517quote_meta(char_u *dest, char_u *src, int len)
5518{
5519 unsigned m = (unsigned)len + 1; // one extra for the NUL
5520
5521 for ( ; --len >= 0; src++)
5522 {
5523 switch (*src)
5524 {
5525 case '.':
5526 case '*':
5527 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005528 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005529 break;
5530 // FALLTHROUGH
5531 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005532 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005533 break;
5534 // FALLTHROUGH
5535 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005536 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005537 break;
5538 // FALLTHROUGH
5539 case '^': // currently it's not needed.
5540 case '$':
5541 m++;
5542 if (dest != NULL)
5543 *dest++ = '\\';
5544 break;
5545 }
5546 if (dest != NULL)
5547 *dest++ = *src;
5548 // Copy remaining bytes of a multibyte character.
5549 if (has_mbyte)
5550 {
5551 int i, mb_len;
5552
5553 mb_len = (*mb_ptr2len)(src) - 1;
5554 if (mb_len > 0 && len >= mb_len)
5555 for (i = 0; i < mb_len; ++i)
5556 {
5557 --len;
5558 ++src;
5559 if (dest != NULL)
5560 *dest++ = *src;
5561 }
5562 }
5563 }
5564 if (dest != NULL)
5565 *dest = NUL;
5566
5567 return m;
5568}
5569
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005570#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005571 void
5572free_insexpand_stuff(void)
5573{
John Marriott5e6ea922024-11-23 14:01:57 +01005574 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005575# ifdef FEAT_EVAL
5576 free_callback(&cfu_cb);
5577 free_callback(&ofu_cb);
5578 free_callback(&tsrfu_cb);
5579# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005580}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005581#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005582
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005583#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005584/*
5585 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5586 * spelled word, if there is one.
5587 */
5588 static void
5589spell_back_to_badword(void)
5590{
5591 pos_T tpos = curwin->w_cursor;
5592
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005593 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005594 if (curwin->w_cursor.col != tpos.col)
5595 start_arrow(&tpos);
5596}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005597#endif