blob: 75403f1b3b386dab84a9fc1beee9ec5673381629 [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/*
2300 * Stop insert completion mode
2301 */
2302 static int
2303ins_compl_stop(int c, int prev_mode, int retval)
2304{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002305 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002306
2307 // Get here when we have finished typing a sequence of ^N and
2308 // ^P or other completion characters in CTRL-X mode. Free up
2309 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002310 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002311 {
John Marriott5e6ea922024-11-23 14:01:57 +01002312 char_u *ptr;
2313
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002314 // If any of the original typed text has been changed, eg when
2315 // ignorecase is set, we must add back-spaces to the redo
2316 // buffer. We add as few as necessary to delete just the part
2317 // of the original text that has changed.
2318 // When using the longest match, edited the match or used
2319 // CTRL-E then don't use the current match.
2320 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002321 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002322 else
2323 ptr = NULL;
2324 ins_compl_fixRedoBufForLeader(ptr);
2325 }
2326
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002327 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002328
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002329 // When completing whole lines: fix indent for 'cindent'.
2330 // Otherwise, break line if it's too long.
2331 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2332 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002333 // re-indent the current line
2334 if (want_cindent)
2335 {
2336 do_c_expr_indent();
2337 want_cindent = FALSE; // don't do it again
2338 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002339 }
2340 else
2341 {
2342 int prev_col = curwin->w_cursor.col;
2343
2344 // put the cursor on the last char, for 'tw' formatting
2345 if (prev_col > 0)
2346 dec_cursor();
2347 // only format when something was inserted
2348 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2349 insertchar(NUL, 0, -1);
2350 if (prev_col > 0
2351 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2352 inc_cursor();
2353 }
2354
2355 // If the popup menu is displayed pressing CTRL-Y means accepting
2356 // the selection without inserting anything. When
2357 // compl_enter_selects is set the Enter key does the same.
2358 if ((c == Ctrl_Y || (compl_enter_selects
2359 && (c == CAR || c == K_KENTER || c == NL)))
2360 && pum_visible())
2361 retval = TRUE;
2362
2363 // CTRL-E means completion is Ended, go back to the typed text.
2364 // but only do this, if the Popup is still visible
2365 if (c == Ctrl_E)
2366 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002367 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002368 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002369
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002370 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002371 if (compl_leader.string != NULL)
2372 {
2373 p = compl_leader.string;
2374 plen = compl_leader.length;
2375 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002376 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002377 {
2378 p = compl_orig_text.string;
2379 plen = compl_orig_text.length;
2380 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002381 if (p != NULL)
2382 {
2383 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002384
John Marriott5e6ea922024-11-23 14:01:57 +01002385 if ((int)plen > compl_len)
2386 ins_bytes_len(p + compl_len, (int)(plen - compl_len));
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002387 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002388 retval = TRUE;
2389 }
2390
2391 auto_format(FALSE, TRUE);
2392
2393 // Trigger the CompleteDonePre event to give scripts a chance to
2394 // act upon the completion before clearing the info, and restore
2395 // ctrl_x_mode, so that complete_info() can be used.
2396 ctrl_x_mode = prev_mode;
2397 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2398
2399 ins_compl_free();
2400 compl_started = FALSE;
2401 compl_matches = 0;
2402 if (!shortmess(SHM_COMPLETIONMENU))
2403 msg_clr_cmdline(); // necessary for "noshowmode"
2404 ctrl_x_mode = CTRL_X_NORMAL;
2405 compl_enter_selects = FALSE;
2406 if (edit_submode != NULL)
2407 {
2408 edit_submode = NULL;
2409 showmode();
2410 }
2411
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002412 if (c == Ctrl_C && cmdwin_type != 0)
2413 // Avoid the popup menu remains displayed when leaving the
2414 // command line window.
2415 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002416 // Indent now if a key was typed that is in 'cinkeys'.
2417 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2418 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002419 // Trigger the CompleteDone event to give scripts a chance to act
2420 // upon the end of completion.
2421 ins_apply_autocmds(EVENT_COMPLETEDONE);
2422
2423 return retval;
2424}
2425
2426/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002427 * Prepare for Insert mode completion, or stop it.
2428 * Called just after typing a character in Insert mode.
2429 * Returns TRUE when the character is not to be inserted;
2430 */
2431 int
2432ins_compl_prep(int c)
2433{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002434 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002435 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002436
2437 // Forget any previous 'special' messages if this is actually
2438 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2439 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2440 edit_submode_extra = NULL;
2441
zeertzjq440d4cb2023-03-02 17:51:32 +00002442 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002443 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002444 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002445 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002446 return retval;
2447
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002448#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002449 // Ignore mouse events in a popup window
2450 if (is_mouse_key(c))
2451 {
2452 // Ignore drag and release events, the position does not need to be in
2453 // the popup and it may have just closed.
2454 if (c == K_LEFTRELEASE
2455 || c == K_LEFTRELEASE_NM
2456 || c == K_MIDDLERELEASE
2457 || c == K_RIGHTRELEASE
2458 || c == K_X1RELEASE
2459 || c == K_X2RELEASE
2460 || c == K_LEFTDRAG
2461 || c == K_MIDDLEDRAG
2462 || c == K_RIGHTDRAG
2463 || c == K_X1DRAG
2464 || c == K_X2DRAG)
2465 return retval;
2466 if (popup_visible)
2467 {
2468 int row = mouse_row;
2469 int col = mouse_col;
2470 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2471
2472 if (wp != NULL && WIN_IS_POPUP(wp))
2473 return retval;
2474 }
2475 }
2476#endif
2477
zeertzjqdca29d92021-08-31 19:12:51 +02002478 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2479 {
2480 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2481 || !vim_is_ctrl_x_key(c))
2482 {
2483 // Not starting another completion mode.
2484 ctrl_x_mode = CTRL_X_CMDLINE;
2485
2486 // CTRL-X CTRL-Z should stop completion without inserting anything
2487 if (c == Ctrl_Z)
2488 retval = TRUE;
2489 }
2490 else
2491 {
2492 ctrl_x_mode = CTRL_X_CMDLINE;
2493
2494 // Other CTRL-X keys first stop completion, then start another
2495 // completion mode.
2496 ins_compl_prep(' ');
2497 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2498 }
2499 }
2500
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002501 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002502 if (ctrl_x_mode_not_defined_yet()
2503 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002504 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002505 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002506 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002507 }
2508
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002509 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002510 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2511 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002512 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002513 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002514 {
2515 // We're already in CTRL-X mode, do we stay in it?
2516 if (!vim_is_ctrl_x_key(c))
2517 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002518 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002519 ctrl_x_mode = CTRL_X_NORMAL;
2520 else
2521 ctrl_x_mode = CTRL_X_FINISHED;
2522 edit_submode = NULL;
2523 }
2524 showmode();
2525 }
2526
2527 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2528 {
2529 // Show error message from attempted keyword completion (probably
2530 // 'Pattern not found') until another key is hit, then go back to
2531 // showing what mode we are in.
2532 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002533 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002534 && c != Ctrl_R && !ins_compl_pum_key(c))
2535 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002536 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002537 }
2538 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2539 // Trigger the CompleteDone event to give scripts a chance to act
2540 // upon the (possibly failed) completion.
2541 ins_apply_autocmds(EVENT_COMPLETEDONE);
2542
LemonBoy2bf52dd2022-04-09 18:17:34 +01002543 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002544
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002545 // reset continue_* if we left expansion-mode, if we stay they'll be
2546 // (re)set properly in ins_complete()
2547 if (!vim_is_ctrl_x_key(c))
2548 {
2549 compl_cont_status = 0;
2550 compl_cont_mode = 0;
2551 }
2552
2553 return retval;
2554}
2555
2556/*
2557 * Fix the redo buffer for the completion leader replacing some of the typed
2558 * text. This inserts backspaces and appends the changed text.
2559 * "ptr" is the known leader text or NUL.
2560 */
2561 static void
2562ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2563{
John Marriott5e6ea922024-11-23 14:01:57 +01002564 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002565 char_u *p;
2566 char_u *ptr = ptr_arg;
2567
2568 if (ptr == NULL)
2569 {
John Marriott5e6ea922024-11-23 14:01:57 +01002570 if (compl_leader.string != NULL)
2571 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002572 else
2573 return; // nothing to do
2574 }
John Marriott5e6ea922024-11-23 14:01:57 +01002575 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002576 {
John Marriott5e6ea922024-11-23 14:01:57 +01002577 p = compl_orig_text.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002578 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2579 ;
2580 if (len > 0)
2581 len -= (*mb_head_off)(p, p + len);
2582 for (p += len; *p != NUL; MB_PTR_ADV(p))
2583 AppendCharToRedobuff(K_BS);
2584 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002585 if (ptr != NULL)
2586 AppendToRedobuffLit(ptr + len, -1);
2587}
2588
2589/*
2590 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2591 * (depending on flag) starting from buf and looking for a non-scanned
2592 * buffer (other than curbuf). curbuf is special, if it is called with
2593 * buf=curbuf then it has to be the first call for a given flag/expansion.
2594 *
2595 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2596 */
2597 static buf_T *
2598ins_compl_next_buf(buf_T *buf, int flag)
2599{
2600 static win_T *wp = NULL;
2601
2602 if (flag == 'w') // just windows
2603 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002604 if (buf == curbuf || !win_valid(wp))
2605 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002606 wp = curwin;
2607 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2608 && wp->w_buffer->b_scanned)
2609 ;
2610 buf = wp->w_buffer;
2611 }
2612 else
2613 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2614 // (unlisted buffers)
2615 // When completing whole lines skip unloaded buffers.
2616 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2617 && ((flag == 'U'
2618 ? buf->b_p_bl
2619 : (!buf->b_p_bl
2620 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2621 || buf->b_scanned))
2622 ;
2623 return buf;
2624}
2625
2626#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002627
2628# ifdef FEAT_EVAL
2629static callback_T cfu_cb; // 'completefunc' callback function
2630static callback_T ofu_cb; // 'omnifunc' callback function
2631static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2632# endif
2633
2634/*
2635 * Copy a global callback function to a buffer local callback.
2636 */
2637 static void
2638copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2639{
2640 free_callback(bufcb);
2641 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2642 copy_callback(bufcb, globcb);
2643}
2644
2645/*
2646 * Parse the 'completefunc' option value and set the callback function.
2647 * Invoked when the 'completefunc' option is set. The option value can be a
2648 * name of a function (string), or function(<name>) or funcref(<name>) or a
2649 * lambda expression.
2650 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002651 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002652did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002653{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002654 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2655 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002656
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002657 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002658
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002659 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002660}
2661
2662/*
2663 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002664 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002665 */
2666 void
2667set_buflocal_cfu_callback(buf_T *buf UNUSED)
2668{
2669# ifdef FEAT_EVAL
2670 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2671# endif
2672}
2673
2674/*
2675 * Parse the 'omnifunc' option value and set the callback function.
2676 * Invoked when the 'omnifunc' option is set. The option value can be a
2677 * name of a function (string), or function(<name>) or funcref(<name>) or a
2678 * lambda expression.
2679 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002680 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002681did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002682{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002683 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2684 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002685
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002686 set_buflocal_ofu_callback(curbuf);
2687 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002688}
2689
2690/*
2691 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002692 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002693 */
2694 void
2695set_buflocal_ofu_callback(buf_T *buf UNUSED)
2696{
2697# ifdef FEAT_EVAL
2698 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2699# endif
2700}
2701
2702/*
2703 * Parse the 'thesaurusfunc' option value and set the callback function.
2704 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2705 * name of a function (string), or function(<name>) or funcref(<name>) or a
2706 * lambda expression.
2707 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002708 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002709did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002710{
2711 int retval;
2712
zeertzjq6eda2692024-11-03 09:23:33 +01002713 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002714 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002715 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2716 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002717 else
2718 {
2719 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002720 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002721 // when using :set, free the local callback
2722 if (!(args->os_flags & OPT_GLOBAL))
2723 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002724 }
2725
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002726 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002727}
2728
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002729/*
2730 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002731 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002732 */
2733 int
2734set_ref_in_insexpand_funcs(int copyID)
2735{
2736 int abort = FALSE;
2737
2738 abort = set_ref_in_callback(&cfu_cb, copyID);
2739 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2740 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2741
2742 return abort;
2743}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002744
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002745/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002746 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002747 */
2748 static char_u *
2749get_complete_funcname(int type)
2750{
2751 switch (type)
2752 {
2753 case CTRL_X_FUNCTION:
2754 return curbuf->b_p_cfu;
2755 case CTRL_X_OMNI:
2756 return curbuf->b_p_ofu;
2757 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002758 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002759 default:
2760 return (char_u *)"";
2761 }
2762}
2763
2764/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002765 * Get the callback to use for insert mode completion.
2766 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002767 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002768get_insert_callback(int type)
2769{
2770 if (type == CTRL_X_FUNCTION)
2771 return &curbuf->b_cfu_cb;
2772 if (type == CTRL_X_OMNI)
2773 return &curbuf->b_ofu_cb;
2774 // CTRL_X_THESAURUS
2775 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2776}
2777
2778/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002779 * Execute user defined complete function 'completefunc', 'omnifunc' or
2780 * 'thesaurusfunc', and get matches in "matches".
2781 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002782 */
2783 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002784expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002785{
2786 list_T *matchlist = NULL;
2787 dict_T *matchdict = NULL;
2788 typval_T args[3];
2789 char_u *funcname;
2790 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002791 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002792 typval_T rettv;
2793 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002794 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002795
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002796 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002797 if (*funcname == NUL)
2798 return;
2799
2800 // Call 'completefunc' to obtain the list of matches.
2801 args[0].v_type = VAR_NUMBER;
2802 args[0].vval.v_number = 0;
2803 args[1].v_type = VAR_STRING;
2804 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2805 args[2].v_type = VAR_UNKNOWN;
2806
2807 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002808 // Lock the text to avoid weird things from happening. Also disallow
2809 // switching to another window, it should not be needed and may end up in
2810 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002811 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002812
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002813 cb = get_insert_callback(type);
2814 retval = call_callback(cb, 0, &rettv, 2, args);
2815
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002816 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002817 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002818 {
2819 switch (rettv.v_type)
2820 {
2821 case VAR_LIST:
2822 matchlist = rettv.vval.v_list;
2823 break;
2824 case VAR_DICT:
2825 matchdict = rettv.vval.v_dict;
2826 break;
2827 case VAR_SPECIAL:
2828 if (rettv.vval.v_number == VVAL_NONE)
2829 compl_opt_suppress_empty = TRUE;
2830 // FALLTHROUGH
2831 default:
2832 // TODO: Give error message?
2833 clear_tv(&rettv);
2834 break;
2835 }
2836 }
zeertzjqcfe45652022-05-27 17:26:55 +01002837 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002838
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002839 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002840 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002841 validate_cursor();
2842 if (!EQUAL_POS(curwin->w_cursor, pos))
2843 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002844 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002845 goto theend;
2846 }
2847
2848 if (matchlist != NULL)
2849 ins_compl_add_list(matchlist);
2850 else if (matchdict != NULL)
2851 ins_compl_add_dict(matchdict);
2852
2853theend:
2854 // Restore State, it might have been changed.
2855 State = save_State;
2856
2857 if (matchdict != NULL)
2858 dict_unref(matchdict);
2859 if (matchlist != NULL)
2860 list_unref(matchlist);
2861}
2862#endif // FEAT_COMPL_FUNC
2863
2864#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02002865
2866 static inline int
2867get_user_highlight_attr(char_u *hlname)
2868{
2869 if (hlname != NULL && *hlname != NUL)
2870 return syn_name2attr(hlname);
2871 return -1;
2872}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002873/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002874 * Add a match to the list of matches from a typeval_T.
2875 * If the given string is already in the list of completions, then return
2876 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2877 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002878 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002879 */
2880 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002881ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002882{
2883 char_u *word;
2884 int dup = FALSE;
2885 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002886 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002887 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002888 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002889 int status;
glepnir0fe17f82024-10-08 22:26:44 +02002890 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02002891 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01002892 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002893
Bram Moolenaar08928322020-01-04 14:32:48 +01002894 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002895 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2896 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002897 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2898 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2899 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2900 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2901 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02002902
glepnir0fe17f82024-10-08 22:26:44 +02002903 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01002904 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02002905
2906 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01002907 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02002908
Bram Moolenaard61efa52022-07-23 09:52:04 +01002909 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2910 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2911 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002912 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002913 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2914 dup = dict_get_number(tv->vval.v_dict, "dup");
2915 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2916 empty = dict_get_number(tv->vval.v_dict, "empty");
2917 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2918 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002919 flags |= CP_EQUAL;
2920 }
2921 else
2922 {
2923 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002924 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002925 }
2926 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002927 {
2928 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002929 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002930 }
glepnir508e7852024-07-25 21:39:08 +02002931 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01002932 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002933 if (status != OK)
2934 clear_tv(&user_data);
2935 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002936}
2937
2938/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002939 * Add completions from a list.
2940 */
2941 static void
2942ins_compl_add_list(list_T *list)
2943{
2944 listitem_T *li;
2945 int dir = compl_direction;
2946
2947 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002948 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002949 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002950 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002951 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002952 // if dir was BACKWARD then honor it just once
2953 dir = FORWARD;
2954 else if (did_emsg)
2955 break;
2956 }
2957}
2958
2959/*
2960 * Add completions from a dict.
2961 */
2962 static void
2963ins_compl_add_dict(dict_T *dict)
2964{
2965 dictitem_T *di_refresh;
2966 dictitem_T *di_words;
2967
2968 // Check for optional "refresh" item.
2969 compl_opt_refresh_always = FALSE;
2970 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2971 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2972 {
2973 char_u *v = di_refresh->di_tv.vval.v_string;
2974
2975 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2976 compl_opt_refresh_always = TRUE;
2977 }
2978
2979 // Add completions from a "words" list.
2980 di_words = dict_find(dict, (char_u *)"words", 5);
2981 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2982 ins_compl_add_list(di_words->di_tv.vval.v_list);
2983}
2984
2985/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002986 * Start completion for the complete() function.
2987 * "startcol" is where the matched text starts (1 is first column).
2988 * "list" is the list of matches.
2989 */
2990 static void
2991set_completion(colnr_T startcol, list_T *list)
2992{
2993 int save_w_wrow = curwin->w_wrow;
2994 int save_w_leftcol = curwin->w_leftcol;
2995 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002996 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002997 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2998 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2999 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003000
3001 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003002 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003003 ins_compl_prep(' ');
3004 ins_compl_clear();
3005 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003006 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003007
3008 compl_direction = FORWARD;
3009 if (startcol > curwin->w_cursor.col)
3010 startcol = curwin->w_cursor.col;
3011 compl_col = startcol;
3012 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3013 // compl_pattern doesn't need to be set
John Marriott5e6ea922024-11-23 14:01:57 +01003014 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col, (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003015 if (p_ic)
3016 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003017 if (compl_orig_text.string == NULL)
3018 {
3019 compl_orig_text.length = 0;
3020 return;
3021 }
3022 compl_orig_text.length = (size_t)compl_length;
3023 if (ins_compl_add(compl_orig_text.string,
3024 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3025 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003026 return;
3027
3028 ctrl_x_mode = CTRL_X_EVAL;
3029
3030 ins_compl_add_list(list);
3031 compl_matches = ins_compl_make_cyclic();
3032 compl_started = TRUE;
3033 compl_used_match = TRUE;
3034 compl_cont_status = 0;
3035
3036 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003037 int no_select = compl_no_select || compl_longest;
3038 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003039 {
3040 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003041 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003042 // Down/Up has no real effect.
3043 ins_complete(K_UP, FALSE);
3044 }
3045 else
3046 ins_complete(Ctrl_N, FALSE);
3047 compl_enter_selects = compl_no_insert;
3048
3049 // Lazily show the popup menu, unless we got interrupted.
3050 if (!compl_interrupted)
3051 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003052 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003053 out_flush();
3054}
3055
3056/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003057 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003058 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003059 void
3060f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003061{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003062 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003063
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003064 if (in_vim9script()
3065 && (check_for_number_arg(argvars, 0) == FAIL
3066 || check_for_list_arg(argvars, 1) == FAIL))
3067 return;
3068
Bram Moolenaar24959102022-05-07 20:01:16 +01003069 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003070 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003071 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003072 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003073 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003074
3075 // Check for undo allowed here, because if something was already inserted
3076 // the line was already saved for undo and this check isn't done.
3077 if (!undo_allowed())
3078 return;
3079
Bram Moolenaard83392a2022-09-01 12:22:46 +01003080 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003081 {
3082 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3083 if (startcol > 0)
3084 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003085 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003086}
3087
3088/*
3089 * "complete_add()" function
3090 */
3091 void
3092f_complete_add(typval_T *argvars, typval_T *rettv)
3093{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003094 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003095 return;
3096
Bram Moolenaar440cf092021-04-03 20:13:30 +02003097 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003098}
3099
3100/*
3101 * "complete_check()" function
3102 */
3103 void
3104f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3105{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003106 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003107 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003108
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003109 ins_compl_check_keys(0, TRUE);
3110 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003111
3112 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003113}
3114
3115/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003116 * Return Insert completion mode name string
3117 */
3118 static char_u *
3119ins_compl_mode(void)
3120{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003121 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003122 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3123
3124 return (char_u *)"";
3125}
3126
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003127/*
3128 * Assign the sequence number to all the completion matches which don't have
3129 * one assigned yet.
3130 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003131 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003132ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003133{
3134 int number = 0;
3135 compl_T *match;
3136
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003137 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003138 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003139 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003140 // This should normally succeed already at the first loop
3141 // cycle, so it's fast!
3142 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003143 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003144 if (match->cp_number != -1)
3145 {
3146 number = match->cp_number;
3147 break;
3148 }
3149 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003150 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003151 for (match = match->cp_next;
3152 match != NULL && match->cp_number == -1;
3153 match = match->cp_next)
3154 match->cp_number = ++number;
3155 }
3156 else // BACKWARD
3157 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003158 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003159 // number. This should normally succeed already at the
3160 // first loop cycle, so it's fast!
3161 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003162 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003163 if (match->cp_number != -1)
3164 {
3165 number = match->cp_number;
3166 break;
3167 }
3168 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003169 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003170 for (match = match->cp_prev; match
3171 && match->cp_number == -1;
3172 match = match->cp_prev)
3173 match->cp_number = ++number;
3174 }
3175}
3176
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003177/*
3178 * Get complete information
3179 */
3180 static void
3181get_complete_info(list_T *what_list, dict_T *retdict)
3182{
3183 int ret = OK;
3184 listitem_T *item;
3185#define CI_WHAT_MODE 0x01
3186#define CI_WHAT_PUM_VISIBLE 0x02
3187#define CI_WHAT_ITEMS 0x04
3188#define CI_WHAT_SELECTED 0x08
3189#define CI_WHAT_INSERTED 0x10
3190#define CI_WHAT_ALL 0xff
3191 int what_flag;
3192
3193 if (what_list == NULL)
3194 what_flag = CI_WHAT_ALL;
3195 else
3196 {
3197 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003198 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003199 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003200 {
3201 char_u *what = tv_get_string(&item->li_tv);
3202
3203 if (STRCMP(what, "mode") == 0)
3204 what_flag |= CI_WHAT_MODE;
3205 else if (STRCMP(what, "pum_visible") == 0)
3206 what_flag |= CI_WHAT_PUM_VISIBLE;
3207 else if (STRCMP(what, "items") == 0)
3208 what_flag |= CI_WHAT_ITEMS;
3209 else if (STRCMP(what, "selected") == 0)
3210 what_flag |= CI_WHAT_SELECTED;
3211 else if (STRCMP(what, "inserted") == 0)
3212 what_flag |= CI_WHAT_INSERTED;
3213 }
3214 }
3215
3216 if (ret == OK && (what_flag & CI_WHAT_MODE))
3217 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3218
3219 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3220 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3221
Girish Palya8950bf72024-03-20 20:07:29 +01003222 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003223 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003224 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003225 dict_T *di;
3226 compl_T *match;
3227 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003228
Girish Palya8950bf72024-03-20 20:07:29 +01003229 if (what_flag & CI_WHAT_ITEMS)
3230 {
3231 li = list_alloc();
3232 if (li == NULL)
3233 return;
3234 ret = dict_add_list(retdict, "items", li);
3235 }
3236 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3237 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3238 ins_compl_update_sequence_numbers();
3239 if (ret == OK && compl_first_match != NULL)
3240 {
3241 int list_idx = 0;
3242 match = compl_first_match;
3243 do
3244 {
3245 if (!match_at_original_text(match))
3246 {
3247 if (what_flag & CI_WHAT_ITEMS)
3248 {
3249 di = dict_alloc();
3250 if (di == NULL)
3251 return;
3252 ret = list_append_dict(li, di);
3253 if (ret != OK)
3254 return;
John Marriott5e6ea922024-11-23 14:01:57 +01003255 dict_add_string(di, "word", match->cp_str.string);
Girish Palya8950bf72024-03-20 20:07:29 +01003256 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3257 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3258 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3259 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3260 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3261 // Add an empty string for backwards compatibility
3262 dict_add_string(di, "user_data", (char_u *)"");
3263 else
3264 dict_add_tv(di, "user_data", &match->cp_user_data);
3265 }
3266 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3267 selected_idx = list_idx;
3268 list_idx += 1;
3269 }
3270 match = match->cp_next;
3271 }
3272 while (match != NULL && !is_first_match(match));
3273 }
3274 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3275 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003276 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003277
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003278 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3279 {
3280 // TODO
3281 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003282}
3283
3284/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003285 * "complete_info()" function
3286 */
3287 void
3288f_complete_info(typval_T *argvars, typval_T *rettv)
3289{
3290 list_T *what_list = NULL;
3291
Bram Moolenaar93a10962022-06-16 11:42:09 +01003292 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003293 return;
3294
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003295 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3296 return;
3297
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003298 if (argvars[0].v_type != VAR_UNKNOWN)
3299 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003300 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003301 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003302 what_list = argvars[0].vval.v_list;
3303 }
3304 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003305}
3306#endif
3307
3308/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003309 * Returns TRUE when using a user-defined function for thesaurus completion.
3310 */
3311 static int
3312thesaurus_func_complete(int type UNUSED)
3313{
3314#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003315 return type == CTRL_X_THESAURUS
3316 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003317#else
3318 return FALSE;
3319#endif
3320}
3321
3322/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003323 * Return value of process_next_cpt_value()
3324 */
3325enum
3326{
3327 INS_COMPL_CPT_OK = 1,
3328 INS_COMPL_CPT_CONT,
3329 INS_COMPL_CPT_END
3330};
3331
3332/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003333 * state information used for getting the next set of insert completion
3334 * matches.
3335 */
3336typedef struct
3337{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003338 char_u *e_cpt_copy; // copy of 'complete'
3339 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003340 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003341 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003342 pos_T prev_match_pos; // previous match position
3343 int set_match_pos; // save first_match_pos/last_match_pos
3344 pos_T first_match_pos; // first match position
3345 pos_T last_match_pos; // last match position
3346 int found_all; // found all matches of a certain type.
3347 char_u *dict; // dictionary file to search
3348 int dict_f; // "dict" is an exact file name or not
3349} ins_compl_next_state_T;
3350
3351/*
3352 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003353 *
3354 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003355 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003356 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003357 * st->found_all - all matches of this type are found
3358 * st->ins_buf - search for completions in this buffer
3359 * st->first_match_pos - position of the first completion match
3360 * st->last_match_pos - position of the last completion match
3361 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003362 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003363 * st->dict - name of the dictionary or thesaurus file to search
3364 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003365 *
3366 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003367 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3368 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003369 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003370 */
3371 static int
3372process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003373 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003374 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003375 pos_T *start_match_pos,
3376 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003377{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003378 int compl_type = -1;
3379 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003380
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003381 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003382
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003383 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3384 st->e_cpt++;
3385
3386 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003387 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003388 st->ins_buf = curbuf;
3389 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003390 // Move the cursor back one character so that ^N can match the
3391 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003392 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003393 {
3394 // Move the cursor to after the last character in the
3395 // buffer, so that word at start of buffer is found
3396 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003397 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003398 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003399 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003400 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003401 compl_type = 0;
3402
3403 // Remember the first match so that the loop stops when we
3404 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003405 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003406 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003407 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003408 && (st->ins_buf = ins_compl_next_buf(
3409 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003410 {
3411 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003412 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003413 {
3414 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003415 st->first_match_pos.col = st->last_match_pos.col = 0;
3416 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3417 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003418 compl_type = 0;
3419 }
3420 else // unloaded buffer, scan like dictionary
3421 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003422 st->found_all = TRUE;
3423 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003424 {
3425 status = INS_COMPL_CPT_CONT;
3426 goto done;
3427 }
3428 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003429 st->dict = st->ins_buf->b_fname;
3430 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003431 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003432 if (!shortmess(SHM_COMPLETIONSCAN))
3433 {
3434 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3435 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3436 st->ins_buf->b_fname == NULL
3437 ? buf_spname(st->ins_buf)
3438 : st->ins_buf->b_sfname == NULL
3439 ? st->ins_buf->b_fname
3440 : st->ins_buf->b_sfname);
3441 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3442 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003443 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003444 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003445 status = INS_COMPL_CPT_END;
3446 else
3447 {
3448 if (ctrl_x_mode_line_or_eval())
3449 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003450 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003451 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003452 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003453 compl_type = CTRL_X_DICTIONARY;
3454 else
3455 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003456 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003457 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003458 st->dict = st->e_cpt;
3459 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003460 }
3461 }
3462#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003463 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003464 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003465 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003466 compl_type = CTRL_X_PATH_DEFINES;
3467#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003468 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003469 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003470 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003471 if (!shortmess(SHM_COMPLETIONSCAN))
3472 {
3473 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3474 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3475 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3476 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003477 }
3478 else
3479 compl_type = -1;
3480
3481 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003482 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003483
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003484 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003485 if (compl_type == -1)
3486 status = INS_COMPL_CPT_CONT;
3487 }
3488
3489done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003490 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003491 return status;
3492}
3493
3494#ifdef FEAT_FIND_ID
3495/*
3496 * Get the next set of identifiers or defines matching "compl_pattern" in
3497 * included files.
3498 */
3499 static void
3500get_next_include_file_completion(int compl_type)
3501{
John Marriott5e6ea922024-11-23 14:01:57 +01003502 find_pattern_in_path(compl_pattern.string, compl_direction,
3503 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003504 (compl_type == CTRL_X_PATH_DEFINES
3505 && !(compl_cont_status & CONT_SOL))
3506 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003507 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003508}
3509#endif
3510
3511/*
3512 * Get the next set of words matching "compl_pattern" in dictionary or
3513 * thesaurus files.
3514 */
3515 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003516get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003517{
3518#ifdef FEAT_COMPL_FUNC
3519 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003520 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003521 else
3522#endif
3523 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003524 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003525 : (compl_type == CTRL_X_THESAURUS
3526 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3527 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003528 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003529 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003530 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003531}
3532
3533/*
3534 * Get the next set of tag names matching "compl_pattern".
3535 */
3536 static void
3537get_next_tag_completion(void)
3538{
3539 int save_p_ic;
3540 char_u **matches;
3541 int num_matches;
3542
3543 // set p_ic according to p_ic, p_scs and pat for find_tags().
3544 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003545 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003546
3547 // Find up to TAG_MANY matches. Avoids that an enormous number
3548 // of matches is found when compl_pattern is empty
3549 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003550 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003551 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003552 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003553 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3554 ins_compl_add_matches(num_matches, matches, p_ic);
3555 g_tag_at_cursor = FALSE;
3556 p_ic = save_p_ic;
3557}
3558
3559/*
glepnir8159fb12024-07-17 20:32:54 +02003560 * Compare function for qsort
3561 */
3562static int compare_scores(const void *a, const void *b)
3563{
3564 int idx_a = *(const int *)a;
3565 int idx_b = *(const int *)b;
3566 int score_a = compl_fuzzy_scores[idx_a];
3567 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003568 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3569 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003570}
3571
3572/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003573 * Get the next set of filename matching "compl_pattern".
3574 */
3575 static void
3576get_next_filename_completion(void)
3577{
3578 char_u **matches;
3579 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003580 char_u *ptr;
3581 garray_T fuzzy_indices;
3582 int i;
3583 int score;
3584 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003585 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003586 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3587 char_u **sorted_matches;
3588 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003589 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003590
glepnirb9de1a02024-08-02 19:14:38 +02003591#ifdef BACKSLASH_IN_FILENAME
3592 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3593 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3594#else
3595 char pathsep = PATHSEP;
3596#endif
3597
glepnir8159fb12024-07-17 20:32:54 +02003598 if (in_fuzzy)
3599 {
glepnirb9de1a02024-08-02 19:14:38 +02003600#ifdef BACKSLASH_IN_FILENAME
3601 if (curbuf->b_p_csl[0] == 's')
3602 {
John Marriott5e6ea922024-11-23 14:01:57 +01003603 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003604 {
3605 if (leader[i] == '\\')
3606 leader[i] = '/';
3607 }
3608 }
3609 else if (curbuf->b_p_csl[0] == 'b')
3610 {
John Marriott5e6ea922024-11-23 14:01:57 +01003611 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003612 {
3613 if (leader[i] == '/')
3614 leader[i] = '\\';
3615 }
3616 }
3617#endif
3618 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003619 if (last_sep == NULL)
3620 {
3621 // No path separator or separator is the last character,
3622 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003623 VIM_CLEAR_STRING(compl_pattern);
3624 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3625 if (compl_pattern.string == NULL)
3626 return;
3627 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003628 }
3629 else if (*(last_sep + 1) == '\0')
3630 in_fuzzy = FALSE;
3631 else
3632 {
3633 // Split leader into path and file parts
3634 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003635 char_u *path_with_wildcard;
3636
3637 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003638 if (path_with_wildcard != NULL)
3639 {
John Marriott5e6ea922024-11-23 14:01:57 +01003640 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3641 VIM_CLEAR_STRING(compl_pattern);
3642 compl_pattern.string = path_with_wildcard;
3643 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003644
3645 // Move leader to the file part
3646 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003647 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003648 }
3649 }
glepnir8159fb12024-07-17 20:32:54 +02003650 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003651
John Marriott5e6ea922024-11-23 14:01:57 +01003652 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003653 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3654 return;
3655
3656 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003657 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003658#ifdef BACKSLASH_IN_FILENAME
3659 if (curbuf->b_p_csl[0] != NUL)
3660 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003661 for (i = 0; i < num_matches; ++i)
3662 {
glepnir8159fb12024-07-17 20:32:54 +02003663 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003664 while (*ptr != NUL)
3665 {
3666 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3667 *ptr = '/';
3668 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3669 *ptr = '\\';
3670 ptr += (*mb_ptr2len)(ptr);
3671 }
3672 }
3673 }
3674#endif
glepnir8159fb12024-07-17 20:32:54 +02003675
3676 if (in_fuzzy)
3677 {
3678 ga_init2(&fuzzy_indices, sizeof(int), 10);
3679 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3680
3681 for (i = 0; i < num_matches; i++)
3682 {
3683 ptr = matches[i];
3684 score = fuzzy_match_str(ptr, leader);
3685 if (score > 0)
3686 {
3687 if (ga_grow(&fuzzy_indices, 1) == OK)
3688 {
3689 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3690 compl_fuzzy_scores[i] = score;
3691 fuzzy_indices.ga_len++;
3692 }
3693 }
3694 }
3695
Christian Brabandt220474d2024-07-20 13:26:44 +02003696 // prevent qsort from deref NULL pointer
3697 if (fuzzy_indices.ga_len > 0)
3698 {
3699 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3700 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003701
Christian Brabandt220474d2024-07-20 13:26:44 +02003702 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3703 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3704 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003705
Christian Brabandt220474d2024-07-20 13:26:44 +02003706 FreeWild(num_matches, matches);
3707 matches = sorted_matches;
3708 num_matches = fuzzy_indices.ga_len;
3709 }
glepnir6b6280c2024-07-27 16:25:45 +02003710 else if (leader_len > 0)
3711 {
3712 FreeWild(num_matches, matches);
3713 num_matches = 0;
3714 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003715
glepnir8159fb12024-07-17 20:32:54 +02003716 vim_free(compl_fuzzy_scores);
3717 ga_clear(&fuzzy_indices);
3718 }
3719
glepnir6b6280c2024-07-27 16:25:45 +02003720 if (num_matches > 0)
3721 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003722}
3723
3724/*
3725 * Get the next set of command-line completions matching "compl_pattern".
3726 */
3727 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003728get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003729{
3730 char_u **matches;
3731 int num_matches;
3732
John Marriott5e6ea922024-11-23 14:01:57 +01003733 if (expand_cmdline(&compl_xp, compl_pattern.string,
3734 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003735 ins_compl_add_matches(num_matches, matches, FALSE);
3736}
3737
3738/*
3739 * Get the next set of spell suggestions matching "compl_pattern".
3740 */
3741 static void
3742get_next_spell_completion(linenr_T lnum UNUSED)
3743{
3744#ifdef FEAT_SPELL
3745 char_u **matches;
3746 int num_matches;
3747
John Marriott5e6ea922024-11-23 14:01:57 +01003748 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003749 if (num_matches > 0)
3750 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003751 else
3752 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003753#endif
3754}
3755
3756/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003757 * Return the next word or line from buffer "ins_buf" at position
3758 * "cur_match_pos" for completion. The length of the match is set in "len".
3759 */
3760 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003761ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003762 buf_T *ins_buf, // buffer being scanned
3763 pos_T *cur_match_pos, // current match position
3764 int *match_len,
3765 int *cont_s_ipos) // next ^X<> will set initial_pos
3766{
3767 char_u *ptr;
3768 int len;
3769
3770 *match_len = 0;
3771 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3772 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003773 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003774 if (ctrl_x_mode_line_or_eval())
3775 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003776 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003777 {
3778 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3779 return NULL;
3780 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003781 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003782 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003783 {
3784 char_u *tmp_ptr = ptr;
3785
3786 ptr = skipwhite(tmp_ptr);
3787 len -= (int)(ptr - tmp_ptr);
3788 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003789 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003790 }
3791 else
3792 {
3793 char_u *tmp_ptr = ptr;
3794
John Marriott5e6ea922024-11-23 14:01:57 +01003795 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003796 {
3797 tmp_ptr += compl_length;
3798 // Skip if already inside a word.
3799 if (vim_iswordp(tmp_ptr))
3800 return NULL;
3801 // Find start of next word.
3802 tmp_ptr = find_word_start(tmp_ptr);
3803 }
3804 // Find end of this word.
3805 tmp_ptr = find_word_end(tmp_ptr);
3806 len = (int)(tmp_ptr - ptr);
3807
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003808 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003809 {
3810 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3811 {
3812 // Try next line, if any. the new word will be
3813 // "join" as if the normal command "J" was used.
3814 // IOSIZE is always greater than
3815 // compl_length, so the next STRNCPY always
3816 // works -- Acevedo
3817 STRNCPY(IObuff, ptr, len);
3818 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3819 tmp_ptr = ptr = skipwhite(ptr);
3820 // Find start of next word.
3821 tmp_ptr = find_word_start(tmp_ptr);
3822 // Find end of next word.
3823 tmp_ptr = find_word_end(tmp_ptr);
3824 if (tmp_ptr > ptr)
3825 {
3826 if (*ptr != ')' && IObuff[len - 1] != TAB)
3827 {
3828 if (IObuff[len - 1] != ' ')
3829 IObuff[len++] = ' ';
3830 // IObuf =~ "\k.* ", thus len >= 2
3831 if (p_js
3832 && (IObuff[len - 2] == '.'
3833 || (vim_strchr(p_cpo, CPO_JOINSP)
3834 == NULL
3835 && (IObuff[len - 2] == '?'
3836 || IObuff[len - 2] == '!'))))
3837 IObuff[len++] = ' ';
3838 }
3839 // copy as much as possible of the new word
3840 if (tmp_ptr - ptr >= IOSIZE - len)
3841 tmp_ptr = ptr + IOSIZE - len - 1;
3842 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3843 len += (int)(tmp_ptr - ptr);
3844 *cont_s_ipos = TRUE;
3845 }
3846 IObuff[len] = NUL;
3847 ptr = IObuff;
3848 }
3849 if (len == compl_length)
3850 return NULL;
3851 }
3852 }
3853
3854 *match_len = len;
3855 return ptr;
3856}
3857
3858/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003859 * Get the next set of words matching "compl_pattern" for default completion(s)
3860 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003861 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3862 * position "st->start_pos" in the "compl_direction" direction. If
3863 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3864 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003865 * Returns OK if a new next match is found, otherwise returns FAIL.
3866 */
3867 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003868get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003869{
3870 int found_new_match = FAIL;
3871 int save_p_scs;
3872 int save_p_ws;
3873 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003874 char_u *ptr = NULL;
3875 int len = 0;
3876 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3877 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003878
3879 // If 'infercase' is set, don't use 'smartcase' here
3880 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003881 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003882 p_scs = FALSE;
3883
3884 // Buffers other than curbuf are scanned from the beginning or the
3885 // end but never from the middle, thus setting nowrapscan in this
3886 // buffer is a good idea, on the other hand, we always set
3887 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3888 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003889 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003890 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003891 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003892 p_ws = TRUE;
3893 looped_around = FALSE;
3894 for (;;)
3895 {
3896 int cont_s_ipos = FALSE;
3897
3898 ++msg_silent; // Don't want messages for wrapscan.
3899
3900 // ctrl_x_mode_line_or_eval() || word-wise search that
3901 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003902 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003903 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01003904 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02003905 else if (in_fuzzy)
3906 found_new_match = search_for_fuzzy_match(st->ins_buf,
3907 st->cur_match_pos, leader, compl_direction,
3908 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003909 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003910 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01003911 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02003912 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003913 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003914 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003915 {
3916 // set "compl_started" even on fail
3917 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003918 st->first_match_pos = *st->cur_match_pos;
3919 st->last_match_pos = *st->cur_match_pos;
3920 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003921 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003922 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3923 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003924 {
3925 found_new_match = FAIL;
3926 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003927 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003928 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3929 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3930 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003931 {
3932 if (looped_around)
3933 found_new_match = FAIL;
3934 else
3935 looped_around = TRUE;
3936 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003937 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003938 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3939 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3940 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003941 {
3942 if (looped_around)
3943 found_new_match = FAIL;
3944 else
3945 looped_around = TRUE;
3946 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003947 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003948 if (found_new_match == FAIL)
3949 break;
3950
3951 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003952 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003953 && start_pos->lnum == st->cur_match_pos->lnum
3954 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003955 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003956
glepnir8159fb12024-07-17 20:32:54 +02003957 if (!in_fuzzy)
3958 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3959 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003960 if (ptr == NULL)
3961 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003962
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003963 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003964 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003965 0, cont_s_ipos) != NOTDONE)
3966 {
3967 found_new_match = OK;
3968 break;
3969 }
3970 }
3971 p_scs = save_p_scs;
3972 p_ws = save_p_ws;
3973
3974 return found_new_match;
3975}
3976
3977/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003978 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003979 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003980 */
3981 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003982get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003983{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003984 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003985
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003986 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003987 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003988 case -1:
3989 break;
3990#ifdef FEAT_FIND_ID
3991 case CTRL_X_PATH_PATTERNS:
3992 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003993 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003994 break;
3995#endif
3996
3997 case CTRL_X_DICTIONARY:
3998 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003999 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4000 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004001 break;
4002
4003 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004004 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004005 break;
4006
4007 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004008 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004009 break;
4010
4011 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004012 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004013 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004014 break;
4015
4016#ifdef FEAT_COMPL_FUNC
4017 case CTRL_X_FUNCTION:
4018 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004019 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004020 break;
4021#endif
4022
4023 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004024 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004025 break;
4026
4027 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004028 found_new_match = get_next_default_completion(st, ini);
4029 if (found_new_match == FAIL && st->ins_buf == curbuf)
4030 st->found_all = TRUE;
4031 }
4032
4033 // check if compl_curr_match has changed, (e.g. other type of
4034 // expansion added something)
4035 if (type != 0 && compl_curr_match != compl_old_match)
4036 found_new_match = OK;
4037
4038 return found_new_match;
4039}
4040
4041/*
4042 * Get the next expansion(s), using "compl_pattern".
4043 * The search starts at position "ini" in curbuf and in the direction
4044 * compl_direction.
4045 * When "compl_started" is FALSE start at that position, otherwise continue
4046 * where we stopped searching before.
4047 * This may return before finding all the matches.
4048 * Return the total number of matches or -1 if still unknown -- Acevedo
4049 */
4050 static int
4051ins_compl_get_exp(pos_T *ini)
4052{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004053 static ins_compl_next_state_T st;
4054 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004055 int i;
4056 int found_new_match;
4057 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004058 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004059
4060 if (!compl_started)
4061 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004062 buf_T *buf;
4063
4064 FOR_ALL_BUFFERS(buf)
4065 buf->b_scanned = 0;
4066 if (!st_cleared)
4067 {
4068 CLEAR_FIELD(st);
4069 st_cleared = TRUE;
4070 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071 st.found_all = FALSE;
4072 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004073 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004074 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004075 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4076 ? (char_u *)"." : curbuf->b_p_cpt);
4077 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004078 st.last_match_pos = st.first_match_pos = *ini;
4079 }
4080 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4081 st.ins_buf = curbuf; // In case the buffer was wiped out.
4082
4083 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004084 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004085 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004086
4087 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4088 for (;;)
4089 {
4090 found_new_match = FAIL;
4091 st.set_match_pos = FALSE;
4092
4093 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4094 // or if found_all says this entry is done. For ^X^L only use the
4095 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004096 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004097 && (!compl_started || st.found_all))
4098 {
glepnir8159fb12024-07-17 20:32:54 +02004099 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004100
4101 if (status == INS_COMPL_CPT_END)
4102 break;
4103 if (status == INS_COMPL_CPT_CONT)
4104 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004105 }
4106
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004107 // If complete() was called then compl_pattern has been reset. The
4108 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004109 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004110 break;
4111
4112 // get the next set of completion matches
4113 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004114
4115 // break the loop for specialized modes (use 'complete' just for the
4116 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4117 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004118 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4119 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004120 {
4121 if (got_int)
4122 break;
4123 // Fill the popup menu as soon as possible.
4124 if (type != -1)
4125 ins_compl_check_keys(0, FALSE);
4126
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004127 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004128 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4129 break;
4130 compl_started = TRUE;
4131 }
4132 else
4133 {
4134 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004135 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004136 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004137
4138 compl_started = FALSE;
4139 }
4140 }
4141 compl_started = TRUE;
4142
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004143 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004144 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004145 found_new_match = FAIL;
4146
4147 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004148 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004149 && !ctrl_x_mode_line_or_eval()))
4150 i = ins_compl_make_cyclic();
4151
4152 if (compl_old_match != NULL)
4153 {
4154 // If several matches were added (FORWARD) or the search failed and has
4155 // just been made cyclic then we have to move compl_curr_match to the
4156 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004157 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004158 : compl_old_match->cp_prev;
4159 if (compl_curr_match == NULL)
4160 compl_curr_match = compl_old_match;
4161 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004162 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004163
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004164 return i;
4165}
4166
4167/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004168 * Update "compl_shown_match" to the actually shown match, it may differ when
4169 * "compl_leader" is used to omit some of the matches.
4170 */
4171 static void
4172ins_compl_update_shown_match(void)
4173{
4174 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004175 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004176 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004177 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004178 compl_shown_match = compl_shown_match->cp_next;
4179
4180 // If we didn't find it searching forward, and compl_shows_dir is
4181 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004182 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004183 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004184 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004185 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004186 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004187 {
4188 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004189 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004190 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004191 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004192 compl_shown_match = compl_shown_match->cp_prev;
4193 }
4194}
4195
4196/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004197 * Delete the old text being completed.
4198 */
4199 void
4200ins_compl_delete(void)
4201{
4202 int col;
4203
4204 // In insert mode: Delete the typed part.
4205 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004206 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004207 if ((int)curwin->w_cursor.col > col)
4208 {
4209 if (stop_arrow() == FAIL)
4210 return;
4211 backspace_until_column(col);
4212 }
4213
4214 // TODO: is this sufficient for redrawing? Redrawing everything causes
4215 // flicker, thus we can't do that.
4216 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004217#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004218 // clear v:completed_item
4219 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004220#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004221}
4222
4223/*
4224 * Insert the new text being completed.
4225 * "in_compl_func" is TRUE when called from complete_check().
4226 */
4227 void
4228ins_compl_insert(int in_compl_func)
4229{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004230 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004231
4232 // Make sure we don't go over the end of the string, this can happen with
4233 // illegal bytes.
John Marriott5e6ea922024-11-23 14:01:57 +01004234 if (compl_len < (int)compl_shown_match->cp_str.length)
4235 ins_bytes(compl_shown_match->cp_str.string + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004236 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004237 compl_used_match = FALSE;
4238 else
4239 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004240#ifdef FEAT_EVAL
4241 {
4242 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4243
4244 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4245 }
4246#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004247 if (!in_compl_func)
4248 compl_curr_match = compl_shown_match;
4249}
4250
4251/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004252 * show the file name for the completion match (if any). Truncate the file
4253 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004254 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004255 static void
4256ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004257{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004258 char *lead = _("match in file");
4259 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4260 char_u *s;
4261 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004262
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004263 if (space <= 0)
4264 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004265
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004266 // We need the tail that fits. With double-byte encoding going
4267 // back from the end is very slow, thus go from the start and keep
4268 // the text that fits in "space" between "s" and "e".
4269 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004270 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004271 space -= ptr2cells(e);
4272 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004273 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004274 space += ptr2cells(s);
4275 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004276 }
4277 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004278 msg_hist_off = TRUE;
4279 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4280 s > compl_shown_match->cp_fname ? "<" : "", s);
4281 msg((char *)IObuff);
4282 msg_hist_off = FALSE;
4283 redraw_cmdline = FALSE; // don't overwrite!
4284}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004285
glepnirdca57fb2024-06-04 22:01:21 +02004286/*
zeertzjq551d8c32024-06-05 19:53:32 +02004287 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004288 */
glepnira218cc62024-06-03 19:32:39 +02004289 static compl_T *
4290find_comp_when_fuzzy(void)
4291{
4292 int score;
4293 char_u* str;
4294 int target_idx = -1;
4295 int is_forward = compl_shows_dir_forward();
4296 int is_backward = compl_shows_dir_backward();
4297 compl_T *comp = NULL;
4298
glepnir43eef882024-06-19 20:20:48 +02004299 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004300 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004301 return compl_first_match != compl_shown_match ? compl_first_match :
4302 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004303
4304 if (is_forward)
4305 target_idx = compl_selected_item + 1;
4306 else if (is_backward)
4307 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004308 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004309
4310 score = compl_match_array[target_idx].pum_score;
4311 str = compl_match_array[target_idx].pum_text;
4312
4313 comp = compl_first_match;
4314 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004315 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004316 return comp;
4317 comp = comp->cp_next;
4318 } while (comp != NULL && !is_first_match(comp));
4319
4320 return NULL;
4321}
4322
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004323/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004324 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004325 * times. The number of matches found is returned in 'num_matches'.
4326 *
4327 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4328 * get more completions. If it is FALSE, then do nothing when there are no more
4329 * completions in the given direction.
4330 *
4331 * If "advance" is TRUE, then completion will move to the first match.
4332 * Otherwise, the original text will be shown.
4333 *
4334 * Returns OK on success and -1 if the number of matches are unknown.
4335 */
4336 static int
4337find_next_completion_match(
4338 int allow_get_expansion,
4339 int todo, // repeat completion this many times
4340 int advance,
4341 int *num_matches)
4342{
4343 int found_end = FALSE;
4344 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004345 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004346 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4347 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004348
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004349 while (--todo >= 0)
4350 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004351 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004352 {
glepniraced8c22024-06-15 15:13:05 +02004353 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4354 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004355 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004356 && (is_first_match(compl_shown_match->cp_next)
4357 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004358 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004359 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004360 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004361 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004362 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004363 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4364 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004365 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004366 }
4367 else
4368 {
4369 if (!allow_get_expansion)
4370 {
4371 if (advance)
4372 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004373 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004374 compl_pending -= todo + 1;
4375 else
4376 compl_pending += todo + 1;
4377 }
4378 return -1;
4379 }
4380
4381 if (!compl_no_select && advance)
4382 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004383 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004384 --compl_pending;
4385 else
4386 ++compl_pending;
4387 }
4388
4389 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004390 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004391
4392 // handle any pending completions
4393 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004394 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004395 {
4396 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4397 {
4398 compl_shown_match = compl_shown_match->cp_next;
4399 --compl_pending;
4400 }
4401 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4402 {
4403 compl_shown_match = compl_shown_match->cp_prev;
4404 ++compl_pending;
4405 }
4406 else
4407 break;
4408 }
4409 found_end = FALSE;
4410 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004411 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004412 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004413 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004414 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004415 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004416 ++todo;
4417 else
4418 // Remember a matching item.
4419 found_compl = compl_shown_match;
4420
4421 // Stop at the end of the list when we found a usable match.
4422 if (found_end)
4423 {
4424 if (found_compl != NULL)
4425 {
4426 compl_shown_match = found_compl;
4427 break;
4428 }
4429 todo = 1; // use first usable match after wrapping around
4430 }
4431 }
4432
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004433 return OK;
4434}
4435
4436/*
4437 * Fill in the next completion in the current direction.
4438 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4439 * get more completions. If it is FALSE, then we just do nothing when there
4440 * are no more completions in a given direction. The latter case is used when
4441 * we are still in the middle of finding completions, to allow browsing
4442 * through the ones found so far.
4443 * Return the total number of matches, or -1 if still unknown -- webb.
4444 *
4445 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4446 * compl_shown_match here.
4447 *
4448 * Note that this function may be called recursively once only. First with
4449 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4450 * calls this function with "allow_get_expansion" FALSE.
4451 */
4452 static int
4453ins_compl_next(
4454 int allow_get_expansion,
4455 int count, // repeat completion this many times; should
4456 // be at least 1
4457 int insert_match, // Insert the newly selected match
4458 int in_compl_func) // called from complete_check()
4459{
4460 int num_matches = -1;
4461 int todo = count;
4462 int advance;
4463 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004464 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004465 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004466 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4467 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004468
4469 // When user complete function return -1 for findstart which is next
4470 // time of 'always', compl_shown_match become NULL.
4471 if (compl_shown_match == NULL)
4472 return -1;
4473
John Marriott5e6ea922024-11-23 14:01:57 +01004474 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004475 && !match_at_original_text(compl_shown_match)
4476 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004477 // Update "compl_shown_match" to the actually shown match
4478 ins_compl_update_shown_match();
4479
4480 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004481 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004482 // Delete old text to be replaced
4483 ins_compl_delete();
4484
4485 // When finding the longest common text we stick at the original text,
4486 // don't let CTRL-N or CTRL-P move to the first match.
4487 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4488
4489 // When restarting the search don't insert the first match either.
4490 if (compl_restarting)
4491 {
4492 advance = FALSE;
4493 compl_restarting = FALSE;
4494 }
4495
4496 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4497 // around.
4498 if (find_next_completion_match(allow_get_expansion, todo, advance,
4499 &num_matches) == -1)
4500 return -1;
4501
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004502 if (curbuf != orig_curbuf)
4503 {
4504 // In case some completion function switched buffer, don't want to
4505 // insert the completion elsewhere.
4506 return -1;
4507 }
4508
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004509 // Insert the text of the new completion, or the compl_leader.
4510 if (compl_no_insert && !started)
4511 {
John Marriott5e6ea922024-11-23 14:01:57 +01004512 ins_bytes(compl_orig_text.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004513 compl_used_match = FALSE;
4514 }
4515 else if (insert_match)
4516 {
4517 if (!compl_get_longest || compl_used_match)
4518 ins_compl_insert(in_compl_func);
4519 else
John Marriott5e6ea922024-11-23 14:01:57 +01004520 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004521 }
4522 else
4523 compl_used_match = FALSE;
4524
4525 if (!allow_get_expansion)
4526 {
4527 // may undisplay the popup menu first
4528 ins_compl_upd_pum();
4529
4530 if (pum_enough_matches())
4531 // Will display the popup menu, don't redraw yet to avoid flicker.
4532 pum_call_update_screen();
4533 else
4534 // Not showing the popup menu yet, redraw to show the user what was
4535 // inserted.
4536 update_screen(0);
4537
4538 // display the updated popup menu
4539 ins_compl_show_pum();
4540#ifdef FEAT_GUI
4541 if (gui.in_use)
4542 {
4543 // Show the cursor after the match, not after the redrawn text.
4544 setcursor();
4545 out_flush_cursor(FALSE, FALSE);
4546 }
4547#endif
4548
4549 // Delete old text to be replaced, since we're still searching and
4550 // don't want to match ourselves!
4551 ins_compl_delete();
4552 }
4553
4554 // Enter will select a match when the match wasn't inserted and the popup
4555 // menu is visible.
4556 if (compl_no_insert && !started)
4557 compl_enter_selects = TRUE;
4558 else
4559 compl_enter_selects = !insert_match && compl_match_array != NULL;
4560
4561 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004562 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004563 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004564
4565 return num_matches;
4566}
4567
4568/*
4569 * Call this while finding completions, to check whether the user has hit a key
4570 * that should change the currently displayed completion, or exit completion
4571 * mode. Also, when compl_pending is not zero, show a completion as soon as
4572 * possible. -- webb
4573 * "frequency" specifies out of how many calls we actually check.
4574 * "in_compl_func" is TRUE when called from complete_check(), don't set
4575 * compl_curr_match.
4576 */
4577 void
4578ins_compl_check_keys(int frequency, int in_compl_func)
4579{
4580 static int count = 0;
4581 int c;
4582
4583 // Don't check when reading keys from a script, :normal or feedkeys().
4584 // That would break the test scripts. But do check for keys when called
4585 // from complete_check().
4586 if (!in_compl_func && (using_script() || ex_normal_busy))
4587 return;
4588
4589 // Only do this at regular intervals
4590 if (++count < frequency)
4591 return;
4592 count = 0;
4593
4594 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4595 // can't do its work correctly.
4596 c = vpeekc_any();
4597 if (c != NUL)
4598 {
4599 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4600 {
4601 c = safe_vgetc(); // Eat the character
4602 compl_shows_dir = ins_compl_key2dir(c);
4603 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4604 c != K_UP && c != K_DOWN, in_compl_func);
4605 }
4606 else
4607 {
4608 // Need to get the character to have KeyTyped set. We'll put it
4609 // back with vungetc() below. But skip K_IGNORE.
4610 c = safe_vgetc();
4611 if (c != K_IGNORE)
4612 {
4613 // Don't interrupt completion when the character wasn't typed,
4614 // e.g., when doing @q to replay keys.
4615 if (c != Ctrl_R && KeyTyped)
4616 compl_interrupted = TRUE;
4617
4618 vungetc(c);
4619 }
4620 }
4621 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004622 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004623 {
4624 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4625
4626 compl_pending = 0;
4627 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4628 }
4629}
4630
4631/*
4632 * Decide the direction of Insert mode complete from the key typed.
4633 * Returns BACKWARD or FORWARD.
4634 */
4635 static int
4636ins_compl_key2dir(int c)
4637{
4638 if (c == Ctrl_P || c == Ctrl_L
4639 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4640 return BACKWARD;
4641 return FORWARD;
4642}
4643
4644/*
4645 * Return TRUE for keys that are used for completion only when the popup menu
4646 * is visible.
4647 */
4648 static int
4649ins_compl_pum_key(int c)
4650{
4651 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4652 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4653 || c == K_UP || c == K_DOWN);
4654}
4655
4656/*
4657 * Decide the number of completions to move forward.
4658 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4659 */
4660 static int
4661ins_compl_key2count(int c)
4662{
4663 int h;
4664
4665 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4666 {
4667 h = pum_get_height();
4668 if (h > 3)
4669 h -= 2; // keep some context
4670 return h;
4671 }
4672 return 1;
4673}
4674
4675/*
4676 * Return TRUE if completion with "c" should insert the match, FALSE if only
4677 * to change the currently selected completion.
4678 */
4679 static int
4680ins_compl_use_match(int c)
4681{
4682 switch (c)
4683 {
4684 case K_UP:
4685 case K_DOWN:
4686 case K_PAGEDOWN:
4687 case K_KPAGEDOWN:
4688 case K_S_DOWN:
4689 case K_PAGEUP:
4690 case K_KPAGEUP:
4691 case K_S_UP:
4692 return FALSE;
4693 }
4694 return TRUE;
4695}
4696
4697/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004698 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4699 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004700 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004701 * Uses the global variables: compl_cont_status and ctrl_x_mode
4702 */
4703 static int
4704get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4705{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004706 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004707 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004708 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004709 {
4710 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4711 ;
4712 compl_col += ++startcol;
4713 compl_length = curs_col - startcol;
4714 }
4715 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004716 {
John Marriott5e6ea922024-11-23 14:01:57 +01004717 compl_pattern.string = str_foldcase(line + compl_col,
4718 compl_length, NULL, 0);
4719 if (compl_pattern.string == NULL)
4720 {
4721 compl_pattern.length = 0;
4722 return FAIL;
4723 }
4724 compl_pattern.length = STRLEN(compl_pattern.string);
4725 }
4726 else
4727 {
4728 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4729 if (compl_pattern.string == NULL)
4730 {
4731 compl_pattern.length = 0;
4732 return FAIL;
4733 }
4734 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02004735 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004736 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004737 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004738 {
4739 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004740 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01004741 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004742
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004743 if (!vim_iswordp(line + compl_col)
4744 || (compl_col > 0
4745 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004746 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004747 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004748 prefixlen = 0;
4749 }
John Marriott5e6ea922024-11-23 14:01:57 +01004750
4751 // we need up to 2 extra chars for the prefix
4752 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
4753 compl_pattern.string = alloc(n);
4754 if (compl_pattern.string == NULL)
4755 {
4756 compl_pattern.length = 0;
4757 return FAIL;
4758 }
4759 STRCPY((char *)compl_pattern.string, prefix);
4760 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004761 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004762 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004763 }
4764 else if (--startcol < 0
4765 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4766 {
John Marriott5e6ea922024-11-23 14:01:57 +01004767 size_t len = STRLEN_LITERAL("\\<\\k\\k");
4768
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004769 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01004770 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
4771 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004772 {
John Marriott5e6ea922024-11-23 14:01:57 +01004773 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004774 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004775 }
John Marriott5e6ea922024-11-23 14:01:57 +01004776 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004777 compl_col += curs_col;
4778 compl_length = 0;
4779 }
4780 else
4781 {
4782 // Search the point of change class of multibyte character
4783 // or not a word single byte character backward.
4784 if (has_mbyte)
4785 {
4786 int base_class;
4787 int head_off;
4788
4789 startcol -= (*mb_head_off)(line, line + startcol);
4790 base_class = mb_get_class(line + startcol);
4791 while (--startcol >= 0)
4792 {
4793 head_off = (*mb_head_off)(line, line + startcol);
4794 if (base_class != mb_get_class(line + startcol
4795 - head_off))
4796 break;
4797 startcol -= head_off;
4798 }
4799 }
4800 else
4801 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4802 ;
4803 compl_col += ++startcol;
4804 compl_length = (int)curs_col - startcol;
4805 if (compl_length == 1)
4806 {
4807 // Only match word with at least two chars -- webb
4808 // there's no need to call quote_meta,
4809 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01004810 compl_pattern.string = alloc(7);
4811 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004812 {
John Marriott5e6ea922024-11-23 14:01:57 +01004813 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004814 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004815 }
John Marriott5e6ea922024-11-23 14:01:57 +01004816 STRCPY((char *)compl_pattern.string, "\\<");
4817 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
4818 STRCAT((char *)compl_pattern.string, "\\k");
4819 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004820 }
4821 else
4822 {
John Marriott5e6ea922024-11-23 14:01:57 +01004823 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
4824
4825 compl_pattern.string = alloc(n);
4826 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004827 {
John Marriott5e6ea922024-11-23 14:01:57 +01004828 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004829 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004830 }
John Marriott5e6ea922024-11-23 14:01:57 +01004831 STRCPY((char *)compl_pattern.string, "\\<");
4832 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004833 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004834 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004835 }
4836 }
4837
4838 return OK;
4839}
4840
4841/*
4842 * Get the pattern, column and length for whole line completion or for the
4843 * complete() function.
4844 * Sets the global variables: compl_col, compl_length and compl_pattern.
4845 */
4846 static int
4847get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4848{
4849 compl_col = (colnr_T)getwhitecols(line);
4850 compl_length = (int)curs_col - (int)compl_col;
4851 if (compl_length < 0) // cursor in indent: empty pattern
4852 compl_length = 0;
4853 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004854 {
John Marriott5e6ea922024-11-23 14:01:57 +01004855 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
4856 NULL, 0);
4857 if (compl_pattern.string == NULL)
4858 {
4859 compl_pattern.length = 0;
4860 return FAIL;
4861 }
4862 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02004863 }
John Marriott5e6ea922024-11-23 14:01:57 +01004864 else
4865 {
4866 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4867 if (compl_pattern.string == NULL)
4868 {
4869 compl_pattern.length = 0;
4870 return FAIL;
4871 }
4872 compl_pattern.length = (size_t)compl_length;
4873 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004874
4875 return OK;
4876}
4877
4878/*
4879 * Get the pattern, column and length for filename completion.
4880 * Sets the global variables: compl_col, compl_length and compl_pattern.
4881 */
4882 static int
4883get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4884{
4885 // Go back to just before the first filename character.
4886 if (startcol > 0)
4887 {
4888 char_u *p = line + startcol;
4889
4890 MB_PTR_BACK(line, p);
4891 while (p > line && vim_isfilec(PTR2CHAR(p)))
4892 MB_PTR_BACK(line, p);
4893 if (p == line && vim_isfilec(PTR2CHAR(p)))
4894 startcol = 0;
4895 else
4896 startcol = (int)(p - line) + 1;
4897 }
4898
4899 compl_col += startcol;
4900 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01004901 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
4902 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004903 {
John Marriott5e6ea922024-11-23 14:01:57 +01004904 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004905 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004906 }
4907
John Marriott5e6ea922024-11-23 14:01:57 +01004908 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004909
4910 return OK;
4911}
4912
4913/*
4914 * Get the pattern, column and length for command-line completion.
4915 * Sets the global variables: compl_col, compl_length and compl_pattern.
4916 */
4917 static int
4918get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4919{
John Marriott5e6ea922024-11-23 14:01:57 +01004920 compl_pattern.string = vim_strnsave(line, curs_col);
4921 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004922 {
John Marriott5e6ea922024-11-23 14:01:57 +01004923 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004924 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004925 }
John Marriott5e6ea922024-11-23 14:01:57 +01004926 compl_pattern.length = curs_col;
4927 set_cmd_context(&compl_xp, compl_pattern.string,
4928 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004929 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4930 || compl_xp.xp_context == EXPAND_NOTHING)
4931 // No completion possible, use an empty pattern to get a
4932 // "pattern not found" message.
4933 compl_col = curs_col;
4934 else
John Marriott5e6ea922024-11-23 14:01:57 +01004935 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004936 compl_length = curs_col - compl_col;
4937
4938 return OK;
4939}
4940
4941/*
4942 * Get the pattern, column and length for user defined completion ('omnifunc',
4943 * 'completefunc' and 'thesaurusfunc')
4944 * Sets the global variables: compl_col, compl_length and compl_pattern.
4945 * Uses the global variable: spell_bad_len
4946 */
4947 static int
4948get_userdefined_compl_info(colnr_T curs_col UNUSED)
4949{
4950 int ret = FAIL;
4951
4952#ifdef FEAT_COMPL_FUNC
4953 // Call user defined function 'completefunc' with "a:findstart"
4954 // set to 1 to obtain the length of text to use for completion.
4955 char_u *line;
4956 typval_T args[3];
4957 int col;
4958 char_u *funcname;
4959 pos_T pos;
4960 int save_State = State;
4961 callback_T *cb;
4962
4963 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4964 // length as a string
4965 funcname = get_complete_funcname(ctrl_x_mode);
4966 if (*funcname == NUL)
4967 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004968 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004969 ? "completefunc" : "omnifunc");
4970 return FAIL;
4971 }
4972
4973 args[0].v_type = VAR_NUMBER;
4974 args[0].vval.v_number = 1;
4975 args[1].v_type = VAR_STRING;
4976 args[1].vval.v_string = (char_u *)"";
4977 args[2].v_type = VAR_UNKNOWN;
4978 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004979 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004980 cb = get_insert_callback(ctrl_x_mode);
4981 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004982 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004983
4984 State = save_State;
4985 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004986 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004987 validate_cursor();
4988 if (!EQUAL_POS(curwin->w_cursor, pos))
4989 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004990 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004991 return FAIL;
4992 }
4993
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004994 // Return value -2 means the user complete function wants to cancel the
4995 // complete without an error, do the same if the function did not execute
4996 // successfully.
4997 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004998 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004999 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005000 if (col == -3)
5001 {
5002 ctrl_x_mode = CTRL_X_NORMAL;
5003 edit_submode = NULL;
5004 if (!shortmess(SHM_COMPLETIONMENU))
5005 msg_clr_cmdline();
5006 return FAIL;
5007 }
5008
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005009 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005010 // completion.
5011 compl_opt_refresh_always = FALSE;
5012 compl_opt_suppress_empty = FALSE;
5013
5014 if (col < 0)
5015 col = curs_col;
5016 compl_col = col;
5017 if (compl_col > curs_col)
5018 compl_col = curs_col;
5019
5020 // Setup variables for completion. Need to obtain "line" again,
5021 // it may have become invalid.
5022 line = ml_get(curwin->w_cursor.lnum);
5023 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005024 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5025 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005026 {
John Marriott5e6ea922024-11-23 14:01:57 +01005027 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005028 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005029 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005030
John Marriott5e6ea922024-11-23 14:01:57 +01005031 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005032 ret = OK;
5033#endif
5034
5035 return ret;
5036}
5037
5038/*
5039 * Get the pattern, column and length for spell completion.
5040 * Sets the global variables: compl_col, compl_length and compl_pattern.
5041 * Uses the global variable: spell_bad_len
5042 */
5043 static int
5044get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5045{
5046 int ret = FAIL;
5047#ifdef FEAT_SPELL
5048 char_u *line;
5049
5050 if (spell_bad_len > 0)
5051 compl_col = curs_col - spell_bad_len;
5052 else
5053 compl_col = spell_word_start(startcol);
5054 if (compl_col >= (colnr_T)startcol)
5055 {
5056 compl_length = 0;
5057 compl_col = curs_col;
5058 }
5059 else
5060 {
5061 spell_expand_check_cap(compl_col);
5062 compl_length = (int)curs_col - compl_col;
5063 }
5064 // Need to obtain "line" again, it may have become invalid.
5065 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005066 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5067 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005068 {
John Marriott5e6ea922024-11-23 14:01:57 +01005069 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005070 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005071 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005072
John Marriott5e6ea922024-11-23 14:01:57 +01005073 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005074 ret = OK;
5075#endif
5076
5077 return ret;
5078}
5079
5080/*
5081 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005082 * "startcol" - start column number of the completion pattern/text
5083 * "cur_col" - current cursor column
5084 * On return, "line_invalid" is set to TRUE, if the current line may have
5085 * become invalid and needs to be fetched again.
5086 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005087 */
5088 static int
5089compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5090{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005091 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005092 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5093 && !thesaurus_func_complete(ctrl_x_mode)))
5094 {
5095 return get_normal_compl_info(line, startcol, curs_col);
5096 }
5097 else if (ctrl_x_mode_line_or_eval())
5098 {
5099 return get_wholeline_compl_info(line, curs_col);
5100 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005101 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005102 {
5103 return get_filename_compl_info(line, startcol, curs_col);
5104 }
5105 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5106 {
5107 return get_cmdline_compl_info(line, curs_col);
5108 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005109 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005110 || thesaurus_func_complete(ctrl_x_mode))
5111 {
5112 if (get_userdefined_compl_info(curs_col) == FAIL)
5113 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005114 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005115 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005116 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005117 {
5118 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5119 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005120 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005121 }
5122 else
5123 {
5124 internal_error("ins_complete()");
5125 return FAIL;
5126 }
5127
5128 return OK;
5129}
5130
5131/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005132 * Continue an interrupted completion mode search in "line".
5133 *
5134 * If this same ctrl_x_mode has been interrupted use the text from
5135 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5136 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5137 * the same line as the cursor then fix it (the line has been split because it
5138 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5139 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005140 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005141 static void
5142ins_compl_continue_search(char_u *line)
5143{
5144 // it is a continued search
5145 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005146 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5147 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005148 {
5149 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5150 {
5151 // line (probably) wrapped, set compl_startpos to the
5152 // first non_blank in the line, if it is not a wordchar
5153 // include it to get a better pattern, but then we don't
5154 // want the "\\<" prefix, check it below
5155 compl_col = (colnr_T)getwhitecols(line);
5156 compl_startpos.col = compl_col;
5157 compl_startpos.lnum = curwin->w_cursor.lnum;
5158 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5159 }
5160 else
5161 {
5162 // S_IPOS was set when we inserted a word that was at the
5163 // beginning of the line, which means that we'll go to SOL
5164 // mode but first we need to redefine compl_startpos
5165 if (compl_cont_status & CONT_S_IPOS)
5166 {
5167 compl_cont_status |= CONT_SOL;
5168 compl_startpos.col = (colnr_T)(skipwhite(
5169 line + compl_length
5170 + compl_startpos.col) - line);
5171 }
5172 compl_col = compl_startpos.col;
5173 }
5174 compl_length = curwin->w_cursor.col - (int)compl_col;
5175 // IObuff is used to add a "word from the next line" would we
5176 // have enough space? just being paranoid
5177#define MIN_SPACE 75
5178 if (compl_length > (IOSIZE - MIN_SPACE))
5179 {
5180 compl_cont_status &= ~CONT_SOL;
5181 compl_length = (IOSIZE - MIN_SPACE);
5182 compl_col = curwin->w_cursor.col - compl_length;
5183 }
5184 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5185 if (compl_length < 1)
5186 compl_cont_status &= CONT_LOCAL;
5187 }
5188 else if (ctrl_x_mode_line_or_eval())
5189 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5190 else
5191 compl_cont_status = 0;
5192}
5193
5194/*
5195 * start insert mode completion
5196 */
5197 static int
5198ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005199{
5200 char_u *line;
5201 int startcol = 0; // column where searched text starts
5202 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005203 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005204 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005205 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005206
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005207 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005208
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005209 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005210 did_si = FALSE;
5211 can_si = FALSE;
5212 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005213 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005214 return FAIL;
5215
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005216 line = ml_get(curwin->w_cursor.lnum);
5217 curs_col = curwin->w_cursor.col;
5218 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005219
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005220 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5221 && compl_cont_mode == ctrl_x_mode)
5222 // this same ctrl-x_mode was interrupted previously. Continue the
5223 // completion.
5224 ins_compl_continue_search(line);
5225 else
5226 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005227
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005228 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005229 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005230 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005231 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005232 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5233 compl_cont_status = 0;
5234 compl_cont_status |= CONT_N_ADDS;
5235 compl_startpos = curwin->w_cursor;
5236 startcol = (int)curs_col;
5237 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005238 }
5239
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005240 // Work out completion pattern and original text -- webb
5241 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5242 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005243 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5244 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005245 // restore did_ai, so that adding comment leader works
5246 did_ai = save_did_ai;
5247 return FAIL;
5248 }
5249 // If "line" was changed while getting completion info get it again.
5250 if (line_invalid)
5251 line = ml_get(curwin->w_cursor.lnum);
5252
glepnir7cfe6932024-09-15 20:06:28 +02005253 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005254 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005255 {
5256 edit_submode_pre = (char_u *)_(" Adding");
5257 if (ctrl_x_mode_line_or_eval())
5258 {
5259 // Insert a new line, keep indentation but ignore 'comments'.
5260 char_u *old = curbuf->b_p_com;
5261
5262 curbuf->b_p_com = (char_u *)"";
5263 compl_startpos.lnum = curwin->w_cursor.lnum;
5264 compl_startpos.col = compl_col;
5265 ins_eol('\r');
5266 curbuf->b_p_com = old;
5267 compl_length = 0;
5268 compl_col = curwin->w_cursor.col;
5269 }
glepnir7cfe6932024-09-15 20:06:28 +02005270 else if (ctrl_x_mode_normal() && in_fuzzy)
5271 {
5272 compl_startpos = curwin->w_cursor;
5273 compl_cont_status &= CONT_S_IPOS;
5274 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005275 }
5276 else
5277 {
5278 edit_submode_pre = NULL;
5279 compl_startpos.col = compl_col;
5280 }
5281
5282 if (compl_cont_status & CONT_LOCAL)
5283 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5284 else
5285 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5286
5287 // If any of the original typed text has been changed we need to fix
5288 // the redo buffer.
5289 ins_compl_fixRedoBufForLeader(NULL);
5290
5291 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005292 VIM_CLEAR_STRING(compl_orig_text);
5293 compl_orig_text.length = (size_t)compl_length;
5294 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005295 if (p_ic)
5296 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005297 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5298 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005299 {
John Marriott5e6ea922024-11-23 14:01:57 +01005300 VIM_CLEAR_STRING(compl_pattern);
5301 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005302 return FAIL;
5303 }
5304
5305 // showmode might reset the internal line pointers, so it must
5306 // be called before line = ml_get(), or when this address is no
5307 // longer needed. -- Acevedo.
5308 edit_submode_extra = (char_u *)_("-- Searching...");
5309 edit_submode_highl = HLF_COUNT;
5310 showmode();
5311 edit_submode_extra = NULL;
5312 out_flush();
5313
5314 return OK;
5315}
5316
5317/*
5318 * display the completion status message
5319 */
5320 static void
5321ins_compl_show_statusmsg(void)
5322{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005323 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005324 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005325 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005326 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005327 ? (char_u *)_("Hit end of paragraph")
5328 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005329 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005330 }
5331
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005332 if (edit_submode_extra == NULL)
5333 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005334 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005335 {
5336 edit_submode_extra = (char_u *)_("Back at original");
5337 edit_submode_highl = HLF_W;
5338 }
5339 else if (compl_cont_status & CONT_S_IPOS)
5340 {
5341 edit_submode_extra = (char_u *)_("Word from other line");
5342 edit_submode_highl = HLF_COUNT;
5343 }
5344 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5345 {
5346 edit_submode_extra = (char_u *)_("The only match");
5347 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005348 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005349 }
5350 else
5351 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005352#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005353 // Update completion sequence number when needed.
5354 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005355 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005356#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005357 // The match should always have a sequence number now, this is
5358 // just a safety check.
5359 if (compl_curr_match->cp_number != -1)
5360 {
5361 // Space for 10 text chars. + 2x10-digit no.s = 31.
5362 // Translations may need more than twice that.
5363 static char_u match_ref[81];
5364
5365 if (compl_matches > 0)
5366 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005367 _("match %d of %d"),
5368 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005369 else
5370 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005371 _("match %d"),
5372 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005373 edit_submode_extra = match_ref;
5374 edit_submode_highl = HLF_R;
5375 if (dollar_vcol >= 0)
5376 curs_columns(FALSE);
5377 }
5378 }
5379 }
5380
5381 // Show a message about what (completion) mode we're in.
5382 if (!compl_opt_suppress_empty)
5383 {
5384 showmode();
5385 if (!shortmess(SHM_COMPLETIONMENU))
5386 {
5387 if (edit_submode_extra != NULL)
5388 {
5389 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005390 {
5391 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005392 msg_attr((char *)edit_submode_extra,
5393 edit_submode_highl < HLF_COUNT
5394 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005395 msg_hist_off = FALSE;
5396 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005397 }
5398 else
5399 msg_clr_cmdline(); // necessary for "noshowmode"
5400 }
5401 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005402}
5403
5404/*
5405 * Do Insert mode completion.
5406 * Called when character "c" was typed, which has a meaning for completion.
5407 * Returns OK if completion was done, FAIL if something failed (out of mem).
5408 */
5409 int
5410ins_complete(int c, int enable_pum)
5411{
5412 int n;
5413 int save_w_wrow;
5414 int save_w_leftcol;
5415 int insert_match;
5416
5417 compl_direction = ins_compl_key2dir(c);
5418 insert_match = ins_compl_use_match(c);
5419
5420 if (!compl_started)
5421 {
5422 if (ins_compl_start() == FAIL)
5423 return FAIL;
5424 }
5425 else if (insert_match && stop_arrow() == FAIL)
5426 return FAIL;
5427
5428 compl_shown_match = compl_curr_match;
5429 compl_shows_dir = compl_direction;
5430
5431 // Find next match (and following matches).
5432 save_w_wrow = curwin->w_wrow;
5433 save_w_leftcol = curwin->w_leftcol;
5434 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5435
5436 // may undisplay the popup menu
5437 ins_compl_upd_pum();
5438
5439 if (n > 1) // all matches have been found
5440 compl_matches = n;
5441 compl_curr_match = compl_shown_match;
5442 compl_direction = compl_shows_dir;
5443
5444 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5445 // mode.
5446 if (got_int && !global_busy)
5447 {
5448 (void)vgetc();
5449 got_int = FALSE;
5450 }
5451
5452 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005453 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005454 {
5455 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5456 // because we couldn't expand anything at first place, but if we used
5457 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5458 // (such as M in M'exico) if not tried already. -- Acevedo
5459 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005460 || compl_status_adding()
5461 || (ctrl_x_mode_not_default()
5462 && !ctrl_x_mode_path_patterns()
5463 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005464 compl_cont_status &= ~CONT_N_ADDS;
5465 }
5466
5467 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5468 compl_cont_status |= CONT_S_IPOS;
5469 else
5470 compl_cont_status &= ~CONT_S_IPOS;
5471
5472 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005473
5474 // Show the popup menu, unless we got interrupted.
5475 if (enable_pum && !compl_interrupted)
5476 show_pum(save_w_wrow, save_w_leftcol);
5477
5478 compl_was_interrupted = compl_interrupted;
5479 compl_interrupted = FALSE;
5480
5481 return OK;
5482}
5483
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005484/*
5485 * Remove (if needed) and show the popup menu
5486 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005487 static void
5488show_pum(int prev_w_wrow, int prev_w_leftcol)
5489{
5490 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005491 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005492 RedrawingDisabled = 0;
5493
5494 // If the cursor moved or the display scrolled we need to remove the pum
5495 // first.
5496 setcursor();
5497 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5498 ins_compl_del_pum();
5499
5500 ins_compl_show_pum();
5501 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005502
5503 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005504}
5505
5506/*
5507 * Looks in the first "len" chars. of "src" for search-metachars.
5508 * If dest is not NULL the chars. are copied there quoting (with
5509 * a backslash) the metachars, and dest would be NUL terminated.
5510 * Returns the length (needed) of dest
5511 */
5512 static unsigned
5513quote_meta(char_u *dest, char_u *src, int len)
5514{
5515 unsigned m = (unsigned)len + 1; // one extra for the NUL
5516
5517 for ( ; --len >= 0; src++)
5518 {
5519 switch (*src)
5520 {
5521 case '.':
5522 case '*':
5523 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005524 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005525 break;
5526 // FALLTHROUGH
5527 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005528 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005529 break;
5530 // FALLTHROUGH
5531 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005532 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005533 break;
5534 // FALLTHROUGH
5535 case '^': // currently it's not needed.
5536 case '$':
5537 m++;
5538 if (dest != NULL)
5539 *dest++ = '\\';
5540 break;
5541 }
5542 if (dest != NULL)
5543 *dest++ = *src;
5544 // Copy remaining bytes of a multibyte character.
5545 if (has_mbyte)
5546 {
5547 int i, mb_len;
5548
5549 mb_len = (*mb_ptr2len)(src) - 1;
5550 if (mb_len > 0 && len >= mb_len)
5551 for (i = 0; i < mb_len; ++i)
5552 {
5553 --len;
5554 ++src;
5555 if (dest != NULL)
5556 *dest++ = *src;
5557 }
5558 }
5559 }
5560 if (dest != NULL)
5561 *dest = NUL;
5562
5563 return m;
5564}
5565
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005566#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005567 void
5568free_insexpand_stuff(void)
5569{
John Marriott5e6ea922024-11-23 14:01:57 +01005570 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005571# ifdef FEAT_EVAL
5572 free_callback(&cfu_cb);
5573 free_callback(&ofu_cb);
5574 free_callback(&tsrfu_cb);
5575# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005576}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005577#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005578
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005579#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005580/*
5581 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5582 * spelled word, if there is one.
5583 */
5584 static void
5585spell_back_to_badword(void)
5586{
5587 pos_T tpos = curwin->w_cursor;
5588
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005589 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005590 if (curwin->w_cursor.col != tpos.col)
5591 start_arrow(&tpos);
5592}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005593#endif