blob: 305511cd8ccc4a831fe741ad3ff64b376ee641c1 [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020061 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010062 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010091 * Structure used to store one match for insert completion.
92 */
93typedef struct compl_S compl_T;
94struct compl_S
95{
96 compl_T *cp_next;
97 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +010098 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +010099 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200100 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100101#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100102 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100103#endif
glepnir0fe17f82024-10-08 22:26:44 +0200104 char_u *cp_fname; // file containing the match, allocated when
105 // cp_flags has CP_FREE_FNAME
106 int cp_flags; // CP_ values
107 int cp_number; // sequence number
108 int cp_score; // fuzzy match score
glepnir7baa0142024-10-09 20:19:25 +0200109 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200110 int cp_user_kind_hlattr; // highlight attribute for kind
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100111};
112
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113// values for cp_flags
114# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
115# define CP_FREE_FNAME 2 // cp_fname is allocated
116# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
117# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
118# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200119# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100120
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100121/*
122 * All the current matches are stored in a list.
123 * "compl_first_match" points to the start of the list.
124 * "compl_curr_match" points to the currently selected entry.
125 * "compl_shown_match" is different from compl_curr_match during
126 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000127 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100128 */
129static compl_T *compl_first_match = NULL;
130static compl_T *compl_curr_match = NULL;
131static compl_T *compl_shown_match = NULL;
132static compl_T *compl_old_match = NULL;
133
134// After using a cursor key <Enter> selects a match in the popup menu,
135// otherwise it inserts a line break.
136static int compl_enter_selects = FALSE;
137
138// When "compl_leader" is not NULL only matches that start with this string
139// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100140static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100141
142static int compl_get_longest = FALSE; // put longest common string
143 // in compl_leader
144
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100145// Selected one of the matches. When FALSE the match was edited or using the
146// longest common string.
147static int compl_used_match;
148
149// didn't finish finding completions.
150static int compl_was_interrupted = FALSE;
151
152// Set when character typed while looking for matches and it means we should
153// stop looking for matches.
154static int compl_interrupted = FALSE;
155
156static int compl_restarting = FALSE; // don't insert match
157
158// When the first completion is done "compl_started" is set. When it's
159// FALSE the word to be completed must be located.
160static int compl_started = FALSE;
161
162// Which Ctrl-X mode are we in?
163static int ctrl_x_mode = CTRL_X_NORMAL;
164
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000165static int compl_matches = 0; // number of completion matches
John Marriott5e6ea922024-11-23 14:01:57 +0100166static string_T compl_pattern = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100167static int compl_direction = FORWARD;
168static int compl_shows_dir = FORWARD;
169static int compl_pending = 0; // > 1 for postponed CTRL-N
170static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000171// Length in bytes of the text being completed (this is deleted to be replaced
172// by the match.)
173static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100174static colnr_T compl_col = 0; // column where the text starts
175 // that is being completed
John Marriott5e6ea922024-11-23 14:01:57 +0100176static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100177 // completion started
178static int compl_cont_mode = 0;
179static expand_T compl_xp;
180
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000181// List of flags for method of completion.
182static int compl_cont_status = 0;
183# define CONT_ADDING 1 // "normal" or "adding" expansion
184# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
185 // it's set only iff N_ADDS is set
186# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
187# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
188 // if so, word-wise-expansion will set SOL
189# define CONT_SOL 16 // pattern includes start of line, just for
190 // word-wise expansion, not set for ^X^L
191# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
192 // expansion, (eg use complete=.)
193
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100194static int compl_opt_refresh_always = FALSE;
195static int compl_opt_suppress_empty = FALSE;
196
glepnira218cc62024-06-03 19:32:39 +0200197static int compl_selected_item = -1;
198
glepnir8159fb12024-07-17 20:32:54 +0200199static int *compl_fuzzy_scores;
200
glepnir80b66202024-11-27 21:53:53 +0100201static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup, int *user_hl);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100202static void ins_compl_longest_match(compl_T *match);
203static void ins_compl_del_pum(void);
204static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
205static char_u *find_line_end(char_u *ptr);
206static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100207static int ins_compl_need_restart(void);
208static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000209static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100210static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100211static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100212static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
213# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
214static void ins_compl_add_list(list_T *list);
215static void ins_compl_add_dict(dict_T *dict);
216# endif
217static int ins_compl_key2dir(int c);
218static int ins_compl_pum_key(int c);
219static int ins_compl_key2count(int c);
220static void show_pum(int prev_w_wrow, int prev_w_leftcol);
221static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100222
223#ifdef FEAT_SPELL
224static void spell_back_to_badword(void);
225static int spell_bad_len = 0; // length of located bad word
226#endif
227
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100228/*
229 * CTRL-X pressed in Insert mode.
230 */
231 void
232ins_ctrl_x(void)
233{
zeertzjqdca29d92021-08-31 19:12:51 +0200234 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100235 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000236 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100237 if (compl_cont_status & CONT_N_ADDS)
238 compl_cont_status |= CONT_INTRPT;
239 else
240 compl_cont_status = 0;
241 // We're not sure which CTRL-X mode it will be yet
242 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
243 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
244 edit_submode_pre = NULL;
245 showmode();
246 }
zeertzjqdca29d92021-08-31 19:12:51 +0200247 else
248 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
249 // CTRL-V look like CTRL-N
250 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100251
LemonBoy2bf52dd2022-04-09 18:17:34 +0100252 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100253}
254
255/*
256 * Functions to check the current CTRL-X mode.
257 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000258int ctrl_x_mode_none(void)
259 { return ctrl_x_mode == 0; }
260int ctrl_x_mode_normal(void)
261 { return ctrl_x_mode == CTRL_X_NORMAL; }
262int ctrl_x_mode_scroll(void)
263 { return ctrl_x_mode == CTRL_X_SCROLL; }
264int ctrl_x_mode_whole_line(void)
265 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
266int ctrl_x_mode_files(void)
267 { return ctrl_x_mode == CTRL_X_FILES; }
268int ctrl_x_mode_tags(void)
269 { return ctrl_x_mode == CTRL_X_TAGS; }
270int ctrl_x_mode_path_patterns(void)
271 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
272int ctrl_x_mode_path_defines(void)
273 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
274int ctrl_x_mode_dictionary(void)
275 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
276int ctrl_x_mode_thesaurus(void)
277 { return ctrl_x_mode == CTRL_X_THESAURUS; }
278int ctrl_x_mode_cmdline(void)
279 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200280 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000281int ctrl_x_mode_function(void)
282 { return ctrl_x_mode == CTRL_X_FUNCTION; }
283int ctrl_x_mode_omni(void)
284 { return ctrl_x_mode == CTRL_X_OMNI; }
285int ctrl_x_mode_spell(void)
286 { return ctrl_x_mode == CTRL_X_SPELL; }
287static int ctrl_x_mode_eval(void)
288 { return ctrl_x_mode == CTRL_X_EVAL; }
289int ctrl_x_mode_line_or_eval(void)
290 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100291
292/*
293 * Whether other than default completion has been selected.
294 */
295 int
296ctrl_x_mode_not_default(void)
297{
298 return ctrl_x_mode != CTRL_X_NORMAL;
299}
300
301/*
zeertzjqdca29d92021-08-31 19:12:51 +0200302 * Whether CTRL-X was typed without a following character,
303 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100304 */
305 int
306ctrl_x_mode_not_defined_yet(void)
307{
308 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
309}
310
311/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000312 * Return TRUE if currently in "normal" or "adding" insert completion matches
313 * state
314 */
315 int
316compl_status_adding(void)
317{
318 return compl_cont_status & CONT_ADDING;
319}
320
321/*
322 * Return TRUE if the completion pattern includes start of line, just for
323 * word-wise expansion.
324 */
325 int
326compl_status_sol(void)
327{
328 return compl_cont_status & CONT_SOL;
329}
330
331/*
332 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
333 */
334 int
335compl_status_local(void)
336{
337 return compl_cont_status & CONT_LOCAL;
338}
339
340/*
341 * Clear the completion status flags
342 */
343 void
344compl_status_clear(void)
345{
346 compl_cont_status = 0;
347}
348
349/*
350 * Return TRUE if completion is using the forward direction matches
351 */
352 static int
353compl_dir_forward(void)
354{
355 return compl_direction == FORWARD;
356}
357
358/*
359 * Return TRUE if currently showing forward completion matches
360 */
361 static int
362compl_shows_dir_forward(void)
363{
364 return compl_shows_dir == FORWARD;
365}
366
367/*
368 * Return TRUE if currently showing backward completion matches
369 */
370 static int
371compl_shows_dir_backward(void)
372{
373 return compl_shows_dir == BACKWARD;
374}
375
376/*
377 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100378 */
379 int
380has_compl_option(int dict_opt)
381{
382 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200383#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100384 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200385#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100386 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100387 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
388#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100389 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100390#endif
391 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100392 {
393 ctrl_x_mode = CTRL_X_NORMAL;
394 edit_submode = NULL;
395 msg_attr(dict_opt ? _("'dictionary' option is empty")
396 : _("'thesaurus' option is empty"),
397 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100398 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100399 {
400 vim_beep(BO_COMPL);
401 setcursor();
402 out_flush();
403#ifdef FEAT_EVAL
404 if (!get_vim_var_nr(VV_TESTING))
405#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100406 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100407 }
408 return FALSE;
409 }
410 return TRUE;
411}
412
413/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000414 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100415 * This depends on the current mode.
416 */
417 int
418vim_is_ctrl_x_key(int c)
419{
420 // Always allow ^R - let its results then be checked
421 if (c == Ctrl_R)
422 return TRUE;
423
424 // Accept <PageUp> and <PageDown> if the popup menu is visible.
425 if (ins_compl_pum_key(c))
426 return TRUE;
427
428 switch (ctrl_x_mode)
429 {
430 case 0: // Not in any CTRL-X mode
431 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
432 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200433 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
435 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
436 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
437 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
438 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200439 || c == Ctrl_S || c == Ctrl_K || c == 's'
440 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100441 case CTRL_X_SCROLL:
442 return (c == Ctrl_Y || c == Ctrl_E);
443 case CTRL_X_WHOLE_LINE:
444 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
445 case CTRL_X_FILES:
446 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
447 case CTRL_X_DICTIONARY:
448 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
449 case CTRL_X_THESAURUS:
450 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
451 case CTRL_X_TAGS:
452 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
453#ifdef FEAT_FIND_ID
454 case CTRL_X_PATH_PATTERNS:
455 return (c == Ctrl_P || c == Ctrl_N);
456 case CTRL_X_PATH_DEFINES:
457 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
458#endif
459 case CTRL_X_CMDLINE:
460 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
461 || c == Ctrl_X);
462#ifdef FEAT_COMPL_FUNC
463 case CTRL_X_FUNCTION:
464 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
465 case CTRL_X_OMNI:
466 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
467#endif
468 case CTRL_X_SPELL:
469 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
470 case CTRL_X_EVAL:
471 return (c == Ctrl_P || c == Ctrl_N);
472 }
473 internal_error("vim_is_ctrl_x_key()");
474 return FALSE;
475}
476
477/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000478 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000479 */
480 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000481match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000482{
483 return match->cp_flags & CP_ORIGINAL_TEXT;
484}
485
486/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000487 * Returns TRUE if "match" is the first match in the completion list.
488 */
489 static int
490is_first_match(compl_T *match)
491{
492 return match == compl_first_match;
493}
494
495/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100496 * Return TRUE when character "c" is part of the item currently being
497 * completed. Used to decide whether to abandon complete mode when the menu
498 * is visible.
499 */
500 int
501ins_compl_accept_char(int c)
502{
503 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
504 // When expanding an identifier only accept identifier chars.
505 return vim_isIDc(c);
506
507 switch (ctrl_x_mode)
508 {
509 case CTRL_X_FILES:
510 // When expanding file name only accept file name chars. But not
511 // path separators, so that "proto/<Tab>" expands files in
512 // "proto", not "proto/" as a whole
513 return vim_isfilec(c) && !vim_ispathsep(c);
514
515 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200516 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100517 case CTRL_X_OMNI:
518 // Command line and Omni completion can work with just about any
519 // printable character, but do stop at white space.
520 return vim_isprintc(c) && !VIM_ISWHITE(c);
521
522 case CTRL_X_WHOLE_LINE:
523 // For while line completion a space can be part of the line.
524 return vim_isprintc(c);
525 }
526 return vim_iswordc(c);
527}
528
529/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000530 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100531 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000532 */
533 static char_u *
534ins_compl_infercase_gettext(
535 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100536 int char_len,
537 int compl_char_len,
538 int min_len,
539 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000540{
541 int *wca; // Wide character array.
542 char_u *p;
543 int i, c;
544 int has_lower = FALSE;
545 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100546 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000547
548 IObuff[0] = NUL;
549
550 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100551 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000552 if (wca == NULL)
553 return IObuff;
554
555 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100556 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000557 if (has_mbyte)
558 wca[i] = mb_ptr2char_adv(&p);
559 else
560 wca[i] = *(p++);
561
562 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100563 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000564 for (i = 0; i < min_len; ++i)
565 {
566 if (has_mbyte)
567 c = mb_ptr2char_adv(&p);
568 else
569 c = *(p++);
570 if (MB_ISLOWER(c))
571 {
572 has_lower = TRUE;
573 if (MB_ISUPPER(wca[i]))
574 {
575 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100576 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000577 wca[i] = MB_TOLOWER(wca[i]);
578 break;
579 }
580 }
581 }
582
583 // Rule 2: No lower case, 2nd consecutive letter converted to
584 // upper case.
585 if (!has_lower)
586 {
John Marriott5e6ea922024-11-23 14:01:57 +0100587 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000588 for (i = 0; i < min_len; ++i)
589 {
590 if (has_mbyte)
591 c = mb_ptr2char_adv(&p);
592 else
593 c = *(p++);
594 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
595 {
596 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100597 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000598 wca[i] = MB_TOUPPER(wca[i]);
599 break;
600 }
601 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
602 }
603 }
604
605 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100606 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000607 for (i = 0; i < min_len; ++i)
608 {
609 if (has_mbyte)
610 c = mb_ptr2char_adv(&p);
611 else
612 c = *(p++);
613 if (MB_ISLOWER(c))
614 wca[i] = MB_TOLOWER(wca[i]);
615 else if (MB_ISUPPER(c))
616 wca[i] = MB_TOUPPER(wca[i]);
617 }
618
619 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000620 p = IObuff;
621 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100622 ga_init2(&gap, 1, 500);
623 while (i < char_len)
624 {
625 if (gap.ga_data != NULL)
626 {
627 if (ga_grow(&gap, 10) == FAIL)
628 {
629 ga_clear(&gap);
630 return (char_u *)"[failed]";
631 }
632 p = (char_u *)gap.ga_data + gap.ga_len;
633 if (has_mbyte)
634 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
635 else
636 {
637 *p = wca[i++];
638 ++gap.ga_len;
639 }
640 }
641 else if ((p - IObuff) + 6 >= IOSIZE)
642 {
643 // Multi-byte characters can occupy up to five bytes more than
644 // ASCII characters, and we also need one byte for NUL, so when
645 // getting to six bytes from the edge of IObuff switch to using a
646 // growarray. Add the character in the next round.
647 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100648 {
649 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100650 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100651 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100652 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100653 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100654 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100655 }
656 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000657 p += (*mb_char2bytes)(wca[i++], p);
658 else
659 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100660 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000661 vim_free(wca);
662
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100663 if (gap.ga_data != NULL)
664 {
665 *tofree = gap.ga_data;
666 return gap.ga_data;
667 }
668
669 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000670 return IObuff;
671}
672
673/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100674 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
675 * case of the originally typed text is used, and the case of the completed
676 * text is inferred, ie this tries to work out what case you probably wanted
677 * the rest of the word to be in -- webb
678 */
679 int
680ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200681 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100682 int len,
683 int icase,
684 char_u *fname,
685 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200686 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100687{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200688 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100689 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100690 int char_len; // count multi-byte characters
691 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200693 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100694 int res;
695 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100696
697 if (p_ic && curbuf->b_p_inf && len > 0)
698 {
699 // Infer case of completed part.
700
701 // Find actual length of completion.
702 if (has_mbyte)
703 {
704 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100705 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100706 while (*p != NUL)
707 {
708 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100709 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100710 }
711 }
712 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100713 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100714
715 // Find actual length of original text.
716 if (has_mbyte)
717 {
John Marriott5e6ea922024-11-23 14:01:57 +0100718 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100719 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100720 while (*p != NUL)
721 {
722 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100723 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100724 }
725 }
726 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100727 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100728
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100729 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100730 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100731 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100732
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100733 str = ins_compl_infercase_gettext(str, char_len,
734 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200736 if (cont_s_ipos)
737 flags |= CP_CONT_S_IPOS;
738 if (icase)
739 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200740
glepnir5c66e232024-11-15 19:58:27 +0100741 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100742 vim_free(tofree);
743 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100744}
745
746/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000747 * Add a match to the list of matches. The arguments are:
748 * str - text of the match to add
749 * len - length of "str". If -1, then the length of "str" is
750 * computed.
751 * fname - file name to associate with this match.
752 * cptext - list of strings to use with this match (for abbr, menu, info
753 * and kind)
754 * user_data - user supplied data (any vim type) for this match
755 * cdir - match direction. If 0, use "compl_direction".
756 * flags_arg - match flags (cp_flags)
757 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100758 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000759 * If "cdir" is FORWARD, then the match is added after the current match.
760 * Otherwise, it is added before the current match.
761 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762 * If the given string is already in the list of completions, then return
763 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
764 * maybe because alloc() returns NULL, then FAIL is returned.
765 */
766 static int
767ins_compl_add(
768 char_u *str,
769 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100770 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100771 char_u **cptext, // extra text for popup menu or NULL
772 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100773 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200774 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200775 int adup, // accept duplicate match
glepnir80b66202024-11-27 21:53:53 +0100776 int *user_hl) // user abbr/kind hlattr
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777{
778 compl_T *match;
779 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200780 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100781
Bram Moolenaarceb06192021-04-04 15:05:22 +0200782 if (flags & CP_FAST)
783 fast_breakcheck();
784 else
785 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100786 if (got_int)
787 return FAIL;
788 if (len < 0)
789 len = (int)STRLEN(str);
790
791 // If the same match is already present, don't add it.
792 if (compl_first_match != NULL && !adup)
793 {
794 match = compl_first_match;
795 do
796 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000797 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100798 && STRNCMP(match->cp_str.string, str, len) == 0
799 && ((int)match->cp_str.length <= len
800 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100801 return NOTDONE;
802 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000803 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100804 }
805
806 // Remove any popup menu before changing the list of matches.
807 ins_compl_del_pum();
808
809 // Allocate a new match structure.
810 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200811 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100812 if (match == NULL)
813 return FAIL;
814 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200815 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100816 match->cp_number = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100817 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100818 {
819 vim_free(match);
820 return FAIL;
821 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100822
John Marriott5e6ea922024-11-23 14:01:57 +0100823 match->cp_str.length = len;
824
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100825 // match-fname is:
826 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200827 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100828 // - NULL otherwise. --Acevedo
829 if (fname != NULL
830 && compl_curr_match != NULL
831 && compl_curr_match->cp_fname != NULL
832 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
833 match->cp_fname = compl_curr_match->cp_fname;
834 else if (fname != NULL)
835 {
836 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200837 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100838 }
839 else
840 match->cp_fname = NULL;
841 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100842 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
843 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100844
845 if (cptext != NULL)
846 {
847 int i;
848
849 for (i = 0; i < CPT_COUNT; ++i)
850 if (cptext[i] != NULL && *cptext[i] != NUL)
851 match->cp_text[i] = vim_strsave(cptext[i]);
852 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100853#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100854 if (user_data != NULL)
855 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100856#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100857
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000858 // Link the new match structure after (FORWARD) or before (BACKWARD) the
859 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100860 if (compl_first_match == NULL)
861 match->cp_next = match->cp_prev = NULL;
862 else if (dir == FORWARD)
863 {
864 match->cp_next = compl_curr_match->cp_next;
865 match->cp_prev = compl_curr_match;
866 }
867 else // BACKWARD
868 {
869 match->cp_next = compl_curr_match;
870 match->cp_prev = compl_curr_match->cp_prev;
871 }
872 if (match->cp_next)
873 match->cp_next->cp_prev = match;
874 if (match->cp_prev)
875 match->cp_prev->cp_next = match;
876 else // if there's nothing before, it is the first match
877 compl_first_match = match;
878 compl_curr_match = match;
879
880 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200881 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100882 ins_compl_longest_match(match);
883
884 return OK;
885}
886
887/*
888 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200889 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100890 */
891 static int
892ins_compl_equal(compl_T *match, char_u *str, int len)
893{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200894 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200895 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200896 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100897 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
898 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100899}
900
901/*
902 * Reduce the longest common string for match "match".
903 */
904 static void
905ins_compl_longest_match(compl_T *match)
906{
907 char_u *p, *s;
908 int c1, c2;
909 int had_match;
910
John Marriott5e6ea922024-11-23 14:01:57 +0100911 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100912 {
913 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +0100914 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
915 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000916 return;
917
John Marriott5e6ea922024-11-23 14:01:57 +0100918 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000919 had_match = (curwin->w_cursor.col > compl_col);
920 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +0100921 ins_bytes(compl_leader.string + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000922 ins_redraw(FALSE);
923
924 // When the match isn't there (to avoid matching itself) remove it
925 // again after redrawing.
926 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100927 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100928 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000929
930 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100931 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000932
933 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +0100934 p = compl_leader.string;
935 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000936 while (*p != NUL)
937 {
938 if (has_mbyte)
939 {
940 c1 = mb_ptr2char(p);
941 c2 = mb_ptr2char(s);
942 }
943 else
944 {
945 c1 = *p;
946 c2 = *s;
947 }
948 if ((match->cp_flags & CP_ICASE)
949 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
950 break;
951 if (has_mbyte)
952 {
953 MB_PTR_ADV(p);
954 MB_PTR_ADV(s);
955 }
956 else
957 {
958 ++p;
959 ++s;
960 }
961 }
962
963 if (*p != NUL)
964 {
965 // Leader was shortened, need to change the inserted text.
966 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +0100967 compl_leader.length = (size_t)(p - compl_leader.string);
968
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000969 had_match = (curwin->w_cursor.col > compl_col);
970 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +0100971 ins_bytes(compl_leader.string + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000972 ins_redraw(FALSE);
973
974 // When the match isn't there (to avoid matching itself) remove it
975 // again after redrawing.
976 if (!had_match)
977 ins_compl_delete();
978 }
979
980 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100981}
982
983/*
984 * Add an array of matches to the list of matches.
985 * Frees matches[].
986 */
987 static void
988ins_compl_add_matches(
989 int num_matches,
990 char_u **matches,
991 int icase)
992{
993 int i;
994 int add_r = OK;
995 int dir = compl_direction;
996
997 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100998 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnir5c66e232024-11-15 19:58:27 +0100999 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001000 // if dir was BACKWARD then honor it just once
1001 dir = FORWARD;
1002 FreeWild(num_matches, matches);
1003}
1004
1005/*
1006 * Make the completion list cyclic.
1007 * Return the number of matches (excluding the original).
1008 */
1009 static int
1010ins_compl_make_cyclic(void)
1011{
1012 compl_T *match;
1013 int count = 0;
1014
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001015 if (compl_first_match == NULL)
1016 return 0;
1017
1018 // Find the end of the list.
1019 match = compl_first_match;
1020 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001021 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001022 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001023 match = match->cp_next;
1024 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001025 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001026 match->cp_next = compl_first_match;
1027 compl_first_match->cp_prev = match;
1028
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001029 return count;
1030}
1031
1032/*
1033 * Return whether there currently is a shown match.
1034 */
1035 int
1036ins_compl_has_shown_match(void)
1037{
1038 return compl_shown_match == NULL
1039 || compl_shown_match != compl_shown_match->cp_next;
1040}
1041
1042/*
1043 * Return whether the shown match is long enough.
1044 */
1045 int
1046ins_compl_long_shown_match(void)
1047{
John Marriott5e6ea922024-11-23 14:01:57 +01001048 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001049 > curwin->w_cursor.col - compl_col;
1050}
1051
1052/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001053 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001054 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001055 unsigned int
1056get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001057{
zeertzjq529b9ad2024-06-05 20:27:06 +02001058 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001059}
1060
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001061
1062// "compl_match_array" points the currently displayed list of entries in the
1063// popup menu. It is NULL when there is no popup menu.
1064static pumitem_T *compl_match_array = NULL;
1065static int compl_match_arraysize;
1066
1067/*
1068 * Update the screen and when there is any scrolling remove the popup menu.
1069 */
1070 static void
1071ins_compl_upd_pum(void)
1072{
1073 int h;
1074
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001075 if (compl_match_array == NULL)
1076 return;
1077
1078 h = curwin->w_cline_height;
1079 // Update the screen later, before drawing the popup menu over it.
1080 pum_call_update_screen();
1081 if (h != curwin->w_cline_height)
1082 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001083}
1084
1085/*
1086 * Remove any popup menu.
1087 */
1088 static void
1089ins_compl_del_pum(void)
1090{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001091 if (compl_match_array == NULL)
1092 return;
1093
1094 pum_undisplay();
1095 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001096}
1097
1098/*
1099 * Return TRUE if the popup menu should be displayed.
1100 */
1101 int
1102pum_wanted(void)
1103{
1104 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001105 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001106 return FALSE;
1107
1108 // The display looks bad on a B&W display.
1109 if (t_colors < 8
1110#ifdef FEAT_GUI
1111 && !gui.in_use
1112#endif
1113 )
1114 return FALSE;
1115 return TRUE;
1116}
1117
1118/*
1119 * Return TRUE if there are two or more matches to be shown in the popup menu.
1120 * One if 'completopt' contains "menuone".
1121 */
1122 static int
1123pum_enough_matches(void)
1124{
1125 compl_T *compl;
1126 int i;
1127
1128 // Don't display the popup menu if there are no matches or there is only
1129 // one (ignoring the original text).
1130 compl = compl_first_match;
1131 i = 0;
1132 do
1133 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001134 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001135 break;
1136 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001137 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001138
zeertzjq529b9ad2024-06-05 20:27:06 +02001139 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001140 return (i >= 1);
1141 return (i >= 2);
1142}
1143
Bram Moolenaar3075a452021-11-17 15:51:52 +00001144#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001145/*
1146 * Allocate Dict for the completed item.
1147 * { word, abbr, menu, kind, info }
1148 */
1149 static dict_T *
1150ins_compl_dict_alloc(compl_T *match)
1151{
1152 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1153
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001154 if (dict == NULL)
1155 return NULL;
1156
John Marriott5e6ea922024-11-23 14:01:57 +01001157 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1159 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1160 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1161 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1162 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1163 dict_add_string(dict, "user_data", (char_u *)"");
1164 else
1165 dict_add_tv(dict, "user_data", &match->cp_user_data);
1166
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001167 return dict;
1168}
1169
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001170/*
1171 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1172 * completion menu is changed.
1173 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001174 static void
1175trigger_complete_changed_event(int cur)
1176{
1177 dict_T *v_event;
1178 dict_T *item;
1179 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001180 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001181
1182 if (recursive)
1183 return;
1184
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001185 if (cur < 0)
1186 item = dict_alloc();
1187 else
1188 item = ins_compl_dict_alloc(compl_curr_match);
1189 if (item == NULL)
1190 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001191 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001192 dict_add_dict(v_event, "completed_item", item);
1193 pum_set_event_info(v_event);
1194 dict_set_items_ro(v_event);
1195
1196 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001197 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001198 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001199 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001200 recursive = FALSE;
1201
Bram Moolenaar3075a452021-11-17 15:51:52 +00001202 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001203}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001204#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001205
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001206/*
glepnira218cc62024-06-03 19:32:39 +02001207 * pumitem qsort compare func
1208 */
1209 static int
zeertzjq8e567472024-06-14 20:04:42 +02001210ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001211{
1212 const int sa = (*(pumitem_T *)a).pum_score;
1213 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001214 const int ia = (*(pumitem_T *)a).pum_idx;
1215 const int ib = (*(pumitem_T *)b).pum_idx;
1216 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001217}
1218
1219/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001220 * Build a popup menu to show the completion matches.
1221 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1222 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001223 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001224 static int
1225ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001226{
1227 compl_T *compl;
1228 compl_T *shown_compl = NULL;
1229 int did_find_shown_match = FALSE;
1230 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001231 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001232 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001233 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001234 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001235 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1236 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepnir80b66202024-11-27 21:53:53 +01001237 compl_T *match_head = NULL;
1238 compl_T *match_tail = NULL;
1239 compl_T *match_next = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001240
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001241 // Need to build the popup menu list.
1242 compl_match_arraysize = 0;
1243 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001244
glepnira49c0772024-11-30 10:56:30 +01001245 // If the current match is the original text don't find the first
1246 // match after it, don't highlight anything.
1247 if (match_at_original_text(compl_shown_match))
1248 shown_match_ok = TRUE;
1249
1250 if (compl_leader.string != NULL
1251 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1252 && shown_match_ok == FALSE)
1253 compl_shown_match = compl_no_select ? compl_first_match
1254 : compl_first_match->cp_next;
1255
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001256 do
1257 {
zeertzjq551d8c32024-06-05 19:53:32 +02001258 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1259 // set the cp_score for later comparisons.
John Marriott5e6ea922024-11-23 14:01:57 +01001260 if (compl_fuzzy_match && compl_leader.string != NULL && compl_leader.length > 0)
1261 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001262
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001263 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001264 && (compl_leader.string == NULL
1265 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02001266 || (compl_fuzzy_match && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001267 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001268 ++compl_match_arraysize;
glepnir80b66202024-11-27 21:53:53 +01001269 if (match_head == NULL)
1270 match_head = compl;
1271 else
glepnira49c0772024-11-30 10:56:30 +01001272 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001273 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001274
1275 if (!shown_match_ok && !compl_fuzzy_match)
1276 {
1277 if (compl == compl_shown_match || did_find_shown_match)
1278 {
1279 // This item is the shown match or this is the
1280 // first displayed item after the shown match.
1281 compl_shown_match = compl;
1282 did_find_shown_match = TRUE;
1283 shown_match_ok = TRUE;
1284 }
1285 else
1286 // Remember this displayed match for when the
1287 // shown match is just below it.
1288 shown_compl = compl;
1289 cur = i;
1290 }
1291 else if (compl_fuzzy_match)
1292 {
1293 if (i == 0)
1294 shown_compl = compl;
1295 // Update the maximum fuzzy score and the shown match
1296 // if the current item's score is higher
1297 if (compl->cp_score > max_fuzzy_score)
1298 {
1299 did_find_shown_match = TRUE;
1300 max_fuzzy_score = compl->cp_score;
1301 if (!compl_no_select)
1302 compl_shown_match = compl;
1303 }
1304
1305 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1306 {
1307 cur = i;
1308 shown_match_ok = TRUE;
1309 }
1310 }
1311 i++;
glepnir80b66202024-11-27 21:53:53 +01001312 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001313
glepnira218cc62024-06-03 19:32:39 +02001314 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001315 {
1316 did_find_shown_match = TRUE;
1317
1318 // When the original text is the shown match don't set
1319 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001320 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001321 shown_match_ok = TRUE;
1322
1323 if (!shown_match_ok && shown_compl != NULL)
1324 {
1325 // The shown match isn't displayed, set it to the
1326 // previously displayed match.
1327 compl_shown_match = shown_compl;
1328 shown_match_ok = TRUE;
1329 }
1330 }
glepnira49c0772024-11-30 10:56:30 +01001331 compl = compl->cp_next;
1332 } while (compl != NULL && !is_first_match(compl));
1333
1334 if (compl_match_arraysize == 0)
1335 return -1;
1336
1337 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1338 if (compl_match_array == NULL)
1339 return -1;
1340
1341 compl = match_head;
1342 i = 0;
1343 while (compl != NULL)
1344 {
1345 if (compl->cp_text[CPT_ABBR] != NULL)
1346 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR];
1347 else
1348 compl_match_array[i].pum_text = compl->cp_str.string;
1349 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1350 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1351 compl_match_array[i].pum_score = compl->cp_score;
1352 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1353 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
1354 if (compl->cp_text[CPT_MENU] != NULL)
1355 compl_match_array[i++].pum_extra =
1356 compl->cp_text[CPT_MENU];
1357 else
1358 compl_match_array[i++].pum_extra = compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001359 match_next = compl->cp_match_next;
1360 compl->cp_match_next = NULL;
1361 compl = match_next;
1362 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001363
John Marriott5e6ea922024-11-23 14:01:57 +01001364 if (compl_fuzzy_match && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001365 {
1366 for (i = 0; i < compl_match_arraysize; i++)
1367 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001368 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001369 qsort(compl_match_array, (size_t)compl_match_arraysize,
1370 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001371 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001372 }
glepnira218cc62024-06-03 19:32:39 +02001373
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001374 if (!shown_match_ok) // no displayed match at all
1375 cur = -1;
1376
1377 return cur;
1378}
1379
1380/*
1381 * Show the popup menu for the list of matches.
1382 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1383 */
1384 void
1385ins_compl_show_pum(void)
1386{
1387 int i;
1388 int cur = -1;
1389 colnr_T col;
1390
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001391 if (!pum_wanted() || !pum_enough_matches())
1392 return;
1393
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001394 // Update the screen later, before drawing the popup menu over it.
1395 pum_call_update_screen();
1396
1397 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001398 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001399 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001400 else
1401 {
1402 // popup menu already exists, only need to find the current item.
1403 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001404 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001405 || compl_match_array[i].pum_text
1406 == compl_shown_match->cp_text[CPT_ABBR])
1407 {
1408 cur = i;
1409 break;
1410 }
1411 }
1412
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001413 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001414 {
1415#ifdef FEAT_EVAL
1416 if (compl_started && has_completechanged())
1417 trigger_complete_changed_event(cur);
1418#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001419 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001420 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001421
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001422 // In Replace mode when a $ is displayed at the end of the line only
1423 // part of the screen would be updated. We do need to redraw here.
1424 dollar_vcol = -1;
1425
1426 // Compute the screen column of the start of the completed text.
1427 // Use the cursor to get all wrapping and other settings right.
1428 col = curwin->w_cursor.col;
1429 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001430 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001431 pum_display(compl_match_array, compl_match_arraysize, cur);
1432 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001433
glepnircbb46b42024-02-03 18:11:13 +01001434 // After adding leader, set the current match to shown match.
1435 if (compl_started && compl_curr_match != compl_shown_match)
1436 compl_curr_match = compl_shown_match;
1437
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001438#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001439 if (has_completechanged())
1440 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001441#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001442}
1443
1444#define DICT_FIRST (1) // use just first element in "dict"
1445#define DICT_EXACT (2) // "dict" is the exact name of a file
1446
1447/*
glepnir40c1c332024-06-11 19:37:04 +02001448 * Get current completion leader
1449 */
1450 char_u *
1451ins_compl_leader(void)
1452{
John Marriott5e6ea922024-11-23 14:01:57 +01001453 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1454}
1455
1456/*
1457 * Get current completion leader length
1458 */
1459 size_t
1460ins_compl_leader_len(void)
1461{
1462 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001463}
1464
1465/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001466 * Add any identifiers that match the given pattern "pat" in the list of
1467 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001468 */
1469 static void
1470ins_compl_dictionaries(
1471 char_u *dict_start,
1472 char_u *pat,
1473 int flags, // DICT_FIRST and/or DICT_EXACT
1474 int thesaurus) // Thesaurus completion
1475{
1476 char_u *dict = dict_start;
1477 char_u *ptr;
1478 char_u *buf;
1479 regmatch_T regmatch;
1480 char_u **files;
1481 int count;
1482 int save_p_scs;
1483 int dir = compl_direction;
1484
1485 if (*dict == NUL)
1486 {
1487#ifdef FEAT_SPELL
1488 // When 'dictionary' is empty and spell checking is enabled use
1489 // "spell".
1490 if (!thesaurus && curwin->w_p_spell)
1491 dict = (char_u *)"spell";
1492 else
1493#endif
1494 return;
1495 }
1496
1497 buf = alloc(LSIZE);
1498 if (buf == NULL)
1499 return;
1500 regmatch.regprog = NULL; // so that we can goto theend
1501
1502 // If 'infercase' is set, don't use 'smartcase' here
1503 save_p_scs = p_scs;
1504 if (curbuf->b_p_inf)
1505 p_scs = FALSE;
1506
1507 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1508 // to only match at the start of a line. Otherwise just match the
1509 // pattern. Also need to double backslashes.
1510 if (ctrl_x_mode_line_or_eval())
1511 {
1512 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1513 size_t len;
1514
1515 if (pat_esc == NULL)
1516 goto theend;
1517 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001518 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001519 if (ptr == NULL)
1520 {
1521 vim_free(pat_esc);
1522 goto theend;
1523 }
1524 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1525 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1526 vim_free(pat_esc);
1527 vim_free(ptr);
1528 }
1529 else
1530 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001531 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001532 if (regmatch.regprog == NULL)
1533 goto theend;
1534 }
1535
1536 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1537 regmatch.rm_ic = ignorecase(pat);
1538 while (*dict != NUL && !got_int && !compl_interrupted)
1539 {
1540 // copy one dictionary file name into buf
1541 if (flags == DICT_EXACT)
1542 {
1543 count = 1;
1544 files = &dict;
1545 }
1546 else
1547 {
1548 // Expand wildcards in the dictionary name, but do not allow
1549 // backticks (for security, the 'dict' option may have been set in
1550 // a modeline).
1551 copy_option_part(&dict, buf, LSIZE, ",");
1552# ifdef FEAT_SPELL
1553 if (!thesaurus && STRCMP(buf, "spell") == 0)
1554 count = -1;
1555 else
1556# endif
1557 if (vim_strchr(buf, '`') != NULL
1558 || expand_wildcards(1, &buf, &count, &files,
1559 EW_FILE|EW_SILENT) != OK)
1560 count = 0;
1561 }
1562
1563# ifdef FEAT_SPELL
1564 if (count == -1)
1565 {
1566 // Complete from active spelling. Skip "\<" in the pattern, we
1567 // don't use it as a RE.
1568 if (pat[0] == '\\' && pat[1] == '<')
1569 ptr = pat + 2;
1570 else
1571 ptr = pat;
1572 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1573 }
1574 else
1575# endif
1576 if (count > 0) // avoid warning for using "files" uninit
1577 {
1578 ins_compl_files(count, files, thesaurus, flags,
1579 &regmatch, buf, &dir);
1580 if (flags != DICT_EXACT)
1581 FreeWild(count, files);
1582 }
1583 if (flags != 0)
1584 break;
1585 }
1586
1587theend:
1588 p_scs = save_p_scs;
1589 vim_regfree(regmatch.regprog);
1590 vim_free(buf);
1591}
1592
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001593/*
1594 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1595 * skipping the word at 'skip_word'. Returns OK on success.
1596 */
1597 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001598thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001599 char_u *fname,
1600 char_u **buf_arg,
1601 int dir,
1602 char_u *skip_word)
1603{
1604 int status = OK;
1605 char_u *ptr;
1606 char_u *wstart;
1607
1608 // Add the other matches on the line
1609 ptr = *buf_arg;
1610 while (!got_int)
1611 {
1612 // Find start of the next word. Skip white
1613 // space and punctuation.
1614 ptr = find_word_start(ptr);
1615 if (*ptr == NUL || *ptr == NL)
1616 break;
1617 wstart = ptr;
1618
1619 // Find end of the word.
1620 if (has_mbyte)
1621 // Japanese words may have characters in
1622 // different classes, only separate words
1623 // with single-byte non-word characters.
1624 while (*ptr != NUL)
1625 {
1626 int l = (*mb_ptr2len)(ptr);
1627
1628 if (l < 2 && !vim_iswordc(*ptr))
1629 break;
1630 ptr += l;
1631 }
1632 else
1633 ptr = find_word_end(ptr);
1634
1635 // Add the word. Skip the regexp match.
1636 if (wstart != skip_word)
1637 {
1638 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1639 fname, dir, FALSE);
1640 if (status == FAIL)
1641 break;
1642 }
1643 }
1644
1645 *buf_arg = ptr;
1646 return status;
1647}
1648
1649/*
1650 * Process "count" dictionary/thesaurus "files" and add the text matching
1651 * "regmatch".
1652 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001653 static void
1654ins_compl_files(
1655 int count,
1656 char_u **files,
1657 int thesaurus,
1658 int flags,
1659 regmatch_T *regmatch,
1660 char_u *buf,
1661 int *dir)
1662{
1663 char_u *ptr;
1664 int i;
1665 FILE *fp;
1666 int add_r;
1667
1668 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1669 {
1670 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001671 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001672 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001673 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001674 vim_snprintf((char *)IObuff, IOSIZE,
1675 _("Scanning dictionary: %s"), (char *)files[i]);
1676 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1677 }
1678
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001679 if (fp == NULL)
1680 continue;
1681
1682 // Read dictionary file line by line.
1683 // Check each line for a match.
1684 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001685 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001686 ptr = buf;
1687 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001688 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001689 ptr = regmatch->startp[0];
1690 if (ctrl_x_mode_line_or_eval())
1691 ptr = find_line_end(ptr);
1692 else
1693 ptr = find_word_end(ptr);
1694 add_r = ins_compl_add_infercase(regmatch->startp[0],
1695 (int)(ptr - regmatch->startp[0]),
1696 p_ic, files[i], *dir, FALSE);
1697 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001698 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001699 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001700 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001701 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001702 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001703 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001704 if (add_r == OK)
1705 // if dir was BACKWARD then honor it just once
1706 *dir = FORWARD;
1707 else if (add_r == FAIL)
1708 break;
1709 // avoid expensive call to vim_regexec() when at end
1710 // of line
1711 if (*ptr == '\n' || got_int)
1712 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001713 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001714 line_breakcheck();
1715 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001716 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001717 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001718 }
1719}
1720
1721/*
1722 * Find the start of the next word.
1723 * Returns a pointer to the first char of the word. Also stops at a NUL.
1724 */
1725 char_u *
1726find_word_start(char_u *ptr)
1727{
1728 if (has_mbyte)
1729 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1730 ptr += (*mb_ptr2len)(ptr);
1731 else
1732 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1733 ++ptr;
1734 return ptr;
1735}
1736
1737/*
1738 * Find the end of the word. Assumes it starts inside a word.
1739 * Returns a pointer to just after the word.
1740 */
1741 char_u *
1742find_word_end(char_u *ptr)
1743{
1744 int start_class;
1745
1746 if (has_mbyte)
1747 {
1748 start_class = mb_get_class(ptr);
1749 if (start_class > 1)
1750 while (*ptr != NUL)
1751 {
1752 ptr += (*mb_ptr2len)(ptr);
1753 if (mb_get_class(ptr) != start_class)
1754 break;
1755 }
1756 }
1757 else
1758 while (vim_iswordc(*ptr))
1759 ++ptr;
1760 return ptr;
1761}
1762
1763/*
1764 * Find the end of the line, omitting CR and NL at the end.
1765 * Returns a pointer to just after the line.
1766 */
1767 static char_u *
1768find_line_end(char_u *ptr)
1769{
1770 char_u *s;
1771
1772 s = ptr + STRLEN(ptr);
1773 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1774 --s;
1775 return s;
1776}
1777
1778/*
1779 * Free the list of completions
1780 */
1781 static void
1782ins_compl_free(void)
1783{
1784 compl_T *match;
1785 int i;
1786
John Marriott5e6ea922024-11-23 14:01:57 +01001787 VIM_CLEAR_STRING(compl_pattern);
1788 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001789
1790 if (compl_first_match == NULL)
1791 return;
1792
1793 ins_compl_del_pum();
1794 pum_clear();
1795
1796 compl_curr_match = compl_first_match;
1797 do
1798 {
1799 match = compl_curr_match;
1800 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001801 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001802 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001803 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001804 vim_free(match->cp_fname);
1805 for (i = 0; i < CPT_COUNT; ++i)
1806 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001807#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001808 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001809#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001810 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001811 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001812 compl_first_match = compl_curr_match = NULL;
1813 compl_shown_match = NULL;
1814 compl_old_match = NULL;
1815}
1816
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001817/*
1818 * Reset/clear the completion state.
1819 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001820 void
1821ins_compl_clear(void)
1822{
1823 compl_cont_status = 0;
1824 compl_started = FALSE;
1825 compl_matches = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001826 VIM_CLEAR_STRING(compl_pattern);
1827 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001828 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001829 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001830 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001831#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001832 // clear v:completed_item
1833 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001834#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001835}
1836
1837/*
1838 * Return TRUE when Insert completion is active.
1839 */
1840 int
1841ins_compl_active(void)
1842{
1843 return compl_started;
1844}
1845
1846/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001847 * Selected one of the matches. When FALSE the match was edited or using the
1848 * longest common string.
1849 */
1850 int
1851ins_compl_used_match(void)
1852{
1853 return compl_used_match;
1854}
1855
1856/*
1857 * Initialize get longest common string.
1858 */
1859 void
1860ins_compl_init_get_longest(void)
1861{
1862 compl_get_longest = FALSE;
1863}
1864
1865/*
1866 * Returns TRUE when insert completion is interrupted.
1867 */
1868 int
1869ins_compl_interrupted(void)
1870{
1871 return compl_interrupted;
1872}
1873
1874/*
1875 * Returns TRUE if the <Enter> key selects a match in the completion popup
1876 * menu.
1877 */
1878 int
1879ins_compl_enter_selects(void)
1880{
1881 return compl_enter_selects;
1882}
1883
1884/*
1885 * Return the column where the text starts that is being completed
1886 */
1887 colnr_T
1888ins_compl_col(void)
1889{
1890 return compl_col;
1891}
1892
1893/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001894 * Return the length in bytes of the text being completed
1895 */
1896 int
1897ins_compl_len(void)
1898{
1899 return compl_length;
1900}
1901
1902/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001903 * Delete one character before the cursor and show the subset of the matches
1904 * that match the word that is now before the cursor.
1905 * Returns the character to be used, NUL if the work is done and another char
1906 * to be got from the user.
1907 */
1908 int
1909ins_compl_bs(void)
1910{
1911 char_u *line;
1912 char_u *p;
1913
1914 line = ml_get_curline();
1915 p = line + curwin->w_cursor.col;
1916 MB_PTR_BACK(line, p);
1917
1918 // Stop completion when the whole word was deleted. For Omni completion
1919 // allow the word to be deleted, we won't match everything.
1920 // Respect the 'backspace' option.
1921 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001922 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1923 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001924 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1925 - compl_length < 0))
1926 return K_BS;
1927
1928 // Deleted more than what was used to find matches or didn't finish
1929 // finding all matches: need to look for matches all over again.
1930 if (curwin->w_cursor.col <= compl_col + compl_length
1931 || ins_compl_need_restart())
1932 ins_compl_restart();
1933
John Marriott5e6ea922024-11-23 14:01:57 +01001934 VIM_CLEAR_STRING(compl_leader);
1935 compl_leader.length = (size_t)((p - line) - compl_col);
1936 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
1937 if (compl_leader.string == NULL)
1938 {
1939 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001940 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01001941 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001942
1943 ins_compl_new_leader();
1944 if (compl_shown_match != NULL)
1945 // Make sure current match is not a hidden item.
1946 compl_curr_match = compl_shown_match;
1947 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001948}
1949
1950/*
1951 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1952 * be called.
1953 */
1954 static int
1955ins_compl_need_restart(void)
1956{
1957 // Return TRUE if we didn't complete finding matches or when the
1958 // 'completefunc' returned "always" in the "refresh" dictionary item.
1959 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001960 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001961 && compl_opt_refresh_always);
1962}
1963
1964/*
1965 * Called after changing "compl_leader".
1966 * Show the popup menu with a different set of matches.
1967 * May also search for matches again if the previous search was interrupted.
1968 */
1969 static void
1970ins_compl_new_leader(void)
1971{
1972 ins_compl_del_pum();
1973 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01001974 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001975 compl_used_match = FALSE;
1976
1977 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01001978 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001979 else
1980 {
1981#ifdef FEAT_SPELL
1982 spell_bad_len = 0; // need to redetect bad word
1983#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001984 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001985 // the popup menu display the changed text before the cursor. Set
1986 // "compl_restarting" to avoid that the first match is inserted.
1987 pum_call_update_screen();
1988#ifdef FEAT_GUI
1989 if (gui.in_use)
1990 {
1991 // Show the cursor after the match, not after the redrawn text.
1992 setcursor();
1993 out_flush_cursor(FALSE, FALSE);
1994 }
1995#endif
1996 compl_restarting = TRUE;
1997 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1998 compl_cont_status = 0;
1999 compl_restarting = FALSE;
2000 }
2001
2002 compl_enter_selects = !compl_used_match;
2003
2004 // Show the popup menu with a different set of matches.
2005 ins_compl_show_pum();
2006
2007 // Don't let Enter select the original text when there is no popup menu.
2008 if (compl_match_array == NULL)
2009 compl_enter_selects = FALSE;
2010}
2011
2012/*
2013 * Return the length of the completion, from the completion start column to
2014 * the cursor column. Making sure it never goes below zero.
2015 */
2016 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002017get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002018{
2019 int off = (int)curwin->w_cursor.col - (int)compl_col;
2020
2021 if (off < 0)
2022 return 0;
2023 return off;
2024}
2025
2026/*
2027 * Append one character to the match leader. May reduce the number of
2028 * matches.
2029 */
2030 void
2031ins_compl_addleader(int c)
2032{
2033 int cc;
2034
2035 if (stop_arrow() == FAIL)
2036 return;
2037 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2038 {
2039 char_u buf[MB_MAXBYTES + 1];
2040
2041 (*mb_char2bytes)(c, buf);
2042 buf[cc] = NUL;
2043 ins_char_bytes(buf, cc);
2044 if (compl_opt_refresh_always)
2045 AppendToRedobuff(buf);
2046 }
2047 else
2048 {
2049 ins_char(c);
2050 if (compl_opt_refresh_always)
2051 AppendCharToRedobuff(c);
2052 }
2053
2054 // If we didn't complete finding matches we must search again.
2055 if (ins_compl_need_restart())
2056 ins_compl_restart();
2057
2058 // When 'always' is set, don't reset compl_leader. While completing,
2059 // cursor doesn't point original position, changing compl_leader would
2060 // break redo.
2061 if (!compl_opt_refresh_always)
2062 {
John Marriott5e6ea922024-11-23 14:01:57 +01002063 VIM_CLEAR_STRING(compl_leader);
2064 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2065 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2066 compl_leader.length);
2067 if (compl_leader.string == NULL)
2068 {
2069 compl_leader.length = 0;
2070 return;
2071 }
2072
2073 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002074 }
2075}
2076
2077/*
2078 * Setup for finding completions again without leaving CTRL-X mode. Used when
2079 * BS or a key was typed while still searching for matches.
2080 */
2081 static void
2082ins_compl_restart(void)
2083{
2084 ins_compl_free();
2085 compl_started = FALSE;
2086 compl_matches = 0;
2087 compl_cont_status = 0;
2088 compl_cont_mode = 0;
2089}
2090
2091/*
2092 * Set the first match, the original text.
2093 */
2094 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002095ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002096{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002097 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002098 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2099 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002100 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002101 {
John Marriott5e6ea922024-11-23 14:01:57 +01002102 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002103 if (p != NULL)
2104 {
John Marriott5e6ea922024-11-23 14:01:57 +01002105 VIM_CLEAR_STRING(compl_first_match->cp_str);
2106 compl_first_match->cp_str.string = p;
2107 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002108 }
2109 }
2110 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002111 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002112 {
John Marriott5e6ea922024-11-23 14:01:57 +01002113 char_u *p = vim_strnsave(str, len);
2114 if (p != NULL)
2115 {
2116 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2117 compl_first_match->cp_prev->cp_str.string = p;
2118 compl_first_match->cp_prev->cp_str.length = len;
2119 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002120 }
2121}
2122
2123/*
2124 * Append one character to the match leader. May reduce the number of
2125 * matches.
2126 */
2127 void
2128ins_compl_addfrommatch(void)
2129{
2130 char_u *p;
2131 int len = (int)curwin->w_cursor.col - (int)compl_col;
2132 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133
John Marriott5e6ea922024-11-23 14:01:57 +01002134 p = compl_shown_match->cp_str.string;
2135 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002136 {
John Marriott5e6ea922024-11-23 14:01:57 +01002137 size_t plen;
2138 compl_T *cp;
2139
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002140 // When still at the original match use the first entry that matches
2141 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002142 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002143 return;
2144
2145 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002146 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002147 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002148 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002149 {
John Marriott5e6ea922024-11-23 14:01:57 +01002150 if (compl_leader.string == NULL
2151 || ins_compl_equal(cp, compl_leader.string,
2152 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002153 {
John Marriott5e6ea922024-11-23 14:01:57 +01002154 p = cp->cp_str.string;
2155 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002156 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002157 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002158 }
John Marriott5e6ea922024-11-23 14:01:57 +01002159 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002160 return;
2161 }
2162 p += len;
2163 c = PTR2CHAR(p);
2164 ins_compl_addleader(c);
2165}
2166
2167/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002168 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002169 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2170 * compl_cont_mode and compl_cont_status.
2171 * Returns TRUE when the character is not to be inserted.
2172 */
2173 static int
2174set_ctrl_x_mode(int c)
2175{
2176 int retval = FALSE;
2177
2178 switch (c)
2179 {
2180 case Ctrl_E:
2181 case Ctrl_Y:
2182 // scroll the window one line up or down
2183 ctrl_x_mode = CTRL_X_SCROLL;
2184 if (!(State & REPLACE_FLAG))
2185 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2186 else
2187 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2188 edit_submode_pre = NULL;
2189 showmode();
2190 break;
2191 case Ctrl_L:
2192 // complete whole line
2193 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2194 break;
2195 case Ctrl_F:
2196 // complete filenames
2197 ctrl_x_mode = CTRL_X_FILES;
2198 break;
2199 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002200 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002201 ctrl_x_mode = CTRL_X_DICTIONARY;
2202 break;
2203 case Ctrl_R:
2204 // Register insertion without exiting CTRL-X mode
2205 // Simply allow ^R to happen without affecting ^X mode
2206 break;
2207 case Ctrl_T:
2208 // complete words from a thesaurus
2209 ctrl_x_mode = CTRL_X_THESAURUS;
2210 break;
2211#ifdef FEAT_COMPL_FUNC
2212 case Ctrl_U:
2213 // user defined completion
2214 ctrl_x_mode = CTRL_X_FUNCTION;
2215 break;
2216 case Ctrl_O:
2217 // omni completion
2218 ctrl_x_mode = CTRL_X_OMNI;
2219 break;
2220#endif
2221 case 's':
2222 case Ctrl_S:
2223 // complete spelling suggestions
2224 ctrl_x_mode = CTRL_X_SPELL;
2225#ifdef FEAT_SPELL
2226 ++emsg_off; // Avoid getting the E756 error twice.
2227 spell_back_to_badword();
2228 --emsg_off;
2229#endif
2230 break;
2231 case Ctrl_RSB:
2232 // complete tag names
2233 ctrl_x_mode = CTRL_X_TAGS;
2234 break;
2235#ifdef FEAT_FIND_ID
2236 case Ctrl_I:
2237 case K_S_TAB:
2238 // complete keywords from included files
2239 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2240 break;
2241 case Ctrl_D:
2242 // complete definitions from included files
2243 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2244 break;
2245#endif
2246 case Ctrl_V:
2247 case Ctrl_Q:
2248 // complete vim commands
2249 ctrl_x_mode = CTRL_X_CMDLINE;
2250 break;
2251 case Ctrl_Z:
2252 // stop completion
2253 ctrl_x_mode = CTRL_X_NORMAL;
2254 edit_submode = NULL;
2255 showmode();
2256 retval = TRUE;
2257 break;
2258 case Ctrl_P:
2259 case Ctrl_N:
2260 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2261 // just started ^X mode, or there were enough ^X's to cancel
2262 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2263 // do normal expansion when interrupting a different mode (say
2264 // ^X^F^X^P or ^P^X^X^P, see below)
2265 // nothing changes if interrupting mode 0, (eg, the flag
2266 // doesn't change when going to ADDING mode -- Acevedo
2267 if (!(compl_cont_status & CONT_INTRPT))
2268 compl_cont_status |= CONT_LOCAL;
2269 else if (compl_cont_mode != 0)
2270 compl_cont_status &= ~CONT_LOCAL;
2271 // FALLTHROUGH
2272 default:
2273 // If we have typed at least 2 ^X's... for modes != 0, we set
2274 // compl_cont_status = 0 (eg, as if we had just started ^X
2275 // mode).
2276 // For mode 0, we set "compl_cont_mode" to an impossible
2277 // value, in both cases ^X^X can be used to restart the same
2278 // mode (avoiding ADDING mode).
2279 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2280 // 'complete' and local ^P expansions respectively.
2281 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2282 // mode -- Acevedo
2283 if (c == Ctrl_X)
2284 {
2285 if (compl_cont_mode != 0)
2286 compl_cont_status = 0;
2287 else
2288 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2289 }
2290 ctrl_x_mode = CTRL_X_NORMAL;
2291 edit_submode = NULL;
2292 showmode();
2293 break;
2294 }
2295
2296 return retval;
2297}
2298
2299/*
glepnir1c5a1202024-12-04 20:27:34 +01002300 * Trigger CompleteDone event and adds relevant information to v:event
2301 */
2302 static void
2303trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2304{
2305#if defined(FEAT_EVAL)
2306 save_v_event_T save_v_event;
2307 dict_T *v_event = get_v_event(&save_v_event);
2308 char_u *mode_str = NULL;
2309
2310 mode = mode & ~CTRL_X_WANT_IDENT;
2311 if (ctrl_x_mode_names[mode])
2312 mode_str = (char_u *)ctrl_x_mode_names[mode];
2313
2314 (void)dict_add_string(v_event, "complete_word",
2315 word == NULL ? (char_u *)"" : word);
2316 (void)dict_add_string(v_event, "complete_type",
2317 mode_str != NULL ? mode_str : (char_u *)"");
2318
2319 dict_set_items_ro(v_event);
2320#endif
2321 ins_apply_autocmds(EVENT_COMPLETEDONE);
2322
2323#if defined(FEAT_EVAL)
2324 restore_v_event(v_event, &save_v_event);
2325#endif
2326}
2327
2328/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002329 * Stop insert completion mode
2330 */
2331 static int
2332ins_compl_stop(int c, int prev_mode, int retval)
2333{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002334 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002335 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002336
2337 // Get here when we have finished typing a sequence of ^N and
2338 // ^P or other completion characters in CTRL-X mode. Free up
2339 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002340 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002341 {
John Marriott5e6ea922024-11-23 14:01:57 +01002342 char_u *ptr;
2343
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002344 // If any of the original typed text has been changed, eg when
2345 // ignorecase is set, we must add back-spaces to the redo
2346 // buffer. We add as few as necessary to delete just the part
2347 // of the original text that has changed.
2348 // When using the longest match, edited the match or used
2349 // CTRL-E then don't use the current match.
2350 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002351 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002352 else
2353 ptr = NULL;
2354 ins_compl_fixRedoBufForLeader(ptr);
2355 }
2356
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002357 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002358
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002359 // When completing whole lines: fix indent for 'cindent'.
2360 // Otherwise, break line if it's too long.
2361 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2362 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002363 // re-indent the current line
2364 if (want_cindent)
2365 {
2366 do_c_expr_indent();
2367 want_cindent = FALSE; // don't do it again
2368 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002369 }
2370 else
2371 {
2372 int prev_col = curwin->w_cursor.col;
2373
2374 // put the cursor on the last char, for 'tw' formatting
2375 if (prev_col > 0)
2376 dec_cursor();
2377 // only format when something was inserted
2378 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2379 insertchar(NUL, 0, -1);
2380 if (prev_col > 0
2381 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2382 inc_cursor();
2383 }
2384
2385 // If the popup menu is displayed pressing CTRL-Y means accepting
2386 // the selection without inserting anything. When
2387 // compl_enter_selects is set the Enter key does the same.
2388 if ((c == Ctrl_Y || (compl_enter_selects
2389 && (c == CAR || c == K_KENTER || c == NL)))
2390 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002391 {
2392 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002393 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002394 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002395
2396 // CTRL-E means completion is Ended, go back to the typed text.
2397 // but only do this, if the Popup is still visible
2398 if (c == Ctrl_E)
2399 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002400 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002401 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002402
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002403 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002404 if (compl_leader.string != NULL)
2405 {
2406 p = compl_leader.string;
2407 plen = compl_leader.length;
2408 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002409 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002410 {
2411 p = compl_orig_text.string;
2412 plen = compl_orig_text.length;
2413 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002414 if (p != NULL)
2415 {
2416 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002417
John Marriott5e6ea922024-11-23 14:01:57 +01002418 if ((int)plen > compl_len)
2419 ins_bytes_len(p + compl_len, (int)(plen - compl_len));
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002420 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002421 retval = TRUE;
2422 }
2423
2424 auto_format(FALSE, TRUE);
2425
2426 // Trigger the CompleteDonePre event to give scripts a chance to
2427 // act upon the completion before clearing the info, and restore
2428 // ctrl_x_mode, so that complete_info() can be used.
2429 ctrl_x_mode = prev_mode;
2430 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2431
2432 ins_compl_free();
2433 compl_started = FALSE;
2434 compl_matches = 0;
2435 if (!shortmess(SHM_COMPLETIONMENU))
2436 msg_clr_cmdline(); // necessary for "noshowmode"
2437 ctrl_x_mode = CTRL_X_NORMAL;
2438 compl_enter_selects = FALSE;
2439 if (edit_submode != NULL)
2440 {
2441 edit_submode = NULL;
2442 showmode();
2443 }
2444
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002445 if (c == Ctrl_C && cmdwin_type != 0)
2446 // Avoid the popup menu remains displayed when leaving the
2447 // command line window.
2448 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002449 // Indent now if a key was typed that is in 'cinkeys'.
2450 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2451 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002452 // Trigger the CompleteDone event to give scripts a chance to act
2453 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002454 trigger_complete_done_event(prev_mode, word);
2455 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002456
2457 return retval;
2458}
2459
2460/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002461 * Prepare for Insert mode completion, or stop it.
2462 * Called just after typing a character in Insert mode.
2463 * Returns TRUE when the character is not to be inserted;
2464 */
2465 int
2466ins_compl_prep(int c)
2467{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002468 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002469 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002470
2471 // Forget any previous 'special' messages if this is actually
2472 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2473 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2474 edit_submode_extra = NULL;
2475
zeertzjq440d4cb2023-03-02 17:51:32 +00002476 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002477 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002478 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002479 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002480 return retval;
2481
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002482#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002483 // Ignore mouse events in a popup window
2484 if (is_mouse_key(c))
2485 {
2486 // Ignore drag and release events, the position does not need to be in
2487 // the popup and it may have just closed.
2488 if (c == K_LEFTRELEASE
2489 || c == K_LEFTRELEASE_NM
2490 || c == K_MIDDLERELEASE
2491 || c == K_RIGHTRELEASE
2492 || c == K_X1RELEASE
2493 || c == K_X2RELEASE
2494 || c == K_LEFTDRAG
2495 || c == K_MIDDLEDRAG
2496 || c == K_RIGHTDRAG
2497 || c == K_X1DRAG
2498 || c == K_X2DRAG)
2499 return retval;
2500 if (popup_visible)
2501 {
2502 int row = mouse_row;
2503 int col = mouse_col;
2504 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2505
2506 if (wp != NULL && WIN_IS_POPUP(wp))
2507 return retval;
2508 }
2509 }
2510#endif
2511
zeertzjqdca29d92021-08-31 19:12:51 +02002512 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2513 {
2514 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2515 || !vim_is_ctrl_x_key(c))
2516 {
2517 // Not starting another completion mode.
2518 ctrl_x_mode = CTRL_X_CMDLINE;
2519
2520 // CTRL-X CTRL-Z should stop completion without inserting anything
2521 if (c == Ctrl_Z)
2522 retval = TRUE;
2523 }
2524 else
2525 {
2526 ctrl_x_mode = CTRL_X_CMDLINE;
2527
2528 // Other CTRL-X keys first stop completion, then start another
2529 // completion mode.
2530 ins_compl_prep(' ');
2531 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2532 }
2533 }
2534
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002535 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002536 if (ctrl_x_mode_not_defined_yet()
2537 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002538 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002539 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002540 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002541 }
2542
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002543 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002544 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2545 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002546 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002547 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002548 {
2549 // We're already in CTRL-X mode, do we stay in it?
2550 if (!vim_is_ctrl_x_key(c))
2551 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002552 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002553 ctrl_x_mode = CTRL_X_NORMAL;
2554 else
2555 ctrl_x_mode = CTRL_X_FINISHED;
2556 edit_submode = NULL;
2557 }
2558 showmode();
2559 }
2560
2561 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2562 {
2563 // Show error message from attempted keyword completion (probably
2564 // 'Pattern not found') until another key is hit, then go back to
2565 // showing what mode we are in.
2566 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002567 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002568 && c != Ctrl_R && !ins_compl_pum_key(c))
2569 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002570 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002571 }
2572 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2573 // Trigger the CompleteDone event to give scripts a chance to act
2574 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002575 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002576
LemonBoy2bf52dd2022-04-09 18:17:34 +01002577 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002578
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002579 // reset continue_* if we left expansion-mode, if we stay they'll be
2580 // (re)set properly in ins_complete()
2581 if (!vim_is_ctrl_x_key(c))
2582 {
2583 compl_cont_status = 0;
2584 compl_cont_mode = 0;
2585 }
2586
2587 return retval;
2588}
2589
2590/*
2591 * Fix the redo buffer for the completion leader replacing some of the typed
2592 * text. This inserts backspaces and appends the changed text.
2593 * "ptr" is the known leader text or NUL.
2594 */
2595 static void
2596ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2597{
John Marriott5e6ea922024-11-23 14:01:57 +01002598 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002599 char_u *p;
2600 char_u *ptr = ptr_arg;
2601
2602 if (ptr == NULL)
2603 {
John Marriott5e6ea922024-11-23 14:01:57 +01002604 if (compl_leader.string != NULL)
2605 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002606 else
2607 return; // nothing to do
2608 }
John Marriott5e6ea922024-11-23 14:01:57 +01002609 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002610 {
John Marriott5e6ea922024-11-23 14:01:57 +01002611 p = compl_orig_text.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002612 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2613 ;
2614 if (len > 0)
2615 len -= (*mb_head_off)(p, p + len);
2616 for (p += len; *p != NUL; MB_PTR_ADV(p))
2617 AppendCharToRedobuff(K_BS);
2618 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002619 if (ptr != NULL)
2620 AppendToRedobuffLit(ptr + len, -1);
2621}
2622
2623/*
2624 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2625 * (depending on flag) starting from buf and looking for a non-scanned
2626 * buffer (other than curbuf). curbuf is special, if it is called with
2627 * buf=curbuf then it has to be the first call for a given flag/expansion.
2628 *
2629 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2630 */
2631 static buf_T *
2632ins_compl_next_buf(buf_T *buf, int flag)
2633{
2634 static win_T *wp = NULL;
2635
2636 if (flag == 'w') // just windows
2637 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002638 if (buf == curbuf || !win_valid(wp))
2639 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002640 wp = curwin;
2641 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2642 && wp->w_buffer->b_scanned)
2643 ;
2644 buf = wp->w_buffer;
2645 }
2646 else
2647 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2648 // (unlisted buffers)
2649 // When completing whole lines skip unloaded buffers.
2650 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2651 && ((flag == 'U'
2652 ? buf->b_p_bl
2653 : (!buf->b_p_bl
2654 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2655 || buf->b_scanned))
2656 ;
2657 return buf;
2658}
2659
2660#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002661
2662# ifdef FEAT_EVAL
2663static callback_T cfu_cb; // 'completefunc' callback function
2664static callback_T ofu_cb; // 'omnifunc' callback function
2665static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2666# endif
2667
2668/*
2669 * Copy a global callback function to a buffer local callback.
2670 */
2671 static void
2672copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2673{
2674 free_callback(bufcb);
2675 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2676 copy_callback(bufcb, globcb);
2677}
2678
2679/*
2680 * Parse the 'completefunc' option value and set the callback function.
2681 * Invoked when the 'completefunc' option is set. The option value can be a
2682 * name of a function (string), or function(<name>) or funcref(<name>) or a
2683 * lambda expression.
2684 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002685 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002686did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002687{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002688 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2689 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002690
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002691 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002692
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002693 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002694}
2695
2696/*
2697 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002698 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002699 */
2700 void
2701set_buflocal_cfu_callback(buf_T *buf UNUSED)
2702{
2703# ifdef FEAT_EVAL
2704 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2705# endif
2706}
2707
2708/*
2709 * Parse the 'omnifunc' option value and set the callback function.
2710 * Invoked when the 'omnifunc' option is set. The option value can be a
2711 * name of a function (string), or function(<name>) or funcref(<name>) or a
2712 * lambda expression.
2713 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002714 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002715did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002716{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002717 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2718 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002719
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002720 set_buflocal_ofu_callback(curbuf);
2721 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002722}
2723
2724/*
2725 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002726 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002727 */
2728 void
2729set_buflocal_ofu_callback(buf_T *buf UNUSED)
2730{
2731# ifdef FEAT_EVAL
2732 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2733# endif
2734}
2735
2736/*
2737 * Parse the 'thesaurusfunc' option value and set the callback function.
2738 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2739 * name of a function (string), or function(<name>) or funcref(<name>) or a
2740 * lambda expression.
2741 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002742 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002743did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002744{
2745 int retval;
2746
zeertzjq6eda2692024-11-03 09:23:33 +01002747 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002748 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002749 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2750 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002751 else
2752 {
2753 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002754 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002755 // when using :set, free the local callback
2756 if (!(args->os_flags & OPT_GLOBAL))
2757 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002758 }
2759
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002760 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002761}
2762
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002763/*
2764 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002765 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002766 */
2767 int
2768set_ref_in_insexpand_funcs(int copyID)
2769{
2770 int abort = FALSE;
2771
2772 abort = set_ref_in_callback(&cfu_cb, copyID);
2773 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2774 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2775
2776 return abort;
2777}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002778
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002779/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002780 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002781 */
2782 static char_u *
2783get_complete_funcname(int type)
2784{
2785 switch (type)
2786 {
2787 case CTRL_X_FUNCTION:
2788 return curbuf->b_p_cfu;
2789 case CTRL_X_OMNI:
2790 return curbuf->b_p_ofu;
2791 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002792 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002793 default:
2794 return (char_u *)"";
2795 }
2796}
2797
2798/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002799 * Get the callback to use for insert mode completion.
2800 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002801 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002802get_insert_callback(int type)
2803{
2804 if (type == CTRL_X_FUNCTION)
2805 return &curbuf->b_cfu_cb;
2806 if (type == CTRL_X_OMNI)
2807 return &curbuf->b_ofu_cb;
2808 // CTRL_X_THESAURUS
2809 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2810}
2811
2812/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002813 * Execute user defined complete function 'completefunc', 'omnifunc' or
2814 * 'thesaurusfunc', and get matches in "matches".
2815 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002816 */
2817 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002818expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002819{
2820 list_T *matchlist = NULL;
2821 dict_T *matchdict = NULL;
2822 typval_T args[3];
2823 char_u *funcname;
2824 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002825 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002826 typval_T rettv;
2827 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002828 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002829
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002830 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002831 if (*funcname == NUL)
2832 return;
2833
2834 // Call 'completefunc' to obtain the list of matches.
2835 args[0].v_type = VAR_NUMBER;
2836 args[0].vval.v_number = 0;
2837 args[1].v_type = VAR_STRING;
2838 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2839 args[2].v_type = VAR_UNKNOWN;
2840
2841 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002842 // Lock the text to avoid weird things from happening. Also disallow
2843 // switching to another window, it should not be needed and may end up in
2844 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002845 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002846
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002847 cb = get_insert_callback(type);
2848 retval = call_callback(cb, 0, &rettv, 2, args);
2849
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002850 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002851 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002852 {
2853 switch (rettv.v_type)
2854 {
2855 case VAR_LIST:
2856 matchlist = rettv.vval.v_list;
2857 break;
2858 case VAR_DICT:
2859 matchdict = rettv.vval.v_dict;
2860 break;
2861 case VAR_SPECIAL:
2862 if (rettv.vval.v_number == VVAL_NONE)
2863 compl_opt_suppress_empty = TRUE;
2864 // FALLTHROUGH
2865 default:
2866 // TODO: Give error message?
2867 clear_tv(&rettv);
2868 break;
2869 }
2870 }
zeertzjqcfe45652022-05-27 17:26:55 +01002871 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002872
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002873 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002874 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002875 validate_cursor();
2876 if (!EQUAL_POS(curwin->w_cursor, pos))
2877 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002878 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002879 goto theend;
2880 }
2881
2882 if (matchlist != NULL)
2883 ins_compl_add_list(matchlist);
2884 else if (matchdict != NULL)
2885 ins_compl_add_dict(matchdict);
2886
2887theend:
2888 // Restore State, it might have been changed.
2889 State = save_State;
2890
2891 if (matchdict != NULL)
2892 dict_unref(matchdict);
2893 if (matchlist != NULL)
2894 list_unref(matchlist);
2895}
2896#endif // FEAT_COMPL_FUNC
2897
2898#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02002899
2900 static inline int
2901get_user_highlight_attr(char_u *hlname)
2902{
2903 if (hlname != NULL && *hlname != NUL)
2904 return syn_name2attr(hlname);
2905 return -1;
2906}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002907/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002908 * Add a match to the list of matches from a typeval_T.
2909 * If the given string is already in the list of completions, then return
2910 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2911 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002912 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002913 */
2914 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002915ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002916{
2917 char_u *word;
2918 int dup = FALSE;
2919 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002920 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002921 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002922 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002923 int status;
glepnir0fe17f82024-10-08 22:26:44 +02002924 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02002925 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01002926 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002927
Bram Moolenaar08928322020-01-04 14:32:48 +01002928 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002929 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2930 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002931 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2932 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2933 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2934 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2935 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02002936
glepnir0fe17f82024-10-08 22:26:44 +02002937 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01002938 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02002939
2940 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01002941 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02002942
Bram Moolenaard61efa52022-07-23 09:52:04 +01002943 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2944 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2945 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002946 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002947 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2948 dup = dict_get_number(tv->vval.v_dict, "dup");
2949 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2950 empty = dict_get_number(tv->vval.v_dict, "empty");
2951 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2952 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002953 flags |= CP_EQUAL;
2954 }
2955 else
2956 {
2957 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002958 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002959 }
2960 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002961 {
2962 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002963 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002964 }
glepnir508e7852024-07-25 21:39:08 +02002965 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01002966 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002967 if (status != OK)
2968 clear_tv(&user_data);
2969 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002970}
2971
2972/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002973 * Add completions from a list.
2974 */
2975 static void
2976ins_compl_add_list(list_T *list)
2977{
2978 listitem_T *li;
2979 int dir = compl_direction;
2980
2981 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002982 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002983 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002984 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002985 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002986 // if dir was BACKWARD then honor it just once
2987 dir = FORWARD;
2988 else if (did_emsg)
2989 break;
2990 }
2991}
2992
2993/*
2994 * Add completions from a dict.
2995 */
2996 static void
2997ins_compl_add_dict(dict_T *dict)
2998{
2999 dictitem_T *di_refresh;
3000 dictitem_T *di_words;
3001
3002 // Check for optional "refresh" item.
3003 compl_opt_refresh_always = FALSE;
3004 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3005 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3006 {
3007 char_u *v = di_refresh->di_tv.vval.v_string;
3008
3009 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3010 compl_opt_refresh_always = TRUE;
3011 }
3012
3013 // Add completions from a "words" list.
3014 di_words = dict_find(dict, (char_u *)"words", 5);
3015 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3016 ins_compl_add_list(di_words->di_tv.vval.v_list);
3017}
3018
3019/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003020 * Start completion for the complete() function.
3021 * "startcol" is where the matched text starts (1 is first column).
3022 * "list" is the list of matches.
3023 */
3024 static void
3025set_completion(colnr_T startcol, list_T *list)
3026{
3027 int save_w_wrow = curwin->w_wrow;
3028 int save_w_leftcol = curwin->w_leftcol;
3029 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003030 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003031 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3032 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3033 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003034
3035 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003036 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003037 ins_compl_prep(' ');
3038 ins_compl_clear();
3039 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003040 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003041
3042 compl_direction = FORWARD;
3043 if (startcol > curwin->w_cursor.col)
3044 startcol = curwin->w_cursor.col;
3045 compl_col = startcol;
3046 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3047 // compl_pattern doesn't need to be set
John Marriott5e6ea922024-11-23 14:01:57 +01003048 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col, (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003049 if (p_ic)
3050 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003051 if (compl_orig_text.string == NULL)
3052 {
3053 compl_orig_text.length = 0;
3054 return;
3055 }
3056 compl_orig_text.length = (size_t)compl_length;
3057 if (ins_compl_add(compl_orig_text.string,
3058 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3059 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003060 return;
3061
3062 ctrl_x_mode = CTRL_X_EVAL;
3063
3064 ins_compl_add_list(list);
3065 compl_matches = ins_compl_make_cyclic();
3066 compl_started = TRUE;
3067 compl_used_match = TRUE;
3068 compl_cont_status = 0;
3069
3070 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003071 int no_select = compl_no_select || compl_longest;
3072 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003073 {
3074 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003075 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003076 // Down/Up has no real effect.
3077 ins_complete(K_UP, FALSE);
3078 }
3079 else
3080 ins_complete(Ctrl_N, FALSE);
3081 compl_enter_selects = compl_no_insert;
3082
3083 // Lazily show the popup menu, unless we got interrupted.
3084 if (!compl_interrupted)
3085 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003086 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003087 out_flush();
3088}
3089
3090/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003091 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003092 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003093 void
3094f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003095{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003096 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003097
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003098 if (in_vim9script()
3099 && (check_for_number_arg(argvars, 0) == FAIL
3100 || check_for_list_arg(argvars, 1) == FAIL))
3101 return;
3102
Bram Moolenaar24959102022-05-07 20:01:16 +01003103 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003104 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003105 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003106 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003107 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003108
3109 // Check for undo allowed here, because if something was already inserted
3110 // the line was already saved for undo and this check isn't done.
3111 if (!undo_allowed())
3112 return;
3113
Bram Moolenaard83392a2022-09-01 12:22:46 +01003114 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003115 {
3116 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3117 if (startcol > 0)
3118 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003119 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003120}
3121
3122/*
3123 * "complete_add()" function
3124 */
3125 void
3126f_complete_add(typval_T *argvars, typval_T *rettv)
3127{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003128 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003129 return;
3130
Bram Moolenaar440cf092021-04-03 20:13:30 +02003131 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003132}
3133
3134/*
3135 * "complete_check()" function
3136 */
3137 void
3138f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3139{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003140 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003141 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003142
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003143 ins_compl_check_keys(0, TRUE);
3144 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003145
3146 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003147}
3148
3149/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003150 * Return Insert completion mode name string
3151 */
3152 static char_u *
3153ins_compl_mode(void)
3154{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003155 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003156 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3157
3158 return (char_u *)"";
3159}
3160
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003161/*
3162 * Assign the sequence number to all the completion matches which don't have
3163 * one assigned yet.
3164 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003165 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003166ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003167{
3168 int number = 0;
3169 compl_T *match;
3170
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003171 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003172 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003173 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003174 // This should normally succeed already at the first loop
3175 // cycle, so it's fast!
3176 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003177 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003178 if (match->cp_number != -1)
3179 {
3180 number = match->cp_number;
3181 break;
3182 }
3183 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003184 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003185 for (match = match->cp_next;
3186 match != NULL && match->cp_number == -1;
3187 match = match->cp_next)
3188 match->cp_number = ++number;
3189 }
3190 else // BACKWARD
3191 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003192 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003193 // number. This should normally succeed already at the
3194 // first loop cycle, so it's fast!
3195 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003196 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003197 if (match->cp_number != -1)
3198 {
3199 number = match->cp_number;
3200 break;
3201 }
3202 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003203 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003204 for (match = match->cp_prev; match
3205 && match->cp_number == -1;
3206 match = match->cp_prev)
3207 match->cp_number = ++number;
3208 }
3209}
3210
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003211/*
3212 * Get complete information
3213 */
3214 static void
3215get_complete_info(list_T *what_list, dict_T *retdict)
3216{
3217 int ret = OK;
3218 listitem_T *item;
3219#define CI_WHAT_MODE 0x01
3220#define CI_WHAT_PUM_VISIBLE 0x02
3221#define CI_WHAT_ITEMS 0x04
3222#define CI_WHAT_SELECTED 0x08
3223#define CI_WHAT_INSERTED 0x10
3224#define CI_WHAT_ALL 0xff
3225 int what_flag;
3226
3227 if (what_list == NULL)
3228 what_flag = CI_WHAT_ALL;
3229 else
3230 {
3231 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003232 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003233 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003234 {
3235 char_u *what = tv_get_string(&item->li_tv);
3236
3237 if (STRCMP(what, "mode") == 0)
3238 what_flag |= CI_WHAT_MODE;
3239 else if (STRCMP(what, "pum_visible") == 0)
3240 what_flag |= CI_WHAT_PUM_VISIBLE;
3241 else if (STRCMP(what, "items") == 0)
3242 what_flag |= CI_WHAT_ITEMS;
3243 else if (STRCMP(what, "selected") == 0)
3244 what_flag |= CI_WHAT_SELECTED;
3245 else if (STRCMP(what, "inserted") == 0)
3246 what_flag |= CI_WHAT_INSERTED;
3247 }
3248 }
3249
3250 if (ret == OK && (what_flag & CI_WHAT_MODE))
3251 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3252
3253 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3254 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3255
Girish Palya8950bf72024-03-20 20:07:29 +01003256 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003257 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003258 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003259 dict_T *di;
3260 compl_T *match;
3261 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003262
Girish Palya8950bf72024-03-20 20:07:29 +01003263 if (what_flag & CI_WHAT_ITEMS)
3264 {
3265 li = list_alloc();
3266 if (li == NULL)
3267 return;
3268 ret = dict_add_list(retdict, "items", li);
3269 }
3270 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3271 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3272 ins_compl_update_sequence_numbers();
3273 if (ret == OK && compl_first_match != NULL)
3274 {
3275 int list_idx = 0;
3276 match = compl_first_match;
3277 do
3278 {
3279 if (!match_at_original_text(match))
3280 {
3281 if (what_flag & CI_WHAT_ITEMS)
3282 {
3283 di = dict_alloc();
3284 if (di == NULL)
3285 return;
3286 ret = list_append_dict(li, di);
3287 if (ret != OK)
3288 return;
John Marriott5e6ea922024-11-23 14:01:57 +01003289 dict_add_string(di, "word", match->cp_str.string);
Girish Palya8950bf72024-03-20 20:07:29 +01003290 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3291 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3292 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3293 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3294 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3295 // Add an empty string for backwards compatibility
3296 dict_add_string(di, "user_data", (char_u *)"");
3297 else
3298 dict_add_tv(di, "user_data", &match->cp_user_data);
3299 }
3300 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3301 selected_idx = list_idx;
3302 list_idx += 1;
3303 }
3304 match = match->cp_next;
3305 }
3306 while (match != NULL && !is_first_match(match));
3307 }
3308 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3309 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003310 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003311
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003312 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3313 {
3314 // TODO
3315 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003316}
3317
3318/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003319 * "complete_info()" function
3320 */
3321 void
3322f_complete_info(typval_T *argvars, typval_T *rettv)
3323{
3324 list_T *what_list = NULL;
3325
Bram Moolenaar93a10962022-06-16 11:42:09 +01003326 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003327 return;
3328
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003329 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3330 return;
3331
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003332 if (argvars[0].v_type != VAR_UNKNOWN)
3333 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003334 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003335 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003336 what_list = argvars[0].vval.v_list;
3337 }
3338 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003339}
3340#endif
3341
3342/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003343 * Returns TRUE when using a user-defined function for thesaurus completion.
3344 */
3345 static int
3346thesaurus_func_complete(int type UNUSED)
3347{
3348#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003349 return type == CTRL_X_THESAURUS
3350 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003351#else
3352 return FALSE;
3353#endif
3354}
3355
3356/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003357 * Return value of process_next_cpt_value()
3358 */
3359enum
3360{
3361 INS_COMPL_CPT_OK = 1,
3362 INS_COMPL_CPT_CONT,
3363 INS_COMPL_CPT_END
3364};
3365
3366/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003367 * state information used for getting the next set of insert completion
3368 * matches.
3369 */
3370typedef struct
3371{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003372 char_u *e_cpt_copy; // copy of 'complete'
3373 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003374 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003375 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003376 pos_T prev_match_pos; // previous match position
3377 int set_match_pos; // save first_match_pos/last_match_pos
3378 pos_T first_match_pos; // first match position
3379 pos_T last_match_pos; // last match position
3380 int found_all; // found all matches of a certain type.
3381 char_u *dict; // dictionary file to search
3382 int dict_f; // "dict" is an exact file name or not
3383} ins_compl_next_state_T;
3384
3385/*
3386 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003387 *
3388 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003389 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003390 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003391 * st->found_all - all matches of this type are found
3392 * st->ins_buf - search for completions in this buffer
3393 * st->first_match_pos - position of the first completion match
3394 * st->last_match_pos - position of the last completion match
3395 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003396 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003397 * st->dict - name of the dictionary or thesaurus file to search
3398 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003399 *
3400 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003401 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3402 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003403 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003404 */
3405 static int
3406process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003407 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003408 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003409 pos_T *start_match_pos,
3410 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003411{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003412 int compl_type = -1;
3413 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003414
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003415 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003416
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003417 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3418 st->e_cpt++;
3419
3420 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003421 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003422 st->ins_buf = curbuf;
3423 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003424 // Move the cursor back one character so that ^N can match the
3425 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003426 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003427 {
3428 // Move the cursor to after the last character in the
3429 // buffer, so that word at start of buffer is found
3430 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003431 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003432 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003433 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003434 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003435 compl_type = 0;
3436
3437 // Remember the first match so that the loop stops when we
3438 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003439 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003440 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003441 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003442 && (st->ins_buf = ins_compl_next_buf(
3443 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003444 {
3445 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003446 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003447 {
3448 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003449 st->first_match_pos.col = st->last_match_pos.col = 0;
3450 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3451 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003452 compl_type = 0;
3453 }
3454 else // unloaded buffer, scan like dictionary
3455 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003456 st->found_all = TRUE;
3457 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003458 {
3459 status = INS_COMPL_CPT_CONT;
3460 goto done;
3461 }
3462 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003463 st->dict = st->ins_buf->b_fname;
3464 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003465 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003466 if (!shortmess(SHM_COMPLETIONSCAN))
3467 {
3468 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3469 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3470 st->ins_buf->b_fname == NULL
3471 ? buf_spname(st->ins_buf)
3472 : st->ins_buf->b_sfname == NULL
3473 ? st->ins_buf->b_fname
3474 : st->ins_buf->b_sfname);
3475 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3476 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003477 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003478 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003479 status = INS_COMPL_CPT_END;
3480 else
3481 {
3482 if (ctrl_x_mode_line_or_eval())
3483 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003484 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003485 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003486 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003487 compl_type = CTRL_X_DICTIONARY;
3488 else
3489 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003490 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003491 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003492 st->dict = st->e_cpt;
3493 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003494 }
3495 }
3496#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003497 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003498 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003499 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003500 compl_type = CTRL_X_PATH_DEFINES;
3501#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003502 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003503 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003504 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003505 if (!shortmess(SHM_COMPLETIONSCAN))
3506 {
3507 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3508 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3509 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3510 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003511 }
3512 else
3513 compl_type = -1;
3514
3515 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003516 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003517
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003518 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003519 if (compl_type == -1)
3520 status = INS_COMPL_CPT_CONT;
3521 }
3522
3523done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003524 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003525 return status;
3526}
3527
3528#ifdef FEAT_FIND_ID
3529/*
3530 * Get the next set of identifiers or defines matching "compl_pattern" in
3531 * included files.
3532 */
3533 static void
3534get_next_include_file_completion(int compl_type)
3535{
John Marriott5e6ea922024-11-23 14:01:57 +01003536 find_pattern_in_path(compl_pattern.string, compl_direction,
3537 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003538 (compl_type == CTRL_X_PATH_DEFINES
3539 && !(compl_cont_status & CONT_SOL))
3540 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003541 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003542}
3543#endif
3544
3545/*
3546 * Get the next set of words matching "compl_pattern" in dictionary or
3547 * thesaurus files.
3548 */
3549 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003550get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003551{
3552#ifdef FEAT_COMPL_FUNC
3553 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003554 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003555 else
3556#endif
3557 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003558 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003559 : (compl_type == CTRL_X_THESAURUS
3560 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3561 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003562 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003563 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003564 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003565}
3566
3567/*
3568 * Get the next set of tag names matching "compl_pattern".
3569 */
3570 static void
3571get_next_tag_completion(void)
3572{
3573 int save_p_ic;
3574 char_u **matches;
3575 int num_matches;
3576
3577 // set p_ic according to p_ic, p_scs and pat for find_tags().
3578 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003579 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003580
3581 // Find up to TAG_MANY matches. Avoids that an enormous number
3582 // of matches is found when compl_pattern is empty
3583 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003584 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003585 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003586 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003587 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3588 ins_compl_add_matches(num_matches, matches, p_ic);
3589 g_tag_at_cursor = FALSE;
3590 p_ic = save_p_ic;
3591}
3592
3593/*
glepnir8159fb12024-07-17 20:32:54 +02003594 * Compare function for qsort
3595 */
3596static int compare_scores(const void *a, const void *b)
3597{
3598 int idx_a = *(const int *)a;
3599 int idx_b = *(const int *)b;
3600 int score_a = compl_fuzzy_scores[idx_a];
3601 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003602 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3603 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003604}
3605
3606/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003607 * Get the next set of filename matching "compl_pattern".
3608 */
3609 static void
3610get_next_filename_completion(void)
3611{
3612 char_u **matches;
3613 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003614 char_u *ptr;
3615 garray_T fuzzy_indices;
3616 int i;
3617 int score;
3618 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003619 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003620 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3621 char_u **sorted_matches;
3622 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003623 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003624
glepnirb9de1a02024-08-02 19:14:38 +02003625#ifdef BACKSLASH_IN_FILENAME
3626 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3627 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3628#else
3629 char pathsep = PATHSEP;
3630#endif
3631
glepnir8159fb12024-07-17 20:32:54 +02003632 if (in_fuzzy)
3633 {
glepnirb9de1a02024-08-02 19:14:38 +02003634#ifdef BACKSLASH_IN_FILENAME
3635 if (curbuf->b_p_csl[0] == 's')
3636 {
John Marriott5e6ea922024-11-23 14:01:57 +01003637 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003638 {
3639 if (leader[i] == '\\')
3640 leader[i] = '/';
3641 }
3642 }
3643 else if (curbuf->b_p_csl[0] == 'b')
3644 {
John Marriott5e6ea922024-11-23 14:01:57 +01003645 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003646 {
3647 if (leader[i] == '/')
3648 leader[i] = '\\';
3649 }
3650 }
3651#endif
3652 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003653 if (last_sep == NULL)
3654 {
3655 // No path separator or separator is the last character,
3656 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003657 VIM_CLEAR_STRING(compl_pattern);
3658 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3659 if (compl_pattern.string == NULL)
3660 return;
3661 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003662 }
3663 else if (*(last_sep + 1) == '\0')
3664 in_fuzzy = FALSE;
3665 else
3666 {
3667 // Split leader into path and file parts
3668 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003669 char_u *path_with_wildcard;
3670
3671 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003672 if (path_with_wildcard != NULL)
3673 {
John Marriott5e6ea922024-11-23 14:01:57 +01003674 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3675 VIM_CLEAR_STRING(compl_pattern);
3676 compl_pattern.string = path_with_wildcard;
3677 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003678
3679 // Move leader to the file part
3680 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003681 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003682 }
3683 }
glepnir8159fb12024-07-17 20:32:54 +02003684 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003685
John Marriott5e6ea922024-11-23 14:01:57 +01003686 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003687 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3688 return;
3689
3690 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003691 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003692#ifdef BACKSLASH_IN_FILENAME
3693 if (curbuf->b_p_csl[0] != NUL)
3694 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003695 for (i = 0; i < num_matches; ++i)
3696 {
glepnir8159fb12024-07-17 20:32:54 +02003697 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003698 while (*ptr != NUL)
3699 {
3700 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3701 *ptr = '/';
3702 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3703 *ptr = '\\';
3704 ptr += (*mb_ptr2len)(ptr);
3705 }
3706 }
3707 }
3708#endif
glepnir8159fb12024-07-17 20:32:54 +02003709
3710 if (in_fuzzy)
3711 {
3712 ga_init2(&fuzzy_indices, sizeof(int), 10);
3713 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3714
3715 for (i = 0; i < num_matches; i++)
3716 {
3717 ptr = matches[i];
3718 score = fuzzy_match_str(ptr, leader);
3719 if (score > 0)
3720 {
3721 if (ga_grow(&fuzzy_indices, 1) == OK)
3722 {
3723 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3724 compl_fuzzy_scores[i] = score;
3725 fuzzy_indices.ga_len++;
3726 }
3727 }
3728 }
3729
Christian Brabandt220474d2024-07-20 13:26:44 +02003730 // prevent qsort from deref NULL pointer
3731 if (fuzzy_indices.ga_len > 0)
3732 {
3733 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3734 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003735
Christian Brabandt220474d2024-07-20 13:26:44 +02003736 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3737 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3738 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003739
Christian Brabandt220474d2024-07-20 13:26:44 +02003740 FreeWild(num_matches, matches);
3741 matches = sorted_matches;
3742 num_matches = fuzzy_indices.ga_len;
3743 }
glepnir6b6280c2024-07-27 16:25:45 +02003744 else if (leader_len > 0)
3745 {
3746 FreeWild(num_matches, matches);
3747 num_matches = 0;
3748 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003749
glepnir8159fb12024-07-17 20:32:54 +02003750 vim_free(compl_fuzzy_scores);
3751 ga_clear(&fuzzy_indices);
3752 }
3753
glepnir6b6280c2024-07-27 16:25:45 +02003754 if (num_matches > 0)
3755 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003756}
3757
3758/*
3759 * Get the next set of command-line completions matching "compl_pattern".
3760 */
3761 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003762get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003763{
3764 char_u **matches;
3765 int num_matches;
3766
John Marriott5e6ea922024-11-23 14:01:57 +01003767 if (expand_cmdline(&compl_xp, compl_pattern.string,
3768 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003769 ins_compl_add_matches(num_matches, matches, FALSE);
3770}
3771
3772/*
3773 * Get the next set of spell suggestions matching "compl_pattern".
3774 */
3775 static void
3776get_next_spell_completion(linenr_T lnum UNUSED)
3777{
3778#ifdef FEAT_SPELL
3779 char_u **matches;
3780 int num_matches;
3781
John Marriott5e6ea922024-11-23 14:01:57 +01003782 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003783 if (num_matches > 0)
3784 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003785 else
3786 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003787#endif
3788}
3789
3790/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003791 * Return the next word or line from buffer "ins_buf" at position
3792 * "cur_match_pos" for completion. The length of the match is set in "len".
3793 */
3794 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003795ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003796 buf_T *ins_buf, // buffer being scanned
3797 pos_T *cur_match_pos, // current match position
3798 int *match_len,
3799 int *cont_s_ipos) // next ^X<> will set initial_pos
3800{
3801 char_u *ptr;
3802 int len;
3803
3804 *match_len = 0;
3805 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3806 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003807 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003808 if (ctrl_x_mode_line_or_eval())
3809 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003810 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003811 {
3812 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3813 return NULL;
3814 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003815 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003816 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003817 {
3818 char_u *tmp_ptr = ptr;
3819
3820 ptr = skipwhite(tmp_ptr);
3821 len -= (int)(ptr - tmp_ptr);
3822 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003823 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003824 }
3825 else
3826 {
3827 char_u *tmp_ptr = ptr;
3828
John Marriott5e6ea922024-11-23 14:01:57 +01003829 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003830 {
3831 tmp_ptr += compl_length;
3832 // Skip if already inside a word.
3833 if (vim_iswordp(tmp_ptr))
3834 return NULL;
3835 // Find start of next word.
3836 tmp_ptr = find_word_start(tmp_ptr);
3837 }
3838 // Find end of this word.
3839 tmp_ptr = find_word_end(tmp_ptr);
3840 len = (int)(tmp_ptr - ptr);
3841
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003842 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003843 {
3844 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3845 {
3846 // Try next line, if any. the new word will be
3847 // "join" as if the normal command "J" was used.
3848 // IOSIZE is always greater than
3849 // compl_length, so the next STRNCPY always
3850 // works -- Acevedo
3851 STRNCPY(IObuff, ptr, len);
3852 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3853 tmp_ptr = ptr = skipwhite(ptr);
3854 // Find start of next word.
3855 tmp_ptr = find_word_start(tmp_ptr);
3856 // Find end of next word.
3857 tmp_ptr = find_word_end(tmp_ptr);
3858 if (tmp_ptr > ptr)
3859 {
3860 if (*ptr != ')' && IObuff[len - 1] != TAB)
3861 {
3862 if (IObuff[len - 1] != ' ')
3863 IObuff[len++] = ' ';
3864 // IObuf =~ "\k.* ", thus len >= 2
3865 if (p_js
3866 && (IObuff[len - 2] == '.'
3867 || (vim_strchr(p_cpo, CPO_JOINSP)
3868 == NULL
3869 && (IObuff[len - 2] == '?'
3870 || IObuff[len - 2] == '!'))))
3871 IObuff[len++] = ' ';
3872 }
3873 // copy as much as possible of the new word
3874 if (tmp_ptr - ptr >= IOSIZE - len)
3875 tmp_ptr = ptr + IOSIZE - len - 1;
3876 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3877 len += (int)(tmp_ptr - ptr);
3878 *cont_s_ipos = TRUE;
3879 }
3880 IObuff[len] = NUL;
3881 ptr = IObuff;
3882 }
3883 if (len == compl_length)
3884 return NULL;
3885 }
3886 }
3887
3888 *match_len = len;
3889 return ptr;
3890}
3891
3892/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003893 * Get the next set of words matching "compl_pattern" for default completion(s)
3894 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003895 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3896 * position "st->start_pos" in the "compl_direction" direction. If
3897 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3898 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003899 * Returns OK if a new next match is found, otherwise returns FAIL.
3900 */
3901 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003902get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003903{
3904 int found_new_match = FAIL;
3905 int save_p_scs;
3906 int save_p_ws;
3907 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003908 char_u *ptr = NULL;
3909 int len = 0;
3910 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3911 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003912
3913 // If 'infercase' is set, don't use 'smartcase' here
3914 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003915 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003916 p_scs = FALSE;
3917
3918 // Buffers other than curbuf are scanned from the beginning or the
3919 // end but never from the middle, thus setting nowrapscan in this
3920 // buffer is a good idea, on the other hand, we always set
3921 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3922 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003923 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003924 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003925 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003926 p_ws = TRUE;
3927 looped_around = FALSE;
3928 for (;;)
3929 {
3930 int cont_s_ipos = FALSE;
3931
3932 ++msg_silent; // Don't want messages for wrapscan.
3933
3934 // ctrl_x_mode_line_or_eval() || word-wise search that
3935 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003936 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003937 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01003938 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02003939 else if (in_fuzzy)
3940 found_new_match = search_for_fuzzy_match(st->ins_buf,
3941 st->cur_match_pos, leader, compl_direction,
3942 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003943 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003944 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01003945 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02003946 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003947 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003948 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003949 {
3950 // set "compl_started" even on fail
3951 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003952 st->first_match_pos = *st->cur_match_pos;
3953 st->last_match_pos = *st->cur_match_pos;
3954 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003955 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003956 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3957 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003958 {
3959 found_new_match = FAIL;
3960 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003961 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003962 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3963 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3964 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003965 {
3966 if (looped_around)
3967 found_new_match = FAIL;
3968 else
3969 looped_around = TRUE;
3970 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003971 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003972 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3973 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3974 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003975 {
3976 if (looped_around)
3977 found_new_match = FAIL;
3978 else
3979 looped_around = TRUE;
3980 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003981 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003982 if (found_new_match == FAIL)
3983 break;
3984
3985 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003986 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003987 && start_pos->lnum == st->cur_match_pos->lnum
3988 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003989 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003990
glepnir8159fb12024-07-17 20:32:54 +02003991 if (!in_fuzzy)
3992 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3993 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003994 if (ptr == NULL)
3995 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003996
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003997 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003998 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003999 0, cont_s_ipos) != NOTDONE)
4000 {
4001 found_new_match = OK;
4002 break;
4003 }
4004 }
4005 p_scs = save_p_scs;
4006 p_ws = save_p_ws;
4007
4008 return found_new_match;
4009}
4010
4011/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004012 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004013 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004014 */
4015 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004016get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004017{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004018 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004019
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004020 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004021 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004022 case -1:
4023 break;
4024#ifdef FEAT_FIND_ID
4025 case CTRL_X_PATH_PATTERNS:
4026 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004027 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004028 break;
4029#endif
4030
4031 case CTRL_X_DICTIONARY:
4032 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004033 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4034 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004035 break;
4036
4037 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004038 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004039 break;
4040
4041 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004042 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004043 break;
4044
4045 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004046 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004047 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004048 break;
4049
4050#ifdef FEAT_COMPL_FUNC
4051 case CTRL_X_FUNCTION:
4052 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004053 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004054 break;
4055#endif
4056
4057 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004058 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004059 break;
4060
4061 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004062 found_new_match = get_next_default_completion(st, ini);
4063 if (found_new_match == FAIL && st->ins_buf == curbuf)
4064 st->found_all = TRUE;
4065 }
4066
4067 // check if compl_curr_match has changed, (e.g. other type of
4068 // expansion added something)
4069 if (type != 0 && compl_curr_match != compl_old_match)
4070 found_new_match = OK;
4071
4072 return found_new_match;
4073}
4074
4075/*
4076 * Get the next expansion(s), using "compl_pattern".
4077 * The search starts at position "ini" in curbuf and in the direction
4078 * compl_direction.
4079 * When "compl_started" is FALSE start at that position, otherwise continue
4080 * where we stopped searching before.
4081 * This may return before finding all the matches.
4082 * Return the total number of matches or -1 if still unknown -- Acevedo
4083 */
4084 static int
4085ins_compl_get_exp(pos_T *ini)
4086{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004087 static ins_compl_next_state_T st;
4088 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004089 int i;
4090 int found_new_match;
4091 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004092 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004093
4094 if (!compl_started)
4095 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004096 buf_T *buf;
4097
4098 FOR_ALL_BUFFERS(buf)
4099 buf->b_scanned = 0;
4100 if (!st_cleared)
4101 {
4102 CLEAR_FIELD(st);
4103 st_cleared = TRUE;
4104 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004105 st.found_all = FALSE;
4106 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004107 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004108 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004109 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4110 ? (char_u *)"." : curbuf->b_p_cpt);
4111 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004112 st.last_match_pos = st.first_match_pos = *ini;
4113 }
4114 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4115 st.ins_buf = curbuf; // In case the buffer was wiped out.
4116
4117 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004118 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004119 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004120
4121 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4122 for (;;)
4123 {
4124 found_new_match = FAIL;
4125 st.set_match_pos = FALSE;
4126
4127 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4128 // or if found_all says this entry is done. For ^X^L only use the
4129 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004130 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004131 && (!compl_started || st.found_all))
4132 {
glepnir8159fb12024-07-17 20:32:54 +02004133 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004134
4135 if (status == INS_COMPL_CPT_END)
4136 break;
4137 if (status == INS_COMPL_CPT_CONT)
4138 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004139 }
4140
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004141 // If complete() was called then compl_pattern has been reset. The
4142 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004143 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004144 break;
4145
4146 // get the next set of completion matches
4147 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004148
4149 // break the loop for specialized modes (use 'complete' just for the
4150 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4151 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004152 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4153 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004154 {
4155 if (got_int)
4156 break;
4157 // Fill the popup menu as soon as possible.
4158 if (type != -1)
4159 ins_compl_check_keys(0, FALSE);
4160
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004161 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004162 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4163 break;
4164 compl_started = TRUE;
4165 }
4166 else
4167 {
4168 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004169 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004170 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004171
4172 compl_started = FALSE;
4173 }
4174 }
4175 compl_started = TRUE;
4176
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004177 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004178 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004179 found_new_match = FAIL;
4180
4181 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004182 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004183 && !ctrl_x_mode_line_or_eval()))
4184 i = ins_compl_make_cyclic();
4185
4186 if (compl_old_match != NULL)
4187 {
4188 // If several matches were added (FORWARD) or the search failed and has
4189 // just been made cyclic then we have to move compl_curr_match to the
4190 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004191 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004192 : compl_old_match->cp_prev;
4193 if (compl_curr_match == NULL)
4194 compl_curr_match = compl_old_match;
4195 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004196 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004197
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004198 return i;
4199}
4200
4201/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004202 * Update "compl_shown_match" to the actually shown match, it may differ when
4203 * "compl_leader" is used to omit some of the matches.
4204 */
4205 static void
4206ins_compl_update_shown_match(void)
4207{
4208 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004209 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004210 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004211 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004212 compl_shown_match = compl_shown_match->cp_next;
4213
4214 // If we didn't find it searching forward, and compl_shows_dir is
4215 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004216 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004217 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004218 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004219 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004220 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004221 {
4222 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004223 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004224 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004225 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004226 compl_shown_match = compl_shown_match->cp_prev;
4227 }
4228}
4229
4230/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004231 * Delete the old text being completed.
4232 */
4233 void
4234ins_compl_delete(void)
4235{
4236 int col;
4237
4238 // In insert mode: Delete the typed part.
4239 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004240 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004241 if ((int)curwin->w_cursor.col > col)
4242 {
4243 if (stop_arrow() == FAIL)
4244 return;
4245 backspace_until_column(col);
4246 }
4247
4248 // TODO: is this sufficient for redrawing? Redrawing everything causes
4249 // flicker, thus we can't do that.
4250 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004251#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004252 // clear v:completed_item
4253 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004254#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004255}
4256
4257/*
4258 * Insert the new text being completed.
4259 * "in_compl_func" is TRUE when called from complete_check().
4260 */
4261 void
4262ins_compl_insert(int in_compl_func)
4263{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004264 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004265
4266 // Make sure we don't go over the end of the string, this can happen with
4267 // illegal bytes.
John Marriott5e6ea922024-11-23 14:01:57 +01004268 if (compl_len < (int)compl_shown_match->cp_str.length)
4269 ins_bytes(compl_shown_match->cp_str.string + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004270 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004271 compl_used_match = FALSE;
4272 else
4273 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004274#ifdef FEAT_EVAL
4275 {
4276 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4277
4278 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4279 }
4280#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004281 if (!in_compl_func)
4282 compl_curr_match = compl_shown_match;
4283}
4284
4285/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004286 * show the file name for the completion match (if any). Truncate the file
4287 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004288 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004289 static void
4290ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004291{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004292 char *lead = _("match in file");
4293 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4294 char_u *s;
4295 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004296
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004297 if (space <= 0)
4298 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004299
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004300 // We need the tail that fits. With double-byte encoding going
4301 // back from the end is very slow, thus go from the start and keep
4302 // the text that fits in "space" between "s" and "e".
4303 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004304 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004305 space -= ptr2cells(e);
4306 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004307 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004308 space += ptr2cells(s);
4309 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004310 }
4311 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004312 msg_hist_off = TRUE;
4313 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4314 s > compl_shown_match->cp_fname ? "<" : "", s);
4315 msg((char *)IObuff);
4316 msg_hist_off = FALSE;
4317 redraw_cmdline = FALSE; // don't overwrite!
4318}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004319
glepnirdca57fb2024-06-04 22:01:21 +02004320/*
zeertzjq551d8c32024-06-05 19:53:32 +02004321 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004322 */
glepnira218cc62024-06-03 19:32:39 +02004323 static compl_T *
4324find_comp_when_fuzzy(void)
4325{
4326 int score;
4327 char_u* str;
4328 int target_idx = -1;
4329 int is_forward = compl_shows_dir_forward();
4330 int is_backward = compl_shows_dir_backward();
4331 compl_T *comp = NULL;
4332
glepnir43eef882024-06-19 20:20:48 +02004333 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004334 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004335 return compl_first_match != compl_shown_match ? compl_first_match :
4336 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004337
4338 if (is_forward)
4339 target_idx = compl_selected_item + 1;
4340 else if (is_backward)
4341 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004342 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004343
4344 score = compl_match_array[target_idx].pum_score;
4345 str = compl_match_array[target_idx].pum_text;
4346
4347 comp = compl_first_match;
4348 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004349 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004350 return comp;
4351 comp = comp->cp_next;
4352 } while (comp != NULL && !is_first_match(comp));
4353
4354 return NULL;
4355}
4356
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004357/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004358 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004359 * times. The number of matches found is returned in 'num_matches'.
4360 *
4361 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4362 * get more completions. If it is FALSE, then do nothing when there are no more
4363 * completions in the given direction.
4364 *
4365 * If "advance" is TRUE, then completion will move to the first match.
4366 * Otherwise, the original text will be shown.
4367 *
4368 * Returns OK on success and -1 if the number of matches are unknown.
4369 */
4370 static int
4371find_next_completion_match(
4372 int allow_get_expansion,
4373 int todo, // repeat completion this many times
4374 int advance,
4375 int *num_matches)
4376{
4377 int found_end = FALSE;
4378 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004379 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004380 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4381 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004382
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004383 while (--todo >= 0)
4384 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004385 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004386 {
glepniraced8c22024-06-15 15:13:05 +02004387 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4388 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004389 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004390 && (is_first_match(compl_shown_match->cp_next)
4391 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004392 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004393 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004394 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004395 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004396 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004397 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4398 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004399 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004400 }
4401 else
4402 {
4403 if (!allow_get_expansion)
4404 {
4405 if (advance)
4406 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004407 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004408 compl_pending -= todo + 1;
4409 else
4410 compl_pending += todo + 1;
4411 }
4412 return -1;
4413 }
4414
4415 if (!compl_no_select && advance)
4416 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004417 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004418 --compl_pending;
4419 else
4420 ++compl_pending;
4421 }
4422
4423 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004424 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004425
4426 // handle any pending completions
4427 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004428 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004429 {
4430 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4431 {
4432 compl_shown_match = compl_shown_match->cp_next;
4433 --compl_pending;
4434 }
4435 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4436 {
4437 compl_shown_match = compl_shown_match->cp_prev;
4438 ++compl_pending;
4439 }
4440 else
4441 break;
4442 }
4443 found_end = FALSE;
4444 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004445 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004446 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004447 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004448 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004449 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004450 ++todo;
4451 else
4452 // Remember a matching item.
4453 found_compl = compl_shown_match;
4454
4455 // Stop at the end of the list when we found a usable match.
4456 if (found_end)
4457 {
4458 if (found_compl != NULL)
4459 {
4460 compl_shown_match = found_compl;
4461 break;
4462 }
4463 todo = 1; // use first usable match after wrapping around
4464 }
4465 }
4466
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004467 return OK;
4468}
4469
4470/*
4471 * Fill in the next completion in the current direction.
4472 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4473 * get more completions. If it is FALSE, then we just do nothing when there
4474 * are no more completions in a given direction. The latter case is used when
4475 * we are still in the middle of finding completions, to allow browsing
4476 * through the ones found so far.
4477 * Return the total number of matches, or -1 if still unknown -- webb.
4478 *
4479 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4480 * compl_shown_match here.
4481 *
4482 * Note that this function may be called recursively once only. First with
4483 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4484 * calls this function with "allow_get_expansion" FALSE.
4485 */
4486 static int
4487ins_compl_next(
4488 int allow_get_expansion,
4489 int count, // repeat completion this many times; should
4490 // be at least 1
4491 int insert_match, // Insert the newly selected match
4492 int in_compl_func) // called from complete_check()
4493{
4494 int num_matches = -1;
4495 int todo = count;
4496 int advance;
4497 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004498 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004499 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004500 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4501 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004502
4503 // When user complete function return -1 for findstart which is next
4504 // time of 'always', compl_shown_match become NULL.
4505 if (compl_shown_match == NULL)
4506 return -1;
4507
John Marriott5e6ea922024-11-23 14:01:57 +01004508 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004509 && !match_at_original_text(compl_shown_match)
4510 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004511 // Update "compl_shown_match" to the actually shown match
4512 ins_compl_update_shown_match();
4513
4514 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004515 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004516 // Delete old text to be replaced
4517 ins_compl_delete();
4518
4519 // When finding the longest common text we stick at the original text,
4520 // don't let CTRL-N or CTRL-P move to the first match.
4521 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4522
4523 // When restarting the search don't insert the first match either.
4524 if (compl_restarting)
4525 {
4526 advance = FALSE;
4527 compl_restarting = FALSE;
4528 }
4529
4530 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4531 // around.
4532 if (find_next_completion_match(allow_get_expansion, todo, advance,
4533 &num_matches) == -1)
4534 return -1;
4535
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004536 if (curbuf != orig_curbuf)
4537 {
4538 // In case some completion function switched buffer, don't want to
4539 // insert the completion elsewhere.
4540 return -1;
4541 }
4542
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004543 // Insert the text of the new completion, or the compl_leader.
4544 if (compl_no_insert && !started)
4545 {
John Marriott5e6ea922024-11-23 14:01:57 +01004546 ins_bytes(compl_orig_text.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004547 compl_used_match = FALSE;
4548 }
4549 else if (insert_match)
4550 {
4551 if (!compl_get_longest || compl_used_match)
4552 ins_compl_insert(in_compl_func);
4553 else
John Marriott5e6ea922024-11-23 14:01:57 +01004554 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004555 }
4556 else
4557 compl_used_match = FALSE;
4558
4559 if (!allow_get_expansion)
4560 {
4561 // may undisplay the popup menu first
4562 ins_compl_upd_pum();
4563
4564 if (pum_enough_matches())
4565 // Will display the popup menu, don't redraw yet to avoid flicker.
4566 pum_call_update_screen();
4567 else
4568 // Not showing the popup menu yet, redraw to show the user what was
4569 // inserted.
4570 update_screen(0);
4571
4572 // display the updated popup menu
4573 ins_compl_show_pum();
4574#ifdef FEAT_GUI
4575 if (gui.in_use)
4576 {
4577 // Show the cursor after the match, not after the redrawn text.
4578 setcursor();
4579 out_flush_cursor(FALSE, FALSE);
4580 }
4581#endif
4582
4583 // Delete old text to be replaced, since we're still searching and
4584 // don't want to match ourselves!
4585 ins_compl_delete();
4586 }
4587
4588 // Enter will select a match when the match wasn't inserted and the popup
4589 // menu is visible.
4590 if (compl_no_insert && !started)
4591 compl_enter_selects = TRUE;
4592 else
4593 compl_enter_selects = !insert_match && compl_match_array != NULL;
4594
4595 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004596 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004597 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004598
4599 return num_matches;
4600}
4601
4602/*
4603 * Call this while finding completions, to check whether the user has hit a key
4604 * that should change the currently displayed completion, or exit completion
4605 * mode. Also, when compl_pending is not zero, show a completion as soon as
4606 * possible. -- webb
4607 * "frequency" specifies out of how many calls we actually check.
4608 * "in_compl_func" is TRUE when called from complete_check(), don't set
4609 * compl_curr_match.
4610 */
4611 void
4612ins_compl_check_keys(int frequency, int in_compl_func)
4613{
4614 static int count = 0;
4615 int c;
4616
4617 // Don't check when reading keys from a script, :normal or feedkeys().
4618 // That would break the test scripts. But do check for keys when called
4619 // from complete_check().
4620 if (!in_compl_func && (using_script() || ex_normal_busy))
4621 return;
4622
4623 // Only do this at regular intervals
4624 if (++count < frequency)
4625 return;
4626 count = 0;
4627
4628 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4629 // can't do its work correctly.
4630 c = vpeekc_any();
4631 if (c != NUL)
4632 {
4633 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4634 {
4635 c = safe_vgetc(); // Eat the character
4636 compl_shows_dir = ins_compl_key2dir(c);
4637 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4638 c != K_UP && c != K_DOWN, in_compl_func);
4639 }
4640 else
4641 {
4642 // Need to get the character to have KeyTyped set. We'll put it
4643 // back with vungetc() below. But skip K_IGNORE.
4644 c = safe_vgetc();
4645 if (c != K_IGNORE)
4646 {
4647 // Don't interrupt completion when the character wasn't typed,
4648 // e.g., when doing @q to replay keys.
4649 if (c != Ctrl_R && KeyTyped)
4650 compl_interrupted = TRUE;
4651
4652 vungetc(c);
4653 }
4654 }
4655 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004656 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004657 {
4658 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4659
4660 compl_pending = 0;
4661 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4662 }
4663}
4664
4665/*
4666 * Decide the direction of Insert mode complete from the key typed.
4667 * Returns BACKWARD or FORWARD.
4668 */
4669 static int
4670ins_compl_key2dir(int c)
4671{
4672 if (c == Ctrl_P || c == Ctrl_L
4673 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4674 return BACKWARD;
4675 return FORWARD;
4676}
4677
4678/*
4679 * Return TRUE for keys that are used for completion only when the popup menu
4680 * is visible.
4681 */
4682 static int
4683ins_compl_pum_key(int c)
4684{
4685 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4686 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4687 || c == K_UP || c == K_DOWN);
4688}
4689
4690/*
4691 * Decide the number of completions to move forward.
4692 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4693 */
4694 static int
4695ins_compl_key2count(int c)
4696{
4697 int h;
4698
4699 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4700 {
4701 h = pum_get_height();
4702 if (h > 3)
4703 h -= 2; // keep some context
4704 return h;
4705 }
4706 return 1;
4707}
4708
4709/*
4710 * Return TRUE if completion with "c" should insert the match, FALSE if only
4711 * to change the currently selected completion.
4712 */
4713 static int
4714ins_compl_use_match(int c)
4715{
4716 switch (c)
4717 {
4718 case K_UP:
4719 case K_DOWN:
4720 case K_PAGEDOWN:
4721 case K_KPAGEDOWN:
4722 case K_S_DOWN:
4723 case K_PAGEUP:
4724 case K_KPAGEUP:
4725 case K_S_UP:
4726 return FALSE;
4727 }
4728 return TRUE;
4729}
4730
4731/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004732 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4733 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004734 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004735 * Uses the global variables: compl_cont_status and ctrl_x_mode
4736 */
4737 static int
4738get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4739{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004740 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004741 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004742 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004743 {
4744 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4745 ;
4746 compl_col += ++startcol;
4747 compl_length = curs_col - startcol;
4748 }
4749 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004750 {
John Marriott5e6ea922024-11-23 14:01:57 +01004751 compl_pattern.string = str_foldcase(line + compl_col,
4752 compl_length, NULL, 0);
4753 if (compl_pattern.string == NULL)
4754 {
4755 compl_pattern.length = 0;
4756 return FAIL;
4757 }
4758 compl_pattern.length = STRLEN(compl_pattern.string);
4759 }
4760 else
4761 {
4762 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4763 if (compl_pattern.string == NULL)
4764 {
4765 compl_pattern.length = 0;
4766 return FAIL;
4767 }
4768 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02004769 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004770 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004771 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004772 {
4773 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004774 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01004775 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004776
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004777 if (!vim_iswordp(line + compl_col)
4778 || (compl_col > 0
4779 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004780 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004781 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004782 prefixlen = 0;
4783 }
John Marriott5e6ea922024-11-23 14:01:57 +01004784
4785 // we need up to 2 extra chars for the prefix
4786 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
4787 compl_pattern.string = alloc(n);
4788 if (compl_pattern.string == NULL)
4789 {
4790 compl_pattern.length = 0;
4791 return FAIL;
4792 }
4793 STRCPY((char *)compl_pattern.string, prefix);
4794 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004795 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004796 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004797 }
4798 else if (--startcol < 0
4799 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4800 {
John Marriott5e6ea922024-11-23 14:01:57 +01004801 size_t len = STRLEN_LITERAL("\\<\\k\\k");
4802
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004803 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01004804 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
4805 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004806 {
John Marriott5e6ea922024-11-23 14:01:57 +01004807 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004808 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004809 }
John Marriott5e6ea922024-11-23 14:01:57 +01004810 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004811 compl_col += curs_col;
4812 compl_length = 0;
4813 }
4814 else
4815 {
4816 // Search the point of change class of multibyte character
4817 // or not a word single byte character backward.
4818 if (has_mbyte)
4819 {
4820 int base_class;
4821 int head_off;
4822
4823 startcol -= (*mb_head_off)(line, line + startcol);
4824 base_class = mb_get_class(line + startcol);
4825 while (--startcol >= 0)
4826 {
4827 head_off = (*mb_head_off)(line, line + startcol);
4828 if (base_class != mb_get_class(line + startcol
4829 - head_off))
4830 break;
4831 startcol -= head_off;
4832 }
4833 }
4834 else
4835 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4836 ;
4837 compl_col += ++startcol;
4838 compl_length = (int)curs_col - startcol;
4839 if (compl_length == 1)
4840 {
4841 // Only match word with at least two chars -- webb
4842 // there's no need to call quote_meta,
4843 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01004844 compl_pattern.string = alloc(7);
4845 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004846 {
John Marriott5e6ea922024-11-23 14:01:57 +01004847 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004848 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004849 }
John Marriott5e6ea922024-11-23 14:01:57 +01004850 STRCPY((char *)compl_pattern.string, "\\<");
4851 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
4852 STRCAT((char *)compl_pattern.string, "\\k");
4853 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004854 }
4855 else
4856 {
John Marriott5e6ea922024-11-23 14:01:57 +01004857 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
4858
4859 compl_pattern.string = alloc(n);
4860 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004861 {
John Marriott5e6ea922024-11-23 14:01:57 +01004862 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004863 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004864 }
John Marriott5e6ea922024-11-23 14:01:57 +01004865 STRCPY((char *)compl_pattern.string, "\\<");
4866 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004867 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004868 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004869 }
4870 }
4871
4872 return OK;
4873}
4874
4875/*
4876 * Get the pattern, column and length for whole line completion or for the
4877 * complete() function.
4878 * Sets the global variables: compl_col, compl_length and compl_pattern.
4879 */
4880 static int
4881get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4882{
4883 compl_col = (colnr_T)getwhitecols(line);
4884 compl_length = (int)curs_col - (int)compl_col;
4885 if (compl_length < 0) // cursor in indent: empty pattern
4886 compl_length = 0;
4887 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004888 {
John Marriott5e6ea922024-11-23 14:01:57 +01004889 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
4890 NULL, 0);
4891 if (compl_pattern.string == NULL)
4892 {
4893 compl_pattern.length = 0;
4894 return FAIL;
4895 }
4896 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02004897 }
John Marriott5e6ea922024-11-23 14:01:57 +01004898 else
4899 {
4900 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4901 if (compl_pattern.string == NULL)
4902 {
4903 compl_pattern.length = 0;
4904 return FAIL;
4905 }
4906 compl_pattern.length = (size_t)compl_length;
4907 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004908
4909 return OK;
4910}
4911
4912/*
4913 * Get the pattern, column and length for filename completion.
4914 * Sets the global variables: compl_col, compl_length and compl_pattern.
4915 */
4916 static int
4917get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4918{
4919 // Go back to just before the first filename character.
4920 if (startcol > 0)
4921 {
4922 char_u *p = line + startcol;
4923
4924 MB_PTR_BACK(line, p);
4925 while (p > line && vim_isfilec(PTR2CHAR(p)))
4926 MB_PTR_BACK(line, p);
4927 if (p == line && vim_isfilec(PTR2CHAR(p)))
4928 startcol = 0;
4929 else
4930 startcol = (int)(p - line) + 1;
4931 }
4932
4933 compl_col += startcol;
4934 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01004935 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
4936 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004937 {
John Marriott5e6ea922024-11-23 14:01:57 +01004938 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004939 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004940 }
4941
John Marriott5e6ea922024-11-23 14:01:57 +01004942 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004943
4944 return OK;
4945}
4946
4947/*
4948 * Get the pattern, column and length for command-line completion.
4949 * Sets the global variables: compl_col, compl_length and compl_pattern.
4950 */
4951 static int
4952get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4953{
John Marriott5e6ea922024-11-23 14:01:57 +01004954 compl_pattern.string = vim_strnsave(line, curs_col);
4955 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004956 {
John Marriott5e6ea922024-11-23 14:01:57 +01004957 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004958 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004959 }
John Marriott5e6ea922024-11-23 14:01:57 +01004960 compl_pattern.length = curs_col;
4961 set_cmd_context(&compl_xp, compl_pattern.string,
4962 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004963 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4964 || compl_xp.xp_context == EXPAND_NOTHING)
4965 // No completion possible, use an empty pattern to get a
4966 // "pattern not found" message.
4967 compl_col = curs_col;
4968 else
John Marriott5e6ea922024-11-23 14:01:57 +01004969 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004970 compl_length = curs_col - compl_col;
4971
4972 return OK;
4973}
4974
4975/*
4976 * Get the pattern, column and length for user defined completion ('omnifunc',
4977 * 'completefunc' and 'thesaurusfunc')
4978 * Sets the global variables: compl_col, compl_length and compl_pattern.
4979 * Uses the global variable: spell_bad_len
4980 */
4981 static int
4982get_userdefined_compl_info(colnr_T curs_col UNUSED)
4983{
4984 int ret = FAIL;
4985
4986#ifdef FEAT_COMPL_FUNC
4987 // Call user defined function 'completefunc' with "a:findstart"
4988 // set to 1 to obtain the length of text to use for completion.
4989 char_u *line;
4990 typval_T args[3];
4991 int col;
4992 char_u *funcname;
4993 pos_T pos;
4994 int save_State = State;
4995 callback_T *cb;
4996
4997 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4998 // length as a string
4999 funcname = get_complete_funcname(ctrl_x_mode);
5000 if (*funcname == NUL)
5001 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005002 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005003 ? "completefunc" : "omnifunc");
5004 return FAIL;
5005 }
5006
5007 args[0].v_type = VAR_NUMBER;
5008 args[0].vval.v_number = 1;
5009 args[1].v_type = VAR_STRING;
5010 args[1].vval.v_string = (char_u *)"";
5011 args[2].v_type = VAR_UNKNOWN;
5012 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005013 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005014 cb = get_insert_callback(ctrl_x_mode);
5015 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005016 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005017
5018 State = save_State;
5019 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005020 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005021 validate_cursor();
5022 if (!EQUAL_POS(curwin->w_cursor, pos))
5023 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005024 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005025 return FAIL;
5026 }
5027
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005028 // Return value -2 means the user complete function wants to cancel the
5029 // complete without an error, do the same if the function did not execute
5030 // successfully.
5031 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005032 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005033 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005034 if (col == -3)
5035 {
5036 ctrl_x_mode = CTRL_X_NORMAL;
5037 edit_submode = NULL;
5038 if (!shortmess(SHM_COMPLETIONMENU))
5039 msg_clr_cmdline();
5040 return FAIL;
5041 }
5042
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005043 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005044 // completion.
5045 compl_opt_refresh_always = FALSE;
5046 compl_opt_suppress_empty = FALSE;
5047
5048 if (col < 0)
5049 col = curs_col;
5050 compl_col = col;
5051 if (compl_col > curs_col)
5052 compl_col = curs_col;
5053
5054 // Setup variables for completion. Need to obtain "line" again,
5055 // it may have become invalid.
5056 line = ml_get(curwin->w_cursor.lnum);
5057 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005058 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5059 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005060 {
John Marriott5e6ea922024-11-23 14:01:57 +01005061 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005062 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005063 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005064
John Marriott5e6ea922024-11-23 14:01:57 +01005065 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005066 ret = OK;
5067#endif
5068
5069 return ret;
5070}
5071
5072/*
5073 * Get the pattern, column and length for spell completion.
5074 * Sets the global variables: compl_col, compl_length and compl_pattern.
5075 * Uses the global variable: spell_bad_len
5076 */
5077 static int
5078get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5079{
5080 int ret = FAIL;
5081#ifdef FEAT_SPELL
5082 char_u *line;
5083
5084 if (spell_bad_len > 0)
5085 compl_col = curs_col - spell_bad_len;
5086 else
5087 compl_col = spell_word_start(startcol);
5088 if (compl_col >= (colnr_T)startcol)
5089 {
5090 compl_length = 0;
5091 compl_col = curs_col;
5092 }
5093 else
5094 {
5095 spell_expand_check_cap(compl_col);
5096 compl_length = (int)curs_col - compl_col;
5097 }
5098 // Need to obtain "line" again, it may have become invalid.
5099 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005100 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5101 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005102 {
John Marriott5e6ea922024-11-23 14:01:57 +01005103 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005104 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005105 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005106
John Marriott5e6ea922024-11-23 14:01:57 +01005107 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005108 ret = OK;
5109#endif
5110
5111 return ret;
5112}
5113
5114/*
5115 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005116 * "startcol" - start column number of the completion pattern/text
5117 * "cur_col" - current cursor column
5118 * On return, "line_invalid" is set to TRUE, if the current line may have
5119 * become invalid and needs to be fetched again.
5120 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005121 */
5122 static int
5123compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5124{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005125 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005126 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5127 && !thesaurus_func_complete(ctrl_x_mode)))
5128 {
5129 return get_normal_compl_info(line, startcol, curs_col);
5130 }
5131 else if (ctrl_x_mode_line_or_eval())
5132 {
5133 return get_wholeline_compl_info(line, curs_col);
5134 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005135 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005136 {
5137 return get_filename_compl_info(line, startcol, curs_col);
5138 }
5139 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5140 {
5141 return get_cmdline_compl_info(line, curs_col);
5142 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005143 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005144 || thesaurus_func_complete(ctrl_x_mode))
5145 {
5146 if (get_userdefined_compl_info(curs_col) == FAIL)
5147 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005148 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005149 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005150 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005151 {
5152 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5153 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005154 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005155 }
5156 else
5157 {
5158 internal_error("ins_complete()");
5159 return FAIL;
5160 }
5161
5162 return OK;
5163}
5164
5165/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005166 * Continue an interrupted completion mode search in "line".
5167 *
5168 * If this same ctrl_x_mode has been interrupted use the text from
5169 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5170 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5171 * the same line as the cursor then fix it (the line has been split because it
5172 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5173 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005174 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005175 static void
5176ins_compl_continue_search(char_u *line)
5177{
5178 // it is a continued search
5179 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005180 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5181 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005182 {
5183 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5184 {
5185 // line (probably) wrapped, set compl_startpos to the
5186 // first non_blank in the line, if it is not a wordchar
5187 // include it to get a better pattern, but then we don't
5188 // want the "\\<" prefix, check it below
5189 compl_col = (colnr_T)getwhitecols(line);
5190 compl_startpos.col = compl_col;
5191 compl_startpos.lnum = curwin->w_cursor.lnum;
5192 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5193 }
5194 else
5195 {
5196 // S_IPOS was set when we inserted a word that was at the
5197 // beginning of the line, which means that we'll go to SOL
5198 // mode but first we need to redefine compl_startpos
5199 if (compl_cont_status & CONT_S_IPOS)
5200 {
5201 compl_cont_status |= CONT_SOL;
5202 compl_startpos.col = (colnr_T)(skipwhite(
5203 line + compl_length
5204 + compl_startpos.col) - line);
5205 }
5206 compl_col = compl_startpos.col;
5207 }
5208 compl_length = curwin->w_cursor.col - (int)compl_col;
5209 // IObuff is used to add a "word from the next line" would we
5210 // have enough space? just being paranoid
5211#define MIN_SPACE 75
5212 if (compl_length > (IOSIZE - MIN_SPACE))
5213 {
5214 compl_cont_status &= ~CONT_SOL;
5215 compl_length = (IOSIZE - MIN_SPACE);
5216 compl_col = curwin->w_cursor.col - compl_length;
5217 }
5218 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5219 if (compl_length < 1)
5220 compl_cont_status &= CONT_LOCAL;
5221 }
5222 else if (ctrl_x_mode_line_or_eval())
5223 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5224 else
5225 compl_cont_status = 0;
5226}
5227
5228/*
5229 * start insert mode completion
5230 */
5231 static int
5232ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005233{
5234 char_u *line;
5235 int startcol = 0; // column where searched text starts
5236 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005237 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005238 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005239 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005240
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005241 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005242
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005243 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005244 did_si = FALSE;
5245 can_si = FALSE;
5246 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005247 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005248 return FAIL;
5249
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005250 line = ml_get(curwin->w_cursor.lnum);
5251 curs_col = curwin->w_cursor.col;
5252 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005253
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005254 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5255 && compl_cont_mode == ctrl_x_mode)
5256 // this same ctrl-x_mode was interrupted previously. Continue the
5257 // completion.
5258 ins_compl_continue_search(line);
5259 else
5260 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005261
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005262 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005263 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005264 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005265 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005266 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5267 compl_cont_status = 0;
5268 compl_cont_status |= CONT_N_ADDS;
5269 compl_startpos = curwin->w_cursor;
5270 startcol = (int)curs_col;
5271 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005272 }
5273
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005274 // Work out completion pattern and original text -- webb
5275 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5276 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005277 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5278 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005279 // restore did_ai, so that adding comment leader works
5280 did_ai = save_did_ai;
5281 return FAIL;
5282 }
5283 // If "line" was changed while getting completion info get it again.
5284 if (line_invalid)
5285 line = ml_get(curwin->w_cursor.lnum);
5286
glepnir7cfe6932024-09-15 20:06:28 +02005287 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005288 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005289 {
5290 edit_submode_pre = (char_u *)_(" Adding");
5291 if (ctrl_x_mode_line_or_eval())
5292 {
5293 // Insert a new line, keep indentation but ignore 'comments'.
5294 char_u *old = curbuf->b_p_com;
5295
5296 curbuf->b_p_com = (char_u *)"";
5297 compl_startpos.lnum = curwin->w_cursor.lnum;
5298 compl_startpos.col = compl_col;
5299 ins_eol('\r');
5300 curbuf->b_p_com = old;
5301 compl_length = 0;
5302 compl_col = curwin->w_cursor.col;
5303 }
glepnir7cfe6932024-09-15 20:06:28 +02005304 else if (ctrl_x_mode_normal() && in_fuzzy)
5305 {
5306 compl_startpos = curwin->w_cursor;
5307 compl_cont_status &= CONT_S_IPOS;
5308 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005309 }
5310 else
5311 {
5312 edit_submode_pre = NULL;
5313 compl_startpos.col = compl_col;
5314 }
5315
5316 if (compl_cont_status & CONT_LOCAL)
5317 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5318 else
5319 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5320
5321 // If any of the original typed text has been changed we need to fix
5322 // the redo buffer.
5323 ins_compl_fixRedoBufForLeader(NULL);
5324
5325 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005326 VIM_CLEAR_STRING(compl_orig_text);
5327 compl_orig_text.length = (size_t)compl_length;
5328 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005329 if (p_ic)
5330 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005331 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5332 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005333 {
John Marriott5e6ea922024-11-23 14:01:57 +01005334 VIM_CLEAR_STRING(compl_pattern);
5335 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005336 return FAIL;
5337 }
5338
5339 // showmode might reset the internal line pointers, so it must
5340 // be called before line = ml_get(), or when this address is no
5341 // longer needed. -- Acevedo.
5342 edit_submode_extra = (char_u *)_("-- Searching...");
5343 edit_submode_highl = HLF_COUNT;
5344 showmode();
5345 edit_submode_extra = NULL;
5346 out_flush();
5347
5348 return OK;
5349}
5350
5351/*
5352 * display the completion status message
5353 */
5354 static void
5355ins_compl_show_statusmsg(void)
5356{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005357 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005358 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005359 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005360 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005361 ? (char_u *)_("Hit end of paragraph")
5362 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005363 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005364 }
5365
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005366 if (edit_submode_extra == NULL)
5367 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005368 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005369 {
5370 edit_submode_extra = (char_u *)_("Back at original");
5371 edit_submode_highl = HLF_W;
5372 }
5373 else if (compl_cont_status & CONT_S_IPOS)
5374 {
5375 edit_submode_extra = (char_u *)_("Word from other line");
5376 edit_submode_highl = HLF_COUNT;
5377 }
5378 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5379 {
5380 edit_submode_extra = (char_u *)_("The only match");
5381 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005382 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005383 }
5384 else
5385 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005386#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005387 // Update completion sequence number when needed.
5388 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005389 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005390#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005391 // The match should always have a sequence number now, this is
5392 // just a safety check.
5393 if (compl_curr_match->cp_number != -1)
5394 {
5395 // Space for 10 text chars. + 2x10-digit no.s = 31.
5396 // Translations may need more than twice that.
5397 static char_u match_ref[81];
5398
5399 if (compl_matches > 0)
5400 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005401 _("match %d of %d"),
5402 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005403 else
5404 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005405 _("match %d"),
5406 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005407 edit_submode_extra = match_ref;
5408 edit_submode_highl = HLF_R;
5409 if (dollar_vcol >= 0)
5410 curs_columns(FALSE);
5411 }
5412 }
5413 }
5414
5415 // Show a message about what (completion) mode we're in.
5416 if (!compl_opt_suppress_empty)
5417 {
5418 showmode();
5419 if (!shortmess(SHM_COMPLETIONMENU))
5420 {
5421 if (edit_submode_extra != NULL)
5422 {
5423 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005424 {
5425 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005426 msg_attr((char *)edit_submode_extra,
5427 edit_submode_highl < HLF_COUNT
5428 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005429 msg_hist_off = FALSE;
5430 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005431 }
5432 else
5433 msg_clr_cmdline(); // necessary for "noshowmode"
5434 }
5435 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005436}
5437
5438/*
5439 * Do Insert mode completion.
5440 * Called when character "c" was typed, which has a meaning for completion.
5441 * Returns OK if completion was done, FAIL if something failed (out of mem).
5442 */
5443 int
5444ins_complete(int c, int enable_pum)
5445{
5446 int n;
5447 int save_w_wrow;
5448 int save_w_leftcol;
5449 int insert_match;
5450
5451 compl_direction = ins_compl_key2dir(c);
5452 insert_match = ins_compl_use_match(c);
5453
5454 if (!compl_started)
5455 {
5456 if (ins_compl_start() == FAIL)
5457 return FAIL;
5458 }
5459 else if (insert_match && stop_arrow() == FAIL)
5460 return FAIL;
5461
5462 compl_shown_match = compl_curr_match;
5463 compl_shows_dir = compl_direction;
5464
5465 // Find next match (and following matches).
5466 save_w_wrow = curwin->w_wrow;
5467 save_w_leftcol = curwin->w_leftcol;
5468 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5469
5470 // may undisplay the popup menu
5471 ins_compl_upd_pum();
5472
5473 if (n > 1) // all matches have been found
5474 compl_matches = n;
5475 compl_curr_match = compl_shown_match;
5476 compl_direction = compl_shows_dir;
5477
5478 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5479 // mode.
5480 if (got_int && !global_busy)
5481 {
5482 (void)vgetc();
5483 got_int = FALSE;
5484 }
5485
5486 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005487 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005488 {
5489 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5490 // because we couldn't expand anything at first place, but if we used
5491 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5492 // (such as M in M'exico) if not tried already. -- Acevedo
5493 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005494 || compl_status_adding()
5495 || (ctrl_x_mode_not_default()
5496 && !ctrl_x_mode_path_patterns()
5497 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005498 compl_cont_status &= ~CONT_N_ADDS;
5499 }
5500
5501 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5502 compl_cont_status |= CONT_S_IPOS;
5503 else
5504 compl_cont_status &= ~CONT_S_IPOS;
5505
5506 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005507
5508 // Show the popup menu, unless we got interrupted.
5509 if (enable_pum && !compl_interrupted)
5510 show_pum(save_w_wrow, save_w_leftcol);
5511
5512 compl_was_interrupted = compl_interrupted;
5513 compl_interrupted = FALSE;
5514
5515 return OK;
5516}
5517
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005518/*
5519 * Remove (if needed) and show the popup menu
5520 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005521 static void
5522show_pum(int prev_w_wrow, int prev_w_leftcol)
5523{
5524 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005525 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005526 RedrawingDisabled = 0;
5527
5528 // If the cursor moved or the display scrolled we need to remove the pum
5529 // first.
5530 setcursor();
5531 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5532 ins_compl_del_pum();
5533
5534 ins_compl_show_pum();
5535 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005536
5537 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005538}
5539
5540/*
5541 * Looks in the first "len" chars. of "src" for search-metachars.
5542 * If dest is not NULL the chars. are copied there quoting (with
5543 * a backslash) the metachars, and dest would be NUL terminated.
5544 * Returns the length (needed) of dest
5545 */
5546 static unsigned
5547quote_meta(char_u *dest, char_u *src, int len)
5548{
5549 unsigned m = (unsigned)len + 1; // one extra for the NUL
5550
5551 for ( ; --len >= 0; src++)
5552 {
5553 switch (*src)
5554 {
5555 case '.':
5556 case '*':
5557 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005558 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005559 break;
5560 // FALLTHROUGH
5561 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005562 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005563 break;
5564 // FALLTHROUGH
5565 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005566 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005567 break;
5568 // FALLTHROUGH
5569 case '^': // currently it's not needed.
5570 case '$':
5571 m++;
5572 if (dest != NULL)
5573 *dest++ = '\\';
5574 break;
5575 }
5576 if (dest != NULL)
5577 *dest++ = *src;
5578 // Copy remaining bytes of a multibyte character.
5579 if (has_mbyte)
5580 {
5581 int i, mb_len;
5582
5583 mb_len = (*mb_ptr2len)(src) - 1;
5584 if (mb_len > 0 && len >= mb_len)
5585 for (i = 0; i < mb_len; ++i)
5586 {
5587 --len;
5588 ++src;
5589 if (dest != NULL)
5590 *dest++ = *src;
5591 }
5592 }
5593 }
5594 if (dest != NULL)
5595 *dest = NUL;
5596
5597 return m;
5598}
5599
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005600#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005601 void
5602free_insexpand_stuff(void)
5603{
John Marriott5e6ea922024-11-23 14:01:57 +01005604 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005605# ifdef FEAT_EVAL
5606 free_callback(&cfu_cb);
5607 free_callback(&ofu_cb);
5608 free_callback(&tsrfu_cb);
5609# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005610}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005611#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005612
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005613#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005614/*
5615 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5616 * spelled word, if there is one.
5617 */
5618 static void
5619spell_back_to_badword(void)
5620{
5621 pos_T tpos = curwin->w_cursor;
5622
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005623 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005624 if (curwin->w_cursor.col != tpos.col)
5625 start_arrow(&tpos);
5626}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005627#endif