blob: ba5f919a9b765c699e4fa3b18f0be2d6e1660c78 [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;
1231 int i;
1232 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
1245 do
1246 {
zeertzjq551d8c32024-06-05 19:53:32 +02001247 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1248 // set the cp_score for later comparisons.
John Marriott5e6ea922024-11-23 14:01:57 +01001249 if (compl_fuzzy_match && compl_leader.string != NULL && compl_leader.length > 0)
1250 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001251
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001252 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001253 && (compl_leader.string == NULL
1254 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02001255 || (compl_fuzzy_match && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001256 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001257 ++compl_match_arraysize;
glepnir80b66202024-11-27 21:53:53 +01001258 if (match_head == NULL)
1259 match_head = compl;
1260 else
1261 match_tail->cp_match_next = compl;
1262 match_tail = compl;
1263 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001264 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001265 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001266
1267 if (compl_match_arraysize == 0)
1268 return -1;
1269
1270 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1271 if (compl_match_array == NULL)
1272 return -1;
1273
1274 // If the current match is the original text don't find the first
1275 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001276 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001277 shown_match_ok = TRUE;
1278
John Marriott5e6ea922024-11-23 14:01:57 +01001279 if (compl_leader.string != NULL
1280 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
glepnir53387c52024-05-27 15:11:01 +02001281 && shown_match_ok == FALSE)
1282 compl_shown_match = compl_no_select ? compl_first_match
1283 : compl_first_match->cp_next;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001284 i = 0;
glepnir80b66202024-11-27 21:53:53 +01001285 compl = match_head;
1286 if (match_tail == match_head)
1287 did_find_shown_match = TRUE;
1288 while (compl != NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001289 {
glepnir80b66202024-11-27 21:53:53 +01001290 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001291 {
glepnir80b66202024-11-27 21:53:53 +01001292 if (compl == compl_shown_match || did_find_shown_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001293 {
glepnir80b66202024-11-27 21:53:53 +01001294 // This item is the shown match or this is the
1295 // first displayed item after the shown match.
1296 compl_shown_match = compl;
1297 did_find_shown_match = TRUE;
1298 shown_match_ok = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001299 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001300 else
glepnir80b66202024-11-27 21:53:53 +01001301 // Remember this displayed match for when the
1302 // shown match is just below it.
1303 shown_compl = compl;
1304 cur = i;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001305 }
glepnir80b66202024-11-27 21:53:53 +01001306 else if (compl_fuzzy_match)
1307 {
1308 if (i == 0)
1309 shown_compl = compl;
1310 // Update the maximum fuzzy score and the shown match
1311 // if the current item's score is higher
1312 if (compl->cp_score > max_fuzzy_score)
1313 {
1314 did_find_shown_match = TRUE;
1315 max_fuzzy_score = compl->cp_score;
1316 if (!compl_no_select)
1317 compl_shown_match = compl;
1318 }
1319
1320 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1321 {
1322 cur = i;
1323 shown_match_ok = TRUE;
1324 }
1325
1326 // If there is no "no select" condition and the max fuzzy
1327 // score is positive, or there is no completion leader or the
1328 // leader length is zero, mark the shown match as valid and
1329 // reset the current index.
1330 if (!compl_no_select
1331 && (max_fuzzy_score > 0
1332 || (compl_leader.string == NULL || compl_leader.length == 0)))
1333 {
1334 if (match_at_original_text(compl_shown_match))
1335 compl_shown_match = shown_compl;
1336 }
1337 }
1338
1339 if (compl->cp_text[CPT_ABBR] != NULL)
1340 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR];
1341 else
1342 compl_match_array[i].pum_text = compl->cp_str.string;
1343 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1344 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1345 compl_match_array[i].pum_score = compl->cp_score;
1346 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1347 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
1348 if (compl->cp_text[CPT_MENU] != NULL)
1349 compl_match_array[i++].pum_extra =
1350 compl->cp_text[CPT_MENU];
1351 else
1352 compl_match_array[i++].pum_extra = compl->cp_fname;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001353
glepnira218cc62024-06-03 19:32:39 +02001354 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001355 {
1356 did_find_shown_match = TRUE;
1357
1358 // When the original text is the shown match don't set
1359 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001360 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001361 shown_match_ok = TRUE;
1362
1363 if (!shown_match_ok && shown_compl != NULL)
1364 {
1365 // The shown match isn't displayed, set it to the
1366 // previously displayed match.
1367 compl_shown_match = shown_compl;
1368 shown_match_ok = TRUE;
1369 }
1370 }
glepnir80b66202024-11-27 21:53:53 +01001371 match_next = compl->cp_match_next;
1372 compl->cp_match_next = NULL;
1373 compl = match_next;
1374 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001375
John Marriott5e6ea922024-11-23 14:01:57 +01001376 if (compl_fuzzy_match && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001377 {
1378 for (i = 0; i < compl_match_arraysize; i++)
1379 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001380 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001381 qsort(compl_match_array, (size_t)compl_match_arraysize,
1382 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001383 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001384 }
glepnira218cc62024-06-03 19:32:39 +02001385
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001386 if (!shown_match_ok) // no displayed match at all
1387 cur = -1;
1388
1389 return cur;
1390}
1391
1392/*
1393 * Show the popup menu for the list of matches.
1394 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1395 */
1396 void
1397ins_compl_show_pum(void)
1398{
1399 int i;
1400 int cur = -1;
1401 colnr_T col;
1402
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001403 if (!pum_wanted() || !pum_enough_matches())
1404 return;
1405
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001406 // Update the screen later, before drawing the popup menu over it.
1407 pum_call_update_screen();
1408
1409 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001410 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001411 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001412 else
1413 {
1414 // popup menu already exists, only need to find the current item.
1415 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001416 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001417 || compl_match_array[i].pum_text
1418 == compl_shown_match->cp_text[CPT_ABBR])
1419 {
1420 cur = i;
1421 break;
1422 }
1423 }
1424
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001425 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001426 {
1427#ifdef FEAT_EVAL
1428 if (compl_started && has_completechanged())
1429 trigger_complete_changed_event(cur);
1430#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001431 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001432 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001433
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001434 // In Replace mode when a $ is displayed at the end of the line only
1435 // part of the screen would be updated. We do need to redraw here.
1436 dollar_vcol = -1;
1437
1438 // Compute the screen column of the start of the completed text.
1439 // Use the cursor to get all wrapping and other settings right.
1440 col = curwin->w_cursor.col;
1441 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001442 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001443 pum_display(compl_match_array, compl_match_arraysize, cur);
1444 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001445
glepnircbb46b42024-02-03 18:11:13 +01001446 // After adding leader, set the current match to shown match.
1447 if (compl_started && compl_curr_match != compl_shown_match)
1448 compl_curr_match = compl_shown_match;
1449
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001450#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001451 if (has_completechanged())
1452 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001453#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001454}
1455
1456#define DICT_FIRST (1) // use just first element in "dict"
1457#define DICT_EXACT (2) // "dict" is the exact name of a file
1458
1459/*
glepnir40c1c332024-06-11 19:37:04 +02001460 * Get current completion leader
1461 */
1462 char_u *
1463ins_compl_leader(void)
1464{
John Marriott5e6ea922024-11-23 14:01:57 +01001465 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1466}
1467
1468/*
1469 * Get current completion leader length
1470 */
1471 size_t
1472ins_compl_leader_len(void)
1473{
1474 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001475}
1476
1477/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001478 * Add any identifiers that match the given pattern "pat" in the list of
1479 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001480 */
1481 static void
1482ins_compl_dictionaries(
1483 char_u *dict_start,
1484 char_u *pat,
1485 int flags, // DICT_FIRST and/or DICT_EXACT
1486 int thesaurus) // Thesaurus completion
1487{
1488 char_u *dict = dict_start;
1489 char_u *ptr;
1490 char_u *buf;
1491 regmatch_T regmatch;
1492 char_u **files;
1493 int count;
1494 int save_p_scs;
1495 int dir = compl_direction;
1496
1497 if (*dict == NUL)
1498 {
1499#ifdef FEAT_SPELL
1500 // When 'dictionary' is empty and spell checking is enabled use
1501 // "spell".
1502 if (!thesaurus && curwin->w_p_spell)
1503 dict = (char_u *)"spell";
1504 else
1505#endif
1506 return;
1507 }
1508
1509 buf = alloc(LSIZE);
1510 if (buf == NULL)
1511 return;
1512 regmatch.regprog = NULL; // so that we can goto theend
1513
1514 // If 'infercase' is set, don't use 'smartcase' here
1515 save_p_scs = p_scs;
1516 if (curbuf->b_p_inf)
1517 p_scs = FALSE;
1518
1519 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1520 // to only match at the start of a line. Otherwise just match the
1521 // pattern. Also need to double backslashes.
1522 if (ctrl_x_mode_line_or_eval())
1523 {
1524 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1525 size_t len;
1526
1527 if (pat_esc == NULL)
1528 goto theend;
1529 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001530 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001531 if (ptr == NULL)
1532 {
1533 vim_free(pat_esc);
1534 goto theend;
1535 }
1536 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1537 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1538 vim_free(pat_esc);
1539 vim_free(ptr);
1540 }
1541 else
1542 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001543 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001544 if (regmatch.regprog == NULL)
1545 goto theend;
1546 }
1547
1548 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1549 regmatch.rm_ic = ignorecase(pat);
1550 while (*dict != NUL && !got_int && !compl_interrupted)
1551 {
1552 // copy one dictionary file name into buf
1553 if (flags == DICT_EXACT)
1554 {
1555 count = 1;
1556 files = &dict;
1557 }
1558 else
1559 {
1560 // Expand wildcards in the dictionary name, but do not allow
1561 // backticks (for security, the 'dict' option may have been set in
1562 // a modeline).
1563 copy_option_part(&dict, buf, LSIZE, ",");
1564# ifdef FEAT_SPELL
1565 if (!thesaurus && STRCMP(buf, "spell") == 0)
1566 count = -1;
1567 else
1568# endif
1569 if (vim_strchr(buf, '`') != NULL
1570 || expand_wildcards(1, &buf, &count, &files,
1571 EW_FILE|EW_SILENT) != OK)
1572 count = 0;
1573 }
1574
1575# ifdef FEAT_SPELL
1576 if (count == -1)
1577 {
1578 // Complete from active spelling. Skip "\<" in the pattern, we
1579 // don't use it as a RE.
1580 if (pat[0] == '\\' && pat[1] == '<')
1581 ptr = pat + 2;
1582 else
1583 ptr = pat;
1584 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1585 }
1586 else
1587# endif
1588 if (count > 0) // avoid warning for using "files" uninit
1589 {
1590 ins_compl_files(count, files, thesaurus, flags,
1591 &regmatch, buf, &dir);
1592 if (flags != DICT_EXACT)
1593 FreeWild(count, files);
1594 }
1595 if (flags != 0)
1596 break;
1597 }
1598
1599theend:
1600 p_scs = save_p_scs;
1601 vim_regfree(regmatch.regprog);
1602 vim_free(buf);
1603}
1604
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001605/*
1606 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1607 * skipping the word at 'skip_word'. Returns OK on success.
1608 */
1609 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001610thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001611 char_u *fname,
1612 char_u **buf_arg,
1613 int dir,
1614 char_u *skip_word)
1615{
1616 int status = OK;
1617 char_u *ptr;
1618 char_u *wstart;
1619
1620 // Add the other matches on the line
1621 ptr = *buf_arg;
1622 while (!got_int)
1623 {
1624 // Find start of the next word. Skip white
1625 // space and punctuation.
1626 ptr = find_word_start(ptr);
1627 if (*ptr == NUL || *ptr == NL)
1628 break;
1629 wstart = ptr;
1630
1631 // Find end of the word.
1632 if (has_mbyte)
1633 // Japanese words may have characters in
1634 // different classes, only separate words
1635 // with single-byte non-word characters.
1636 while (*ptr != NUL)
1637 {
1638 int l = (*mb_ptr2len)(ptr);
1639
1640 if (l < 2 && !vim_iswordc(*ptr))
1641 break;
1642 ptr += l;
1643 }
1644 else
1645 ptr = find_word_end(ptr);
1646
1647 // Add the word. Skip the regexp match.
1648 if (wstart != skip_word)
1649 {
1650 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1651 fname, dir, FALSE);
1652 if (status == FAIL)
1653 break;
1654 }
1655 }
1656
1657 *buf_arg = ptr;
1658 return status;
1659}
1660
1661/*
1662 * Process "count" dictionary/thesaurus "files" and add the text matching
1663 * "regmatch".
1664 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001665 static void
1666ins_compl_files(
1667 int count,
1668 char_u **files,
1669 int thesaurus,
1670 int flags,
1671 regmatch_T *regmatch,
1672 char_u *buf,
1673 int *dir)
1674{
1675 char_u *ptr;
1676 int i;
1677 FILE *fp;
1678 int add_r;
1679
1680 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1681 {
1682 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001683 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001684 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001685 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001686 vim_snprintf((char *)IObuff, IOSIZE,
1687 _("Scanning dictionary: %s"), (char *)files[i]);
1688 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1689 }
1690
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001691 if (fp == NULL)
1692 continue;
1693
1694 // Read dictionary file line by line.
1695 // Check each line for a match.
1696 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001697 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001698 ptr = buf;
1699 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001700 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001701 ptr = regmatch->startp[0];
1702 if (ctrl_x_mode_line_or_eval())
1703 ptr = find_line_end(ptr);
1704 else
1705 ptr = find_word_end(ptr);
1706 add_r = ins_compl_add_infercase(regmatch->startp[0],
1707 (int)(ptr - regmatch->startp[0]),
1708 p_ic, files[i], *dir, FALSE);
1709 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001710 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001711 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001712 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001713 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001714 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001715 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001716 if (add_r == OK)
1717 // if dir was BACKWARD then honor it just once
1718 *dir = FORWARD;
1719 else if (add_r == FAIL)
1720 break;
1721 // avoid expensive call to vim_regexec() when at end
1722 // of line
1723 if (*ptr == '\n' || got_int)
1724 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001725 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001726 line_breakcheck();
1727 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001728 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001729 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001730 }
1731}
1732
1733/*
1734 * Find the start of the next word.
1735 * Returns a pointer to the first char of the word. Also stops at a NUL.
1736 */
1737 char_u *
1738find_word_start(char_u *ptr)
1739{
1740 if (has_mbyte)
1741 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1742 ptr += (*mb_ptr2len)(ptr);
1743 else
1744 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1745 ++ptr;
1746 return ptr;
1747}
1748
1749/*
1750 * Find the end of the word. Assumes it starts inside a word.
1751 * Returns a pointer to just after the word.
1752 */
1753 char_u *
1754find_word_end(char_u *ptr)
1755{
1756 int start_class;
1757
1758 if (has_mbyte)
1759 {
1760 start_class = mb_get_class(ptr);
1761 if (start_class > 1)
1762 while (*ptr != NUL)
1763 {
1764 ptr += (*mb_ptr2len)(ptr);
1765 if (mb_get_class(ptr) != start_class)
1766 break;
1767 }
1768 }
1769 else
1770 while (vim_iswordc(*ptr))
1771 ++ptr;
1772 return ptr;
1773}
1774
1775/*
1776 * Find the end of the line, omitting CR and NL at the end.
1777 * Returns a pointer to just after the line.
1778 */
1779 static char_u *
1780find_line_end(char_u *ptr)
1781{
1782 char_u *s;
1783
1784 s = ptr + STRLEN(ptr);
1785 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1786 --s;
1787 return s;
1788}
1789
1790/*
1791 * Free the list of completions
1792 */
1793 static void
1794ins_compl_free(void)
1795{
1796 compl_T *match;
1797 int i;
1798
John Marriott5e6ea922024-11-23 14:01:57 +01001799 VIM_CLEAR_STRING(compl_pattern);
1800 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001801
1802 if (compl_first_match == NULL)
1803 return;
1804
1805 ins_compl_del_pum();
1806 pum_clear();
1807
1808 compl_curr_match = compl_first_match;
1809 do
1810 {
1811 match = compl_curr_match;
1812 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001813 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001814 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001815 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001816 vim_free(match->cp_fname);
1817 for (i = 0; i < CPT_COUNT; ++i)
1818 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001819#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001820 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001821#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001822 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001823 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001824 compl_first_match = compl_curr_match = NULL;
1825 compl_shown_match = NULL;
1826 compl_old_match = NULL;
1827}
1828
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001829/*
1830 * Reset/clear the completion state.
1831 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001832 void
1833ins_compl_clear(void)
1834{
1835 compl_cont_status = 0;
1836 compl_started = FALSE;
1837 compl_matches = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001838 VIM_CLEAR_STRING(compl_pattern);
1839 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001840 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001841 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001842 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001843#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001844 // clear v:completed_item
1845 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001846#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001847}
1848
1849/*
1850 * Return TRUE when Insert completion is active.
1851 */
1852 int
1853ins_compl_active(void)
1854{
1855 return compl_started;
1856}
1857
1858/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001859 * Selected one of the matches. When FALSE the match was edited or using the
1860 * longest common string.
1861 */
1862 int
1863ins_compl_used_match(void)
1864{
1865 return compl_used_match;
1866}
1867
1868/*
1869 * Initialize get longest common string.
1870 */
1871 void
1872ins_compl_init_get_longest(void)
1873{
1874 compl_get_longest = FALSE;
1875}
1876
1877/*
1878 * Returns TRUE when insert completion is interrupted.
1879 */
1880 int
1881ins_compl_interrupted(void)
1882{
1883 return compl_interrupted;
1884}
1885
1886/*
1887 * Returns TRUE if the <Enter> key selects a match in the completion popup
1888 * menu.
1889 */
1890 int
1891ins_compl_enter_selects(void)
1892{
1893 return compl_enter_selects;
1894}
1895
1896/*
1897 * Return the column where the text starts that is being completed
1898 */
1899 colnr_T
1900ins_compl_col(void)
1901{
1902 return compl_col;
1903}
1904
1905/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001906 * Return the length in bytes of the text being completed
1907 */
1908 int
1909ins_compl_len(void)
1910{
1911 return compl_length;
1912}
1913
1914/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001915 * Delete one character before the cursor and show the subset of the matches
1916 * that match the word that is now before the cursor.
1917 * Returns the character to be used, NUL if the work is done and another char
1918 * to be got from the user.
1919 */
1920 int
1921ins_compl_bs(void)
1922{
1923 char_u *line;
1924 char_u *p;
1925
1926 line = ml_get_curline();
1927 p = line + curwin->w_cursor.col;
1928 MB_PTR_BACK(line, p);
1929
1930 // Stop completion when the whole word was deleted. For Omni completion
1931 // allow the word to be deleted, we won't match everything.
1932 // Respect the 'backspace' option.
1933 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001934 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1935 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001936 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1937 - compl_length < 0))
1938 return K_BS;
1939
1940 // Deleted more than what was used to find matches or didn't finish
1941 // finding all matches: need to look for matches all over again.
1942 if (curwin->w_cursor.col <= compl_col + compl_length
1943 || ins_compl_need_restart())
1944 ins_compl_restart();
1945
John Marriott5e6ea922024-11-23 14:01:57 +01001946 VIM_CLEAR_STRING(compl_leader);
1947 compl_leader.length = (size_t)((p - line) - compl_col);
1948 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
1949 if (compl_leader.string == NULL)
1950 {
1951 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001952 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01001953 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001954
1955 ins_compl_new_leader();
1956 if (compl_shown_match != NULL)
1957 // Make sure current match is not a hidden item.
1958 compl_curr_match = compl_shown_match;
1959 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001960}
1961
1962/*
1963 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1964 * be called.
1965 */
1966 static int
1967ins_compl_need_restart(void)
1968{
1969 // Return TRUE if we didn't complete finding matches or when the
1970 // 'completefunc' returned "always" in the "refresh" dictionary item.
1971 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001972 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001973 && compl_opt_refresh_always);
1974}
1975
1976/*
1977 * Called after changing "compl_leader".
1978 * Show the popup menu with a different set of matches.
1979 * May also search for matches again if the previous search was interrupted.
1980 */
1981 static void
1982ins_compl_new_leader(void)
1983{
1984 ins_compl_del_pum();
1985 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01001986 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001987 compl_used_match = FALSE;
1988
1989 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01001990 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001991 else
1992 {
1993#ifdef FEAT_SPELL
1994 spell_bad_len = 0; // need to redetect bad word
1995#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001996 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001997 // the popup menu display the changed text before the cursor. Set
1998 // "compl_restarting" to avoid that the first match is inserted.
1999 pum_call_update_screen();
2000#ifdef FEAT_GUI
2001 if (gui.in_use)
2002 {
2003 // Show the cursor after the match, not after the redrawn text.
2004 setcursor();
2005 out_flush_cursor(FALSE, FALSE);
2006 }
2007#endif
2008 compl_restarting = TRUE;
2009 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2010 compl_cont_status = 0;
2011 compl_restarting = FALSE;
2012 }
2013
2014 compl_enter_selects = !compl_used_match;
2015
2016 // Show the popup menu with a different set of matches.
2017 ins_compl_show_pum();
2018
2019 // Don't let Enter select the original text when there is no popup menu.
2020 if (compl_match_array == NULL)
2021 compl_enter_selects = FALSE;
2022}
2023
2024/*
2025 * Return the length of the completion, from the completion start column to
2026 * the cursor column. Making sure it never goes below zero.
2027 */
2028 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002029get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002030{
2031 int off = (int)curwin->w_cursor.col - (int)compl_col;
2032
2033 if (off < 0)
2034 return 0;
2035 return off;
2036}
2037
2038/*
2039 * Append one character to the match leader. May reduce the number of
2040 * matches.
2041 */
2042 void
2043ins_compl_addleader(int c)
2044{
2045 int cc;
2046
2047 if (stop_arrow() == FAIL)
2048 return;
2049 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2050 {
2051 char_u buf[MB_MAXBYTES + 1];
2052
2053 (*mb_char2bytes)(c, buf);
2054 buf[cc] = NUL;
2055 ins_char_bytes(buf, cc);
2056 if (compl_opt_refresh_always)
2057 AppendToRedobuff(buf);
2058 }
2059 else
2060 {
2061 ins_char(c);
2062 if (compl_opt_refresh_always)
2063 AppendCharToRedobuff(c);
2064 }
2065
2066 // If we didn't complete finding matches we must search again.
2067 if (ins_compl_need_restart())
2068 ins_compl_restart();
2069
2070 // When 'always' is set, don't reset compl_leader. While completing,
2071 // cursor doesn't point original position, changing compl_leader would
2072 // break redo.
2073 if (!compl_opt_refresh_always)
2074 {
John Marriott5e6ea922024-11-23 14:01:57 +01002075 VIM_CLEAR_STRING(compl_leader);
2076 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2077 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2078 compl_leader.length);
2079 if (compl_leader.string == NULL)
2080 {
2081 compl_leader.length = 0;
2082 return;
2083 }
2084
2085 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002086 }
2087}
2088
2089/*
2090 * Setup for finding completions again without leaving CTRL-X mode. Used when
2091 * BS or a key was typed while still searching for matches.
2092 */
2093 static void
2094ins_compl_restart(void)
2095{
2096 ins_compl_free();
2097 compl_started = FALSE;
2098 compl_matches = 0;
2099 compl_cont_status = 0;
2100 compl_cont_mode = 0;
2101}
2102
2103/*
2104 * Set the first match, the original text.
2105 */
2106 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002107ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002108{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002109 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002110 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2111 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002112 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002113 {
John Marriott5e6ea922024-11-23 14:01:57 +01002114 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002115 if (p != NULL)
2116 {
John Marriott5e6ea922024-11-23 14:01:57 +01002117 VIM_CLEAR_STRING(compl_first_match->cp_str);
2118 compl_first_match->cp_str.string = p;
2119 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002120 }
2121 }
2122 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002123 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002124 {
John Marriott5e6ea922024-11-23 14:01:57 +01002125 char_u *p = vim_strnsave(str, len);
2126 if (p != NULL)
2127 {
2128 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2129 compl_first_match->cp_prev->cp_str.string = p;
2130 compl_first_match->cp_prev->cp_str.length = len;
2131 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002132 }
2133}
2134
2135/*
2136 * Append one character to the match leader. May reduce the number of
2137 * matches.
2138 */
2139 void
2140ins_compl_addfrommatch(void)
2141{
2142 char_u *p;
2143 int len = (int)curwin->w_cursor.col - (int)compl_col;
2144 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002145
John Marriott5e6ea922024-11-23 14:01:57 +01002146 p = compl_shown_match->cp_str.string;
2147 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002148 {
John Marriott5e6ea922024-11-23 14:01:57 +01002149 size_t plen;
2150 compl_T *cp;
2151
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002152 // When still at the original match use the first entry that matches
2153 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002154 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002155 return;
2156
2157 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002158 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002159 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002160 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002161 {
John Marriott5e6ea922024-11-23 14:01:57 +01002162 if (compl_leader.string == NULL
2163 || ins_compl_equal(cp, compl_leader.string,
2164 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002165 {
John Marriott5e6ea922024-11-23 14:01:57 +01002166 p = cp->cp_str.string;
2167 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002168 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002169 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002170 }
John Marriott5e6ea922024-11-23 14:01:57 +01002171 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002172 return;
2173 }
2174 p += len;
2175 c = PTR2CHAR(p);
2176 ins_compl_addleader(c);
2177}
2178
2179/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002180 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002181 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2182 * compl_cont_mode and compl_cont_status.
2183 * Returns TRUE when the character is not to be inserted.
2184 */
2185 static int
2186set_ctrl_x_mode(int c)
2187{
2188 int retval = FALSE;
2189
2190 switch (c)
2191 {
2192 case Ctrl_E:
2193 case Ctrl_Y:
2194 // scroll the window one line up or down
2195 ctrl_x_mode = CTRL_X_SCROLL;
2196 if (!(State & REPLACE_FLAG))
2197 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2198 else
2199 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2200 edit_submode_pre = NULL;
2201 showmode();
2202 break;
2203 case Ctrl_L:
2204 // complete whole line
2205 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2206 break;
2207 case Ctrl_F:
2208 // complete filenames
2209 ctrl_x_mode = CTRL_X_FILES;
2210 break;
2211 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002212 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002213 ctrl_x_mode = CTRL_X_DICTIONARY;
2214 break;
2215 case Ctrl_R:
2216 // Register insertion without exiting CTRL-X mode
2217 // Simply allow ^R to happen without affecting ^X mode
2218 break;
2219 case Ctrl_T:
2220 // complete words from a thesaurus
2221 ctrl_x_mode = CTRL_X_THESAURUS;
2222 break;
2223#ifdef FEAT_COMPL_FUNC
2224 case Ctrl_U:
2225 // user defined completion
2226 ctrl_x_mode = CTRL_X_FUNCTION;
2227 break;
2228 case Ctrl_O:
2229 // omni completion
2230 ctrl_x_mode = CTRL_X_OMNI;
2231 break;
2232#endif
2233 case 's':
2234 case Ctrl_S:
2235 // complete spelling suggestions
2236 ctrl_x_mode = CTRL_X_SPELL;
2237#ifdef FEAT_SPELL
2238 ++emsg_off; // Avoid getting the E756 error twice.
2239 spell_back_to_badword();
2240 --emsg_off;
2241#endif
2242 break;
2243 case Ctrl_RSB:
2244 // complete tag names
2245 ctrl_x_mode = CTRL_X_TAGS;
2246 break;
2247#ifdef FEAT_FIND_ID
2248 case Ctrl_I:
2249 case K_S_TAB:
2250 // complete keywords from included files
2251 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2252 break;
2253 case Ctrl_D:
2254 // complete definitions from included files
2255 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2256 break;
2257#endif
2258 case Ctrl_V:
2259 case Ctrl_Q:
2260 // complete vim commands
2261 ctrl_x_mode = CTRL_X_CMDLINE;
2262 break;
2263 case Ctrl_Z:
2264 // stop completion
2265 ctrl_x_mode = CTRL_X_NORMAL;
2266 edit_submode = NULL;
2267 showmode();
2268 retval = TRUE;
2269 break;
2270 case Ctrl_P:
2271 case Ctrl_N:
2272 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2273 // just started ^X mode, or there were enough ^X's to cancel
2274 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2275 // do normal expansion when interrupting a different mode (say
2276 // ^X^F^X^P or ^P^X^X^P, see below)
2277 // nothing changes if interrupting mode 0, (eg, the flag
2278 // doesn't change when going to ADDING mode -- Acevedo
2279 if (!(compl_cont_status & CONT_INTRPT))
2280 compl_cont_status |= CONT_LOCAL;
2281 else if (compl_cont_mode != 0)
2282 compl_cont_status &= ~CONT_LOCAL;
2283 // FALLTHROUGH
2284 default:
2285 // If we have typed at least 2 ^X's... for modes != 0, we set
2286 // compl_cont_status = 0 (eg, as if we had just started ^X
2287 // mode).
2288 // For mode 0, we set "compl_cont_mode" to an impossible
2289 // value, in both cases ^X^X can be used to restart the same
2290 // mode (avoiding ADDING mode).
2291 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2292 // 'complete' and local ^P expansions respectively.
2293 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2294 // mode -- Acevedo
2295 if (c == Ctrl_X)
2296 {
2297 if (compl_cont_mode != 0)
2298 compl_cont_status = 0;
2299 else
2300 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2301 }
2302 ctrl_x_mode = CTRL_X_NORMAL;
2303 edit_submode = NULL;
2304 showmode();
2305 break;
2306 }
2307
2308 return retval;
2309}
2310
2311/*
2312 * Stop insert completion mode
2313 */
2314 static int
2315ins_compl_stop(int c, int prev_mode, int retval)
2316{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002317 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002318
2319 // Get here when we have finished typing a sequence of ^N and
2320 // ^P or other completion characters in CTRL-X mode. Free up
2321 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002322 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002323 {
John Marriott5e6ea922024-11-23 14:01:57 +01002324 char_u *ptr;
2325
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002326 // If any of the original typed text has been changed, eg when
2327 // ignorecase is set, we must add back-spaces to the redo
2328 // buffer. We add as few as necessary to delete just the part
2329 // of the original text that has changed.
2330 // When using the longest match, edited the match or used
2331 // CTRL-E then don't use the current match.
2332 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002333 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002334 else
2335 ptr = NULL;
2336 ins_compl_fixRedoBufForLeader(ptr);
2337 }
2338
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002339 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002340
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002341 // When completing whole lines: fix indent for 'cindent'.
2342 // Otherwise, break line if it's too long.
2343 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2344 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002345 // re-indent the current line
2346 if (want_cindent)
2347 {
2348 do_c_expr_indent();
2349 want_cindent = FALSE; // don't do it again
2350 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002351 }
2352 else
2353 {
2354 int prev_col = curwin->w_cursor.col;
2355
2356 // put the cursor on the last char, for 'tw' formatting
2357 if (prev_col > 0)
2358 dec_cursor();
2359 // only format when something was inserted
2360 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2361 insertchar(NUL, 0, -1);
2362 if (prev_col > 0
2363 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2364 inc_cursor();
2365 }
2366
2367 // If the popup menu is displayed pressing CTRL-Y means accepting
2368 // the selection without inserting anything. When
2369 // compl_enter_selects is set the Enter key does the same.
2370 if ((c == Ctrl_Y || (compl_enter_selects
2371 && (c == CAR || c == K_KENTER || c == NL)))
2372 && pum_visible())
2373 retval = TRUE;
2374
2375 // CTRL-E means completion is Ended, go back to the typed text.
2376 // but only do this, if the Popup is still visible
2377 if (c == Ctrl_E)
2378 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002379 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002380 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002381
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002382 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002383 if (compl_leader.string != NULL)
2384 {
2385 p = compl_leader.string;
2386 plen = compl_leader.length;
2387 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002388 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002389 {
2390 p = compl_orig_text.string;
2391 plen = compl_orig_text.length;
2392 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002393 if (p != NULL)
2394 {
2395 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002396
John Marriott5e6ea922024-11-23 14:01:57 +01002397 if ((int)plen > compl_len)
2398 ins_bytes_len(p + compl_len, (int)(plen - compl_len));
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002399 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002400 retval = TRUE;
2401 }
2402
2403 auto_format(FALSE, TRUE);
2404
2405 // Trigger the CompleteDonePre event to give scripts a chance to
2406 // act upon the completion before clearing the info, and restore
2407 // ctrl_x_mode, so that complete_info() can be used.
2408 ctrl_x_mode = prev_mode;
2409 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2410
2411 ins_compl_free();
2412 compl_started = FALSE;
2413 compl_matches = 0;
2414 if (!shortmess(SHM_COMPLETIONMENU))
2415 msg_clr_cmdline(); // necessary for "noshowmode"
2416 ctrl_x_mode = CTRL_X_NORMAL;
2417 compl_enter_selects = FALSE;
2418 if (edit_submode != NULL)
2419 {
2420 edit_submode = NULL;
2421 showmode();
2422 }
2423
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002424 if (c == Ctrl_C && cmdwin_type != 0)
2425 // Avoid the popup menu remains displayed when leaving the
2426 // command line window.
2427 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002428 // Indent now if a key was typed that is in 'cinkeys'.
2429 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2430 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002431 // Trigger the CompleteDone event to give scripts a chance to act
2432 // upon the end of completion.
2433 ins_apply_autocmds(EVENT_COMPLETEDONE);
2434
2435 return retval;
2436}
2437
2438/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002439 * Prepare for Insert mode completion, or stop it.
2440 * Called just after typing a character in Insert mode.
2441 * Returns TRUE when the character is not to be inserted;
2442 */
2443 int
2444ins_compl_prep(int c)
2445{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002446 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002447 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002448
2449 // Forget any previous 'special' messages if this is actually
2450 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2451 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2452 edit_submode_extra = NULL;
2453
zeertzjq440d4cb2023-03-02 17:51:32 +00002454 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002455 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002456 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002457 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002458 return retval;
2459
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002460#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002461 // Ignore mouse events in a popup window
2462 if (is_mouse_key(c))
2463 {
2464 // Ignore drag and release events, the position does not need to be in
2465 // the popup and it may have just closed.
2466 if (c == K_LEFTRELEASE
2467 || c == K_LEFTRELEASE_NM
2468 || c == K_MIDDLERELEASE
2469 || c == K_RIGHTRELEASE
2470 || c == K_X1RELEASE
2471 || c == K_X2RELEASE
2472 || c == K_LEFTDRAG
2473 || c == K_MIDDLEDRAG
2474 || c == K_RIGHTDRAG
2475 || c == K_X1DRAG
2476 || c == K_X2DRAG)
2477 return retval;
2478 if (popup_visible)
2479 {
2480 int row = mouse_row;
2481 int col = mouse_col;
2482 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2483
2484 if (wp != NULL && WIN_IS_POPUP(wp))
2485 return retval;
2486 }
2487 }
2488#endif
2489
zeertzjqdca29d92021-08-31 19:12:51 +02002490 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2491 {
2492 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2493 || !vim_is_ctrl_x_key(c))
2494 {
2495 // Not starting another completion mode.
2496 ctrl_x_mode = CTRL_X_CMDLINE;
2497
2498 // CTRL-X CTRL-Z should stop completion without inserting anything
2499 if (c == Ctrl_Z)
2500 retval = TRUE;
2501 }
2502 else
2503 {
2504 ctrl_x_mode = CTRL_X_CMDLINE;
2505
2506 // Other CTRL-X keys first stop completion, then start another
2507 // completion mode.
2508 ins_compl_prep(' ');
2509 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2510 }
2511 }
2512
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002513 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002514 if (ctrl_x_mode_not_defined_yet()
2515 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002516 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002517 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002518 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002519 }
2520
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002521 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002522 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2523 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002524 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002525 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002526 {
2527 // We're already in CTRL-X mode, do we stay in it?
2528 if (!vim_is_ctrl_x_key(c))
2529 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002530 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002531 ctrl_x_mode = CTRL_X_NORMAL;
2532 else
2533 ctrl_x_mode = CTRL_X_FINISHED;
2534 edit_submode = NULL;
2535 }
2536 showmode();
2537 }
2538
2539 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2540 {
2541 // Show error message from attempted keyword completion (probably
2542 // 'Pattern not found') until another key is hit, then go back to
2543 // showing what mode we are in.
2544 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002545 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002546 && c != Ctrl_R && !ins_compl_pum_key(c))
2547 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002548 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002549 }
2550 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2551 // Trigger the CompleteDone event to give scripts a chance to act
2552 // upon the (possibly failed) completion.
2553 ins_apply_autocmds(EVENT_COMPLETEDONE);
2554
LemonBoy2bf52dd2022-04-09 18:17:34 +01002555 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002556
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002557 // reset continue_* if we left expansion-mode, if we stay they'll be
2558 // (re)set properly in ins_complete()
2559 if (!vim_is_ctrl_x_key(c))
2560 {
2561 compl_cont_status = 0;
2562 compl_cont_mode = 0;
2563 }
2564
2565 return retval;
2566}
2567
2568/*
2569 * Fix the redo buffer for the completion leader replacing some of the typed
2570 * text. This inserts backspaces and appends the changed text.
2571 * "ptr" is the known leader text or NUL.
2572 */
2573 static void
2574ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2575{
John Marriott5e6ea922024-11-23 14:01:57 +01002576 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002577 char_u *p;
2578 char_u *ptr = ptr_arg;
2579
2580 if (ptr == NULL)
2581 {
John Marriott5e6ea922024-11-23 14:01:57 +01002582 if (compl_leader.string != NULL)
2583 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002584 else
2585 return; // nothing to do
2586 }
John Marriott5e6ea922024-11-23 14:01:57 +01002587 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002588 {
John Marriott5e6ea922024-11-23 14:01:57 +01002589 p = compl_orig_text.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002590 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2591 ;
2592 if (len > 0)
2593 len -= (*mb_head_off)(p, p + len);
2594 for (p += len; *p != NUL; MB_PTR_ADV(p))
2595 AppendCharToRedobuff(K_BS);
2596 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002597 if (ptr != NULL)
2598 AppendToRedobuffLit(ptr + len, -1);
2599}
2600
2601/*
2602 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2603 * (depending on flag) starting from buf and looking for a non-scanned
2604 * buffer (other than curbuf). curbuf is special, if it is called with
2605 * buf=curbuf then it has to be the first call for a given flag/expansion.
2606 *
2607 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2608 */
2609 static buf_T *
2610ins_compl_next_buf(buf_T *buf, int flag)
2611{
2612 static win_T *wp = NULL;
2613
2614 if (flag == 'w') // just windows
2615 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002616 if (buf == curbuf || !win_valid(wp))
2617 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002618 wp = curwin;
2619 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2620 && wp->w_buffer->b_scanned)
2621 ;
2622 buf = wp->w_buffer;
2623 }
2624 else
2625 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2626 // (unlisted buffers)
2627 // When completing whole lines skip unloaded buffers.
2628 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2629 && ((flag == 'U'
2630 ? buf->b_p_bl
2631 : (!buf->b_p_bl
2632 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2633 || buf->b_scanned))
2634 ;
2635 return buf;
2636}
2637
2638#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002639
2640# ifdef FEAT_EVAL
2641static callback_T cfu_cb; // 'completefunc' callback function
2642static callback_T ofu_cb; // 'omnifunc' callback function
2643static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2644# endif
2645
2646/*
2647 * Copy a global callback function to a buffer local callback.
2648 */
2649 static void
2650copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2651{
2652 free_callback(bufcb);
2653 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2654 copy_callback(bufcb, globcb);
2655}
2656
2657/*
2658 * Parse the 'completefunc' option value and set the callback function.
2659 * Invoked when the 'completefunc' option is set. The option value can be a
2660 * name of a function (string), or function(<name>) or funcref(<name>) or a
2661 * lambda expression.
2662 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002663 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002664did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002665{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002666 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2667 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002668
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002669 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002670
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002671 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002672}
2673
2674/*
2675 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002676 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002677 */
2678 void
2679set_buflocal_cfu_callback(buf_T *buf UNUSED)
2680{
2681# ifdef FEAT_EVAL
2682 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2683# endif
2684}
2685
2686/*
2687 * Parse the 'omnifunc' option value and set the callback function.
2688 * Invoked when the 'omnifunc' option is set. The option value can be a
2689 * name of a function (string), or function(<name>) or funcref(<name>) or a
2690 * lambda expression.
2691 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002692 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002693did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002694{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002695 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2696 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002697
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002698 set_buflocal_ofu_callback(curbuf);
2699 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002700}
2701
2702/*
2703 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002704 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002705 */
2706 void
2707set_buflocal_ofu_callback(buf_T *buf UNUSED)
2708{
2709# ifdef FEAT_EVAL
2710 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2711# endif
2712}
2713
2714/*
2715 * Parse the 'thesaurusfunc' option value and set the callback function.
2716 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2717 * name of a function (string), or function(<name>) or funcref(<name>) or a
2718 * lambda expression.
2719 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002720 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002721did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002722{
2723 int retval;
2724
zeertzjq6eda2692024-11-03 09:23:33 +01002725 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002726 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002727 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2728 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002729 else
2730 {
2731 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002732 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002733 // when using :set, free the local callback
2734 if (!(args->os_flags & OPT_GLOBAL))
2735 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002736 }
2737
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002738 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002739}
2740
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002741/*
2742 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002743 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002744 */
2745 int
2746set_ref_in_insexpand_funcs(int copyID)
2747{
2748 int abort = FALSE;
2749
2750 abort = set_ref_in_callback(&cfu_cb, copyID);
2751 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2752 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2753
2754 return abort;
2755}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002756
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002757/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002758 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002759 */
2760 static char_u *
2761get_complete_funcname(int type)
2762{
2763 switch (type)
2764 {
2765 case CTRL_X_FUNCTION:
2766 return curbuf->b_p_cfu;
2767 case CTRL_X_OMNI:
2768 return curbuf->b_p_ofu;
2769 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002770 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002771 default:
2772 return (char_u *)"";
2773 }
2774}
2775
2776/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002777 * Get the callback to use for insert mode completion.
2778 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002779 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002780get_insert_callback(int type)
2781{
2782 if (type == CTRL_X_FUNCTION)
2783 return &curbuf->b_cfu_cb;
2784 if (type == CTRL_X_OMNI)
2785 return &curbuf->b_ofu_cb;
2786 // CTRL_X_THESAURUS
2787 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2788}
2789
2790/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002791 * Execute user defined complete function 'completefunc', 'omnifunc' or
2792 * 'thesaurusfunc', and get matches in "matches".
2793 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002794 */
2795 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002796expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002797{
2798 list_T *matchlist = NULL;
2799 dict_T *matchdict = NULL;
2800 typval_T args[3];
2801 char_u *funcname;
2802 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002803 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002804 typval_T rettv;
2805 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002806 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002807
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002808 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002809 if (*funcname == NUL)
2810 return;
2811
2812 // Call 'completefunc' to obtain the list of matches.
2813 args[0].v_type = VAR_NUMBER;
2814 args[0].vval.v_number = 0;
2815 args[1].v_type = VAR_STRING;
2816 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2817 args[2].v_type = VAR_UNKNOWN;
2818
2819 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002820 // Lock the text to avoid weird things from happening. Also disallow
2821 // switching to another window, it should not be needed and may end up in
2822 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002823 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002824
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002825 cb = get_insert_callback(type);
2826 retval = call_callback(cb, 0, &rettv, 2, args);
2827
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002828 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002829 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002830 {
2831 switch (rettv.v_type)
2832 {
2833 case VAR_LIST:
2834 matchlist = rettv.vval.v_list;
2835 break;
2836 case VAR_DICT:
2837 matchdict = rettv.vval.v_dict;
2838 break;
2839 case VAR_SPECIAL:
2840 if (rettv.vval.v_number == VVAL_NONE)
2841 compl_opt_suppress_empty = TRUE;
2842 // FALLTHROUGH
2843 default:
2844 // TODO: Give error message?
2845 clear_tv(&rettv);
2846 break;
2847 }
2848 }
zeertzjqcfe45652022-05-27 17:26:55 +01002849 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002850
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002851 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002852 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002853 validate_cursor();
2854 if (!EQUAL_POS(curwin->w_cursor, pos))
2855 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002856 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002857 goto theend;
2858 }
2859
2860 if (matchlist != NULL)
2861 ins_compl_add_list(matchlist);
2862 else if (matchdict != NULL)
2863 ins_compl_add_dict(matchdict);
2864
2865theend:
2866 // Restore State, it might have been changed.
2867 State = save_State;
2868
2869 if (matchdict != NULL)
2870 dict_unref(matchdict);
2871 if (matchlist != NULL)
2872 list_unref(matchlist);
2873}
2874#endif // FEAT_COMPL_FUNC
2875
2876#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02002877
2878 static inline int
2879get_user_highlight_attr(char_u *hlname)
2880{
2881 if (hlname != NULL && *hlname != NUL)
2882 return syn_name2attr(hlname);
2883 return -1;
2884}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002885/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002886 * Add a match to the list of matches from a typeval_T.
2887 * If the given string is already in the list of completions, then return
2888 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2889 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002890 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002891 */
2892 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002893ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002894{
2895 char_u *word;
2896 int dup = FALSE;
2897 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002898 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002899 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002900 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002901 int status;
glepnir0fe17f82024-10-08 22:26:44 +02002902 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02002903 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01002904 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002905
Bram Moolenaar08928322020-01-04 14:32:48 +01002906 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002907 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2908 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002909 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2910 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2911 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2912 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2913 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02002914
glepnir0fe17f82024-10-08 22:26:44 +02002915 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01002916 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02002917
2918 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01002919 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02002920
Bram Moolenaard61efa52022-07-23 09:52:04 +01002921 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2922 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2923 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002924 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002925 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2926 dup = dict_get_number(tv->vval.v_dict, "dup");
2927 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2928 empty = dict_get_number(tv->vval.v_dict, "empty");
2929 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2930 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002931 flags |= CP_EQUAL;
2932 }
2933 else
2934 {
2935 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002936 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002937 }
2938 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002939 {
2940 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002941 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002942 }
glepnir508e7852024-07-25 21:39:08 +02002943 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01002944 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002945 if (status != OK)
2946 clear_tv(&user_data);
2947 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002948}
2949
2950/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002951 * Add completions from a list.
2952 */
2953 static void
2954ins_compl_add_list(list_T *list)
2955{
2956 listitem_T *li;
2957 int dir = compl_direction;
2958
2959 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002960 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002961 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002962 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002963 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002964 // if dir was BACKWARD then honor it just once
2965 dir = FORWARD;
2966 else if (did_emsg)
2967 break;
2968 }
2969}
2970
2971/*
2972 * Add completions from a dict.
2973 */
2974 static void
2975ins_compl_add_dict(dict_T *dict)
2976{
2977 dictitem_T *di_refresh;
2978 dictitem_T *di_words;
2979
2980 // Check for optional "refresh" item.
2981 compl_opt_refresh_always = FALSE;
2982 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2983 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2984 {
2985 char_u *v = di_refresh->di_tv.vval.v_string;
2986
2987 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2988 compl_opt_refresh_always = TRUE;
2989 }
2990
2991 // Add completions from a "words" list.
2992 di_words = dict_find(dict, (char_u *)"words", 5);
2993 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2994 ins_compl_add_list(di_words->di_tv.vval.v_list);
2995}
2996
2997/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002998 * Start completion for the complete() function.
2999 * "startcol" is where the matched text starts (1 is first column).
3000 * "list" is the list of matches.
3001 */
3002 static void
3003set_completion(colnr_T startcol, list_T *list)
3004{
3005 int save_w_wrow = curwin->w_wrow;
3006 int save_w_leftcol = curwin->w_leftcol;
3007 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003008 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003009 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3010 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3011 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003012
3013 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003014 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003015 ins_compl_prep(' ');
3016 ins_compl_clear();
3017 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003018 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003019
3020 compl_direction = FORWARD;
3021 if (startcol > curwin->w_cursor.col)
3022 startcol = curwin->w_cursor.col;
3023 compl_col = startcol;
3024 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3025 // compl_pattern doesn't need to be set
John Marriott5e6ea922024-11-23 14:01:57 +01003026 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col, (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003027 if (p_ic)
3028 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003029 if (compl_orig_text.string == NULL)
3030 {
3031 compl_orig_text.length = 0;
3032 return;
3033 }
3034 compl_orig_text.length = (size_t)compl_length;
3035 if (ins_compl_add(compl_orig_text.string,
3036 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3037 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003038 return;
3039
3040 ctrl_x_mode = CTRL_X_EVAL;
3041
3042 ins_compl_add_list(list);
3043 compl_matches = ins_compl_make_cyclic();
3044 compl_started = TRUE;
3045 compl_used_match = TRUE;
3046 compl_cont_status = 0;
3047
3048 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003049 int no_select = compl_no_select || compl_longest;
3050 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003051 {
3052 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003053 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003054 // Down/Up has no real effect.
3055 ins_complete(K_UP, FALSE);
3056 }
3057 else
3058 ins_complete(Ctrl_N, FALSE);
3059 compl_enter_selects = compl_no_insert;
3060
3061 // Lazily show the popup menu, unless we got interrupted.
3062 if (!compl_interrupted)
3063 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003064 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003065 out_flush();
3066}
3067
3068/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003069 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003070 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003071 void
3072f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003073{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003074 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003075
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003076 if (in_vim9script()
3077 && (check_for_number_arg(argvars, 0) == FAIL
3078 || check_for_list_arg(argvars, 1) == FAIL))
3079 return;
3080
Bram Moolenaar24959102022-05-07 20:01:16 +01003081 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003082 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003083 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003084 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003085 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003086
3087 // Check for undo allowed here, because if something was already inserted
3088 // the line was already saved for undo and this check isn't done.
3089 if (!undo_allowed())
3090 return;
3091
Bram Moolenaard83392a2022-09-01 12:22:46 +01003092 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003093 {
3094 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3095 if (startcol > 0)
3096 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003097 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003098}
3099
3100/*
3101 * "complete_add()" function
3102 */
3103 void
3104f_complete_add(typval_T *argvars, typval_T *rettv)
3105{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003106 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003107 return;
3108
Bram Moolenaar440cf092021-04-03 20:13:30 +02003109 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003110}
3111
3112/*
3113 * "complete_check()" function
3114 */
3115 void
3116f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3117{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003118 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003119 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003120
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003121 ins_compl_check_keys(0, TRUE);
3122 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003123
3124 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003125}
3126
3127/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003128 * Return Insert completion mode name string
3129 */
3130 static char_u *
3131ins_compl_mode(void)
3132{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003133 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003134 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3135
3136 return (char_u *)"";
3137}
3138
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003139/*
3140 * Assign the sequence number to all the completion matches which don't have
3141 * one assigned yet.
3142 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003143 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003144ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003145{
3146 int number = 0;
3147 compl_T *match;
3148
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003149 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003150 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003151 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003152 // This should normally succeed already at the first loop
3153 // cycle, so it's fast!
3154 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003155 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003156 if (match->cp_number != -1)
3157 {
3158 number = match->cp_number;
3159 break;
3160 }
3161 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003162 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003163 for (match = match->cp_next;
3164 match != NULL && match->cp_number == -1;
3165 match = match->cp_next)
3166 match->cp_number = ++number;
3167 }
3168 else // BACKWARD
3169 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003170 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003171 // number. This should normally succeed already at the
3172 // first loop cycle, so it's fast!
3173 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003174 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003175 if (match->cp_number != -1)
3176 {
3177 number = match->cp_number;
3178 break;
3179 }
3180 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003181 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003182 for (match = match->cp_prev; match
3183 && match->cp_number == -1;
3184 match = match->cp_prev)
3185 match->cp_number = ++number;
3186 }
3187}
3188
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003189/*
3190 * Get complete information
3191 */
3192 static void
3193get_complete_info(list_T *what_list, dict_T *retdict)
3194{
3195 int ret = OK;
3196 listitem_T *item;
3197#define CI_WHAT_MODE 0x01
3198#define CI_WHAT_PUM_VISIBLE 0x02
3199#define CI_WHAT_ITEMS 0x04
3200#define CI_WHAT_SELECTED 0x08
3201#define CI_WHAT_INSERTED 0x10
3202#define CI_WHAT_ALL 0xff
3203 int what_flag;
3204
3205 if (what_list == NULL)
3206 what_flag = CI_WHAT_ALL;
3207 else
3208 {
3209 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003210 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003211 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003212 {
3213 char_u *what = tv_get_string(&item->li_tv);
3214
3215 if (STRCMP(what, "mode") == 0)
3216 what_flag |= CI_WHAT_MODE;
3217 else if (STRCMP(what, "pum_visible") == 0)
3218 what_flag |= CI_WHAT_PUM_VISIBLE;
3219 else if (STRCMP(what, "items") == 0)
3220 what_flag |= CI_WHAT_ITEMS;
3221 else if (STRCMP(what, "selected") == 0)
3222 what_flag |= CI_WHAT_SELECTED;
3223 else if (STRCMP(what, "inserted") == 0)
3224 what_flag |= CI_WHAT_INSERTED;
3225 }
3226 }
3227
3228 if (ret == OK && (what_flag & CI_WHAT_MODE))
3229 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3230
3231 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3232 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3233
Girish Palya8950bf72024-03-20 20:07:29 +01003234 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003235 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003236 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003237 dict_T *di;
3238 compl_T *match;
3239 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003240
Girish Palya8950bf72024-03-20 20:07:29 +01003241 if (what_flag & CI_WHAT_ITEMS)
3242 {
3243 li = list_alloc();
3244 if (li == NULL)
3245 return;
3246 ret = dict_add_list(retdict, "items", li);
3247 }
3248 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3249 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3250 ins_compl_update_sequence_numbers();
3251 if (ret == OK && compl_first_match != NULL)
3252 {
3253 int list_idx = 0;
3254 match = compl_first_match;
3255 do
3256 {
3257 if (!match_at_original_text(match))
3258 {
3259 if (what_flag & CI_WHAT_ITEMS)
3260 {
3261 di = dict_alloc();
3262 if (di == NULL)
3263 return;
3264 ret = list_append_dict(li, di);
3265 if (ret != OK)
3266 return;
John Marriott5e6ea922024-11-23 14:01:57 +01003267 dict_add_string(di, "word", match->cp_str.string);
Girish Palya8950bf72024-03-20 20:07:29 +01003268 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3269 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3270 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3271 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3272 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3273 // Add an empty string for backwards compatibility
3274 dict_add_string(di, "user_data", (char_u *)"");
3275 else
3276 dict_add_tv(di, "user_data", &match->cp_user_data);
3277 }
3278 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3279 selected_idx = list_idx;
3280 list_idx += 1;
3281 }
3282 match = match->cp_next;
3283 }
3284 while (match != NULL && !is_first_match(match));
3285 }
3286 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3287 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003288 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003289
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003290 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3291 {
3292 // TODO
3293 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003294}
3295
3296/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003297 * "complete_info()" function
3298 */
3299 void
3300f_complete_info(typval_T *argvars, typval_T *rettv)
3301{
3302 list_T *what_list = NULL;
3303
Bram Moolenaar93a10962022-06-16 11:42:09 +01003304 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003305 return;
3306
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003307 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3308 return;
3309
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003310 if (argvars[0].v_type != VAR_UNKNOWN)
3311 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003312 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003313 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003314 what_list = argvars[0].vval.v_list;
3315 }
3316 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003317}
3318#endif
3319
3320/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003321 * Returns TRUE when using a user-defined function for thesaurus completion.
3322 */
3323 static int
3324thesaurus_func_complete(int type UNUSED)
3325{
3326#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003327 return type == CTRL_X_THESAURUS
3328 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003329#else
3330 return FALSE;
3331#endif
3332}
3333
3334/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003335 * Return value of process_next_cpt_value()
3336 */
3337enum
3338{
3339 INS_COMPL_CPT_OK = 1,
3340 INS_COMPL_CPT_CONT,
3341 INS_COMPL_CPT_END
3342};
3343
3344/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003345 * state information used for getting the next set of insert completion
3346 * matches.
3347 */
3348typedef struct
3349{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003350 char_u *e_cpt_copy; // copy of 'complete'
3351 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003352 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003353 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003354 pos_T prev_match_pos; // previous match position
3355 int set_match_pos; // save first_match_pos/last_match_pos
3356 pos_T first_match_pos; // first match position
3357 pos_T last_match_pos; // last match position
3358 int found_all; // found all matches of a certain type.
3359 char_u *dict; // dictionary file to search
3360 int dict_f; // "dict" is an exact file name or not
3361} ins_compl_next_state_T;
3362
3363/*
3364 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003365 *
3366 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003367 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003368 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003369 * st->found_all - all matches of this type are found
3370 * st->ins_buf - search for completions in this buffer
3371 * st->first_match_pos - position of the first completion match
3372 * st->last_match_pos - position of the last completion match
3373 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003374 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003375 * st->dict - name of the dictionary or thesaurus file to search
3376 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003377 *
3378 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003379 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3380 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003381 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003382 */
3383 static int
3384process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003385 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003386 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003387 pos_T *start_match_pos,
3388 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003389{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003390 int compl_type = -1;
3391 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003392
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003393 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003395 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3396 st->e_cpt++;
3397
3398 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003399 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003400 st->ins_buf = curbuf;
3401 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003402 // Move the cursor back one character so that ^N can match the
3403 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003404 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003405 {
3406 // Move the cursor to after the last character in the
3407 // buffer, so that word at start of buffer is found
3408 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003409 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003410 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003411 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003412 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003413 compl_type = 0;
3414
3415 // Remember the first match so that the loop stops when we
3416 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003417 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003418 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003419 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003420 && (st->ins_buf = ins_compl_next_buf(
3421 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003422 {
3423 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003424 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003425 {
3426 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003427 st->first_match_pos.col = st->last_match_pos.col = 0;
3428 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3429 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003430 compl_type = 0;
3431 }
3432 else // unloaded buffer, scan like dictionary
3433 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003434 st->found_all = TRUE;
3435 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003436 {
3437 status = INS_COMPL_CPT_CONT;
3438 goto done;
3439 }
3440 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003441 st->dict = st->ins_buf->b_fname;
3442 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003443 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003444 if (!shortmess(SHM_COMPLETIONSCAN))
3445 {
3446 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3447 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3448 st->ins_buf->b_fname == NULL
3449 ? buf_spname(st->ins_buf)
3450 : st->ins_buf->b_sfname == NULL
3451 ? st->ins_buf->b_fname
3452 : st->ins_buf->b_sfname);
3453 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3454 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003455 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003456 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003457 status = INS_COMPL_CPT_END;
3458 else
3459 {
3460 if (ctrl_x_mode_line_or_eval())
3461 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003462 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003463 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003464 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003465 compl_type = CTRL_X_DICTIONARY;
3466 else
3467 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003468 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003469 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003470 st->dict = st->e_cpt;
3471 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003472 }
3473 }
3474#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003475 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003476 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003477 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003478 compl_type = CTRL_X_PATH_DEFINES;
3479#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003480 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003481 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003482 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003483 if (!shortmess(SHM_COMPLETIONSCAN))
3484 {
3485 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3486 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3487 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3488 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003489 }
3490 else
3491 compl_type = -1;
3492
3493 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003494 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003495
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003496 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003497 if (compl_type == -1)
3498 status = INS_COMPL_CPT_CONT;
3499 }
3500
3501done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003502 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003503 return status;
3504}
3505
3506#ifdef FEAT_FIND_ID
3507/*
3508 * Get the next set of identifiers or defines matching "compl_pattern" in
3509 * included files.
3510 */
3511 static void
3512get_next_include_file_completion(int compl_type)
3513{
John Marriott5e6ea922024-11-23 14:01:57 +01003514 find_pattern_in_path(compl_pattern.string, compl_direction,
3515 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003516 (compl_type == CTRL_X_PATH_DEFINES
3517 && !(compl_cont_status & CONT_SOL))
3518 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003519 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003520}
3521#endif
3522
3523/*
3524 * Get the next set of words matching "compl_pattern" in dictionary or
3525 * thesaurus files.
3526 */
3527 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003528get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003529{
3530#ifdef FEAT_COMPL_FUNC
3531 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003532 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003533 else
3534#endif
3535 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003536 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003537 : (compl_type == CTRL_X_THESAURUS
3538 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3539 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003540 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003541 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003542 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003543}
3544
3545/*
3546 * Get the next set of tag names matching "compl_pattern".
3547 */
3548 static void
3549get_next_tag_completion(void)
3550{
3551 int save_p_ic;
3552 char_u **matches;
3553 int num_matches;
3554
3555 // set p_ic according to p_ic, p_scs and pat for find_tags().
3556 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003557 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003558
3559 // Find up to TAG_MANY matches. Avoids that an enormous number
3560 // of matches is found when compl_pattern is empty
3561 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003562 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003563 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003564 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003565 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3566 ins_compl_add_matches(num_matches, matches, p_ic);
3567 g_tag_at_cursor = FALSE;
3568 p_ic = save_p_ic;
3569}
3570
3571/*
glepnir8159fb12024-07-17 20:32:54 +02003572 * Compare function for qsort
3573 */
3574static int compare_scores(const void *a, const void *b)
3575{
3576 int idx_a = *(const int *)a;
3577 int idx_b = *(const int *)b;
3578 int score_a = compl_fuzzy_scores[idx_a];
3579 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003580 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3581 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003582}
3583
3584/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003585 * Get the next set of filename matching "compl_pattern".
3586 */
3587 static void
3588get_next_filename_completion(void)
3589{
3590 char_u **matches;
3591 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003592 char_u *ptr;
3593 garray_T fuzzy_indices;
3594 int i;
3595 int score;
3596 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003597 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003598 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3599 char_u **sorted_matches;
3600 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003601 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003602
glepnirb9de1a02024-08-02 19:14:38 +02003603#ifdef BACKSLASH_IN_FILENAME
3604 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3605 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3606#else
3607 char pathsep = PATHSEP;
3608#endif
3609
glepnir8159fb12024-07-17 20:32:54 +02003610 if (in_fuzzy)
3611 {
glepnirb9de1a02024-08-02 19:14:38 +02003612#ifdef BACKSLASH_IN_FILENAME
3613 if (curbuf->b_p_csl[0] == 's')
3614 {
John Marriott5e6ea922024-11-23 14:01:57 +01003615 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003616 {
3617 if (leader[i] == '\\')
3618 leader[i] = '/';
3619 }
3620 }
3621 else if (curbuf->b_p_csl[0] == 'b')
3622 {
John Marriott5e6ea922024-11-23 14:01:57 +01003623 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003624 {
3625 if (leader[i] == '/')
3626 leader[i] = '\\';
3627 }
3628 }
3629#endif
3630 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003631 if (last_sep == NULL)
3632 {
3633 // No path separator or separator is the last character,
3634 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003635 VIM_CLEAR_STRING(compl_pattern);
3636 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3637 if (compl_pattern.string == NULL)
3638 return;
3639 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003640 }
3641 else if (*(last_sep + 1) == '\0')
3642 in_fuzzy = FALSE;
3643 else
3644 {
3645 // Split leader into path and file parts
3646 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003647 char_u *path_with_wildcard;
3648
3649 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003650 if (path_with_wildcard != NULL)
3651 {
John Marriott5e6ea922024-11-23 14:01:57 +01003652 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3653 VIM_CLEAR_STRING(compl_pattern);
3654 compl_pattern.string = path_with_wildcard;
3655 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003656
3657 // Move leader to the file part
3658 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003659 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003660 }
3661 }
glepnir8159fb12024-07-17 20:32:54 +02003662 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003663
John Marriott5e6ea922024-11-23 14:01:57 +01003664 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003665 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3666 return;
3667
3668 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003669 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003670#ifdef BACKSLASH_IN_FILENAME
3671 if (curbuf->b_p_csl[0] != NUL)
3672 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003673 for (i = 0; i < num_matches; ++i)
3674 {
glepnir8159fb12024-07-17 20:32:54 +02003675 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003676 while (*ptr != NUL)
3677 {
3678 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3679 *ptr = '/';
3680 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3681 *ptr = '\\';
3682 ptr += (*mb_ptr2len)(ptr);
3683 }
3684 }
3685 }
3686#endif
glepnir8159fb12024-07-17 20:32:54 +02003687
3688 if (in_fuzzy)
3689 {
3690 ga_init2(&fuzzy_indices, sizeof(int), 10);
3691 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3692
3693 for (i = 0; i < num_matches; i++)
3694 {
3695 ptr = matches[i];
3696 score = fuzzy_match_str(ptr, leader);
3697 if (score > 0)
3698 {
3699 if (ga_grow(&fuzzy_indices, 1) == OK)
3700 {
3701 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3702 compl_fuzzy_scores[i] = score;
3703 fuzzy_indices.ga_len++;
3704 }
3705 }
3706 }
3707
Christian Brabandt220474d2024-07-20 13:26:44 +02003708 // prevent qsort from deref NULL pointer
3709 if (fuzzy_indices.ga_len > 0)
3710 {
3711 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3712 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003713
Christian Brabandt220474d2024-07-20 13:26:44 +02003714 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3715 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3716 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003717
Christian Brabandt220474d2024-07-20 13:26:44 +02003718 FreeWild(num_matches, matches);
3719 matches = sorted_matches;
3720 num_matches = fuzzy_indices.ga_len;
3721 }
glepnir6b6280c2024-07-27 16:25:45 +02003722 else if (leader_len > 0)
3723 {
3724 FreeWild(num_matches, matches);
3725 num_matches = 0;
3726 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003727
glepnir8159fb12024-07-17 20:32:54 +02003728 vim_free(compl_fuzzy_scores);
3729 ga_clear(&fuzzy_indices);
3730 }
3731
glepnir6b6280c2024-07-27 16:25:45 +02003732 if (num_matches > 0)
3733 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003734}
3735
3736/*
3737 * Get the next set of command-line completions matching "compl_pattern".
3738 */
3739 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003740get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003741{
3742 char_u **matches;
3743 int num_matches;
3744
John Marriott5e6ea922024-11-23 14:01:57 +01003745 if (expand_cmdline(&compl_xp, compl_pattern.string,
3746 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003747 ins_compl_add_matches(num_matches, matches, FALSE);
3748}
3749
3750/*
3751 * Get the next set of spell suggestions matching "compl_pattern".
3752 */
3753 static void
3754get_next_spell_completion(linenr_T lnum UNUSED)
3755{
3756#ifdef FEAT_SPELL
3757 char_u **matches;
3758 int num_matches;
3759
John Marriott5e6ea922024-11-23 14:01:57 +01003760 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003761 if (num_matches > 0)
3762 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003763 else
3764 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003765#endif
3766}
3767
3768/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003769 * Return the next word or line from buffer "ins_buf" at position
3770 * "cur_match_pos" for completion. The length of the match is set in "len".
3771 */
3772 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003773ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003774 buf_T *ins_buf, // buffer being scanned
3775 pos_T *cur_match_pos, // current match position
3776 int *match_len,
3777 int *cont_s_ipos) // next ^X<> will set initial_pos
3778{
3779 char_u *ptr;
3780 int len;
3781
3782 *match_len = 0;
3783 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3784 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003785 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003786 if (ctrl_x_mode_line_or_eval())
3787 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003788 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003789 {
3790 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3791 return NULL;
3792 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003793 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003794 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003795 {
3796 char_u *tmp_ptr = ptr;
3797
3798 ptr = skipwhite(tmp_ptr);
3799 len -= (int)(ptr - tmp_ptr);
3800 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003801 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003802 }
3803 else
3804 {
3805 char_u *tmp_ptr = ptr;
3806
John Marriott5e6ea922024-11-23 14:01:57 +01003807 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003808 {
3809 tmp_ptr += compl_length;
3810 // Skip if already inside a word.
3811 if (vim_iswordp(tmp_ptr))
3812 return NULL;
3813 // Find start of next word.
3814 tmp_ptr = find_word_start(tmp_ptr);
3815 }
3816 // Find end of this word.
3817 tmp_ptr = find_word_end(tmp_ptr);
3818 len = (int)(tmp_ptr - ptr);
3819
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003820 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003821 {
3822 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3823 {
3824 // Try next line, if any. the new word will be
3825 // "join" as if the normal command "J" was used.
3826 // IOSIZE is always greater than
3827 // compl_length, so the next STRNCPY always
3828 // works -- Acevedo
3829 STRNCPY(IObuff, ptr, len);
3830 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3831 tmp_ptr = ptr = skipwhite(ptr);
3832 // Find start of next word.
3833 tmp_ptr = find_word_start(tmp_ptr);
3834 // Find end of next word.
3835 tmp_ptr = find_word_end(tmp_ptr);
3836 if (tmp_ptr > ptr)
3837 {
3838 if (*ptr != ')' && IObuff[len - 1] != TAB)
3839 {
3840 if (IObuff[len - 1] != ' ')
3841 IObuff[len++] = ' ';
3842 // IObuf =~ "\k.* ", thus len >= 2
3843 if (p_js
3844 && (IObuff[len - 2] == '.'
3845 || (vim_strchr(p_cpo, CPO_JOINSP)
3846 == NULL
3847 && (IObuff[len - 2] == '?'
3848 || IObuff[len - 2] == '!'))))
3849 IObuff[len++] = ' ';
3850 }
3851 // copy as much as possible of the new word
3852 if (tmp_ptr - ptr >= IOSIZE - len)
3853 tmp_ptr = ptr + IOSIZE - len - 1;
3854 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3855 len += (int)(tmp_ptr - ptr);
3856 *cont_s_ipos = TRUE;
3857 }
3858 IObuff[len] = NUL;
3859 ptr = IObuff;
3860 }
3861 if (len == compl_length)
3862 return NULL;
3863 }
3864 }
3865
3866 *match_len = len;
3867 return ptr;
3868}
3869
3870/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003871 * Get the next set of words matching "compl_pattern" for default completion(s)
3872 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003873 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3874 * position "st->start_pos" in the "compl_direction" direction. If
3875 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3876 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003877 * Returns OK if a new next match is found, otherwise returns FAIL.
3878 */
3879 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003880get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003881{
3882 int found_new_match = FAIL;
3883 int save_p_scs;
3884 int save_p_ws;
3885 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003886 char_u *ptr = NULL;
3887 int len = 0;
3888 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3889 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003890
3891 // If 'infercase' is set, don't use 'smartcase' here
3892 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003893 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003894 p_scs = FALSE;
3895
3896 // Buffers other than curbuf are scanned from the beginning or the
3897 // end but never from the middle, thus setting nowrapscan in this
3898 // buffer is a good idea, on the other hand, we always set
3899 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3900 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003901 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003902 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003903 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003904 p_ws = TRUE;
3905 looped_around = FALSE;
3906 for (;;)
3907 {
3908 int cont_s_ipos = FALSE;
3909
3910 ++msg_silent; // Don't want messages for wrapscan.
3911
3912 // ctrl_x_mode_line_or_eval() || word-wise search that
3913 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003914 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003915 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01003916 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02003917 else if (in_fuzzy)
3918 found_new_match = search_for_fuzzy_match(st->ins_buf,
3919 st->cur_match_pos, leader, compl_direction,
3920 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003921 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003922 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01003923 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02003924 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003925 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003926 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003927 {
3928 // set "compl_started" even on fail
3929 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003930 st->first_match_pos = *st->cur_match_pos;
3931 st->last_match_pos = *st->cur_match_pos;
3932 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003933 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003934 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3935 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003936 {
3937 found_new_match = FAIL;
3938 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003939 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003940 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3941 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3942 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003943 {
3944 if (looped_around)
3945 found_new_match = FAIL;
3946 else
3947 looped_around = TRUE;
3948 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003949 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003950 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3951 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3952 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003953 {
3954 if (looped_around)
3955 found_new_match = FAIL;
3956 else
3957 looped_around = TRUE;
3958 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003959 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003960 if (found_new_match == FAIL)
3961 break;
3962
3963 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003964 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003965 && start_pos->lnum == st->cur_match_pos->lnum
3966 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003967 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003968
glepnir8159fb12024-07-17 20:32:54 +02003969 if (!in_fuzzy)
3970 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3971 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003972 if (ptr == NULL)
3973 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003974
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003975 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003976 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003977 0, cont_s_ipos) != NOTDONE)
3978 {
3979 found_new_match = OK;
3980 break;
3981 }
3982 }
3983 p_scs = save_p_scs;
3984 p_ws = save_p_ws;
3985
3986 return found_new_match;
3987}
3988
3989/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003990 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003991 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003992 */
3993 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003994get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003995{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003996 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003997
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003998 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003999 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004000 case -1:
4001 break;
4002#ifdef FEAT_FIND_ID
4003 case CTRL_X_PATH_PATTERNS:
4004 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004005 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004006 break;
4007#endif
4008
4009 case CTRL_X_DICTIONARY:
4010 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004011 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4012 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004013 break;
4014
4015 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004016 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004017 break;
4018
4019 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004020 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004021 break;
4022
4023 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004024 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004025 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004026 break;
4027
4028#ifdef FEAT_COMPL_FUNC
4029 case CTRL_X_FUNCTION:
4030 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004031 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004032 break;
4033#endif
4034
4035 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004036 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004037 break;
4038
4039 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004040 found_new_match = get_next_default_completion(st, ini);
4041 if (found_new_match == FAIL && st->ins_buf == curbuf)
4042 st->found_all = TRUE;
4043 }
4044
4045 // check if compl_curr_match has changed, (e.g. other type of
4046 // expansion added something)
4047 if (type != 0 && compl_curr_match != compl_old_match)
4048 found_new_match = OK;
4049
4050 return found_new_match;
4051}
4052
4053/*
4054 * Get the next expansion(s), using "compl_pattern".
4055 * The search starts at position "ini" in curbuf and in the direction
4056 * compl_direction.
4057 * When "compl_started" is FALSE start at that position, otherwise continue
4058 * where we stopped searching before.
4059 * This may return before finding all the matches.
4060 * Return the total number of matches or -1 if still unknown -- Acevedo
4061 */
4062 static int
4063ins_compl_get_exp(pos_T *ini)
4064{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004065 static ins_compl_next_state_T st;
4066 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004067 int i;
4068 int found_new_match;
4069 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004070 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071
4072 if (!compl_started)
4073 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004074 buf_T *buf;
4075
4076 FOR_ALL_BUFFERS(buf)
4077 buf->b_scanned = 0;
4078 if (!st_cleared)
4079 {
4080 CLEAR_FIELD(st);
4081 st_cleared = TRUE;
4082 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004083 st.found_all = FALSE;
4084 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004085 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004086 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004087 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4088 ? (char_u *)"." : curbuf->b_p_cpt);
4089 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004090 st.last_match_pos = st.first_match_pos = *ini;
4091 }
4092 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4093 st.ins_buf = curbuf; // In case the buffer was wiped out.
4094
4095 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004096 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004097 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004098
4099 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4100 for (;;)
4101 {
4102 found_new_match = FAIL;
4103 st.set_match_pos = FALSE;
4104
4105 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4106 // or if found_all says this entry is done. For ^X^L only use the
4107 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004108 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004109 && (!compl_started || st.found_all))
4110 {
glepnir8159fb12024-07-17 20:32:54 +02004111 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004112
4113 if (status == INS_COMPL_CPT_END)
4114 break;
4115 if (status == INS_COMPL_CPT_CONT)
4116 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004117 }
4118
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004119 // If complete() was called then compl_pattern has been reset. The
4120 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004121 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004122 break;
4123
4124 // get the next set of completion matches
4125 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004126
4127 // break the loop for specialized modes (use 'complete' just for the
4128 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4129 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004130 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4131 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004132 {
4133 if (got_int)
4134 break;
4135 // Fill the popup menu as soon as possible.
4136 if (type != -1)
4137 ins_compl_check_keys(0, FALSE);
4138
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004139 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004140 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4141 break;
4142 compl_started = TRUE;
4143 }
4144 else
4145 {
4146 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004147 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004148 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004149
4150 compl_started = FALSE;
4151 }
4152 }
4153 compl_started = TRUE;
4154
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004155 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004156 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004157 found_new_match = FAIL;
4158
4159 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004160 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004161 && !ctrl_x_mode_line_or_eval()))
4162 i = ins_compl_make_cyclic();
4163
4164 if (compl_old_match != NULL)
4165 {
4166 // If several matches were added (FORWARD) or the search failed and has
4167 // just been made cyclic then we have to move compl_curr_match to the
4168 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004169 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004170 : compl_old_match->cp_prev;
4171 if (compl_curr_match == NULL)
4172 compl_curr_match = compl_old_match;
4173 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004174 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004175
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004176 return i;
4177}
4178
4179/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004180 * Update "compl_shown_match" to the actually shown match, it may differ when
4181 * "compl_leader" is used to omit some of the matches.
4182 */
4183 static void
4184ins_compl_update_shown_match(void)
4185{
4186 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004187 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004188 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004189 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004190 compl_shown_match = compl_shown_match->cp_next;
4191
4192 // If we didn't find it searching forward, and compl_shows_dir is
4193 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004194 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004195 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004196 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004197 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004198 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004199 {
4200 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004201 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004202 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004203 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004204 compl_shown_match = compl_shown_match->cp_prev;
4205 }
4206}
4207
4208/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004209 * Delete the old text being completed.
4210 */
4211 void
4212ins_compl_delete(void)
4213{
4214 int col;
4215
4216 // In insert mode: Delete the typed part.
4217 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004218 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004219 if ((int)curwin->w_cursor.col > col)
4220 {
4221 if (stop_arrow() == FAIL)
4222 return;
4223 backspace_until_column(col);
4224 }
4225
4226 // TODO: is this sufficient for redrawing? Redrawing everything causes
4227 // flicker, thus we can't do that.
4228 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004229#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004230 // clear v:completed_item
4231 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004232#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004233}
4234
4235/*
4236 * Insert the new text being completed.
4237 * "in_compl_func" is TRUE when called from complete_check().
4238 */
4239 void
4240ins_compl_insert(int in_compl_func)
4241{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004242 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004243
4244 // Make sure we don't go over the end of the string, this can happen with
4245 // illegal bytes.
John Marriott5e6ea922024-11-23 14:01:57 +01004246 if (compl_len < (int)compl_shown_match->cp_str.length)
4247 ins_bytes(compl_shown_match->cp_str.string + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004248 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004249 compl_used_match = FALSE;
4250 else
4251 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004252#ifdef FEAT_EVAL
4253 {
4254 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4255
4256 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4257 }
4258#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004259 if (!in_compl_func)
4260 compl_curr_match = compl_shown_match;
4261}
4262
4263/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004264 * show the file name for the completion match (if any). Truncate the file
4265 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004266 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004267 static void
4268ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004269{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004270 char *lead = _("match in file");
4271 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4272 char_u *s;
4273 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004274
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004275 if (space <= 0)
4276 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004277
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004278 // We need the tail that fits. With double-byte encoding going
4279 // back from the end is very slow, thus go from the start and keep
4280 // the text that fits in "space" between "s" and "e".
4281 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004282 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004283 space -= ptr2cells(e);
4284 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004285 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004286 space += ptr2cells(s);
4287 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004288 }
4289 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004290 msg_hist_off = TRUE;
4291 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4292 s > compl_shown_match->cp_fname ? "<" : "", s);
4293 msg((char *)IObuff);
4294 msg_hist_off = FALSE;
4295 redraw_cmdline = FALSE; // don't overwrite!
4296}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004297
glepnirdca57fb2024-06-04 22:01:21 +02004298/*
zeertzjq551d8c32024-06-05 19:53:32 +02004299 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004300 */
glepnira218cc62024-06-03 19:32:39 +02004301 static compl_T *
4302find_comp_when_fuzzy(void)
4303{
4304 int score;
4305 char_u* str;
4306 int target_idx = -1;
4307 int is_forward = compl_shows_dir_forward();
4308 int is_backward = compl_shows_dir_backward();
4309 compl_T *comp = NULL;
4310
glepnir43eef882024-06-19 20:20:48 +02004311 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004312 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004313 return compl_first_match != compl_shown_match ? compl_first_match :
4314 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004315
4316 if (is_forward)
4317 target_idx = compl_selected_item + 1;
4318 else if (is_backward)
4319 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004320 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004321
4322 score = compl_match_array[target_idx].pum_score;
4323 str = compl_match_array[target_idx].pum_text;
4324
4325 comp = compl_first_match;
4326 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004327 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004328 return comp;
4329 comp = comp->cp_next;
4330 } while (comp != NULL && !is_first_match(comp));
4331
4332 return NULL;
4333}
4334
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004335/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004336 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004337 * times. The number of matches found is returned in 'num_matches'.
4338 *
4339 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4340 * get more completions. If it is FALSE, then do nothing when there are no more
4341 * completions in the given direction.
4342 *
4343 * If "advance" is TRUE, then completion will move to the first match.
4344 * Otherwise, the original text will be shown.
4345 *
4346 * Returns OK on success and -1 if the number of matches are unknown.
4347 */
4348 static int
4349find_next_completion_match(
4350 int allow_get_expansion,
4351 int todo, // repeat completion this many times
4352 int advance,
4353 int *num_matches)
4354{
4355 int found_end = FALSE;
4356 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004357 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004358 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4359 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004360
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004361 while (--todo >= 0)
4362 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004363 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004364 {
glepniraced8c22024-06-15 15:13:05 +02004365 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4366 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004367 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004368 && (is_first_match(compl_shown_match->cp_next)
4369 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004370 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004371 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004372 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004373 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004374 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004375 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4376 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004377 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004378 }
4379 else
4380 {
4381 if (!allow_get_expansion)
4382 {
4383 if (advance)
4384 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004385 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004386 compl_pending -= todo + 1;
4387 else
4388 compl_pending += todo + 1;
4389 }
4390 return -1;
4391 }
4392
4393 if (!compl_no_select && advance)
4394 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004395 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004396 --compl_pending;
4397 else
4398 ++compl_pending;
4399 }
4400
4401 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004402 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004403
4404 // handle any pending completions
4405 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004406 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004407 {
4408 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4409 {
4410 compl_shown_match = compl_shown_match->cp_next;
4411 --compl_pending;
4412 }
4413 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4414 {
4415 compl_shown_match = compl_shown_match->cp_prev;
4416 ++compl_pending;
4417 }
4418 else
4419 break;
4420 }
4421 found_end = FALSE;
4422 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004423 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004424 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004425 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004426 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004427 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004428 ++todo;
4429 else
4430 // Remember a matching item.
4431 found_compl = compl_shown_match;
4432
4433 // Stop at the end of the list when we found a usable match.
4434 if (found_end)
4435 {
4436 if (found_compl != NULL)
4437 {
4438 compl_shown_match = found_compl;
4439 break;
4440 }
4441 todo = 1; // use first usable match after wrapping around
4442 }
4443 }
4444
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004445 return OK;
4446}
4447
4448/*
4449 * Fill in the next completion in the current direction.
4450 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4451 * get more completions. If it is FALSE, then we just do nothing when there
4452 * are no more completions in a given direction. The latter case is used when
4453 * we are still in the middle of finding completions, to allow browsing
4454 * through the ones found so far.
4455 * Return the total number of matches, or -1 if still unknown -- webb.
4456 *
4457 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4458 * compl_shown_match here.
4459 *
4460 * Note that this function may be called recursively once only. First with
4461 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4462 * calls this function with "allow_get_expansion" FALSE.
4463 */
4464 static int
4465ins_compl_next(
4466 int allow_get_expansion,
4467 int count, // repeat completion this many times; should
4468 // be at least 1
4469 int insert_match, // Insert the newly selected match
4470 int in_compl_func) // called from complete_check()
4471{
4472 int num_matches = -1;
4473 int todo = count;
4474 int advance;
4475 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004476 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004477 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004478 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4479 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004480
4481 // When user complete function return -1 for findstart which is next
4482 // time of 'always', compl_shown_match become NULL.
4483 if (compl_shown_match == NULL)
4484 return -1;
4485
John Marriott5e6ea922024-11-23 14:01:57 +01004486 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004487 && !match_at_original_text(compl_shown_match)
4488 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004489 // Update "compl_shown_match" to the actually shown match
4490 ins_compl_update_shown_match();
4491
4492 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004493 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004494 // Delete old text to be replaced
4495 ins_compl_delete();
4496
4497 // When finding the longest common text we stick at the original text,
4498 // don't let CTRL-N or CTRL-P move to the first match.
4499 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4500
4501 // When restarting the search don't insert the first match either.
4502 if (compl_restarting)
4503 {
4504 advance = FALSE;
4505 compl_restarting = FALSE;
4506 }
4507
4508 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4509 // around.
4510 if (find_next_completion_match(allow_get_expansion, todo, advance,
4511 &num_matches) == -1)
4512 return -1;
4513
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004514 if (curbuf != orig_curbuf)
4515 {
4516 // In case some completion function switched buffer, don't want to
4517 // insert the completion elsewhere.
4518 return -1;
4519 }
4520
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004521 // Insert the text of the new completion, or the compl_leader.
4522 if (compl_no_insert && !started)
4523 {
John Marriott5e6ea922024-11-23 14:01:57 +01004524 ins_bytes(compl_orig_text.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004525 compl_used_match = FALSE;
4526 }
4527 else if (insert_match)
4528 {
4529 if (!compl_get_longest || compl_used_match)
4530 ins_compl_insert(in_compl_func);
4531 else
John Marriott5e6ea922024-11-23 14:01:57 +01004532 ins_bytes(compl_leader.string + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004533 }
4534 else
4535 compl_used_match = FALSE;
4536
4537 if (!allow_get_expansion)
4538 {
4539 // may undisplay the popup menu first
4540 ins_compl_upd_pum();
4541
4542 if (pum_enough_matches())
4543 // Will display the popup menu, don't redraw yet to avoid flicker.
4544 pum_call_update_screen();
4545 else
4546 // Not showing the popup menu yet, redraw to show the user what was
4547 // inserted.
4548 update_screen(0);
4549
4550 // display the updated popup menu
4551 ins_compl_show_pum();
4552#ifdef FEAT_GUI
4553 if (gui.in_use)
4554 {
4555 // Show the cursor after the match, not after the redrawn text.
4556 setcursor();
4557 out_flush_cursor(FALSE, FALSE);
4558 }
4559#endif
4560
4561 // Delete old text to be replaced, since we're still searching and
4562 // don't want to match ourselves!
4563 ins_compl_delete();
4564 }
4565
4566 // Enter will select a match when the match wasn't inserted and the popup
4567 // menu is visible.
4568 if (compl_no_insert && !started)
4569 compl_enter_selects = TRUE;
4570 else
4571 compl_enter_selects = !insert_match && compl_match_array != NULL;
4572
4573 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004574 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004575 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004576
4577 return num_matches;
4578}
4579
4580/*
4581 * Call this while finding completions, to check whether the user has hit a key
4582 * that should change the currently displayed completion, or exit completion
4583 * mode. Also, when compl_pending is not zero, show a completion as soon as
4584 * possible. -- webb
4585 * "frequency" specifies out of how many calls we actually check.
4586 * "in_compl_func" is TRUE when called from complete_check(), don't set
4587 * compl_curr_match.
4588 */
4589 void
4590ins_compl_check_keys(int frequency, int in_compl_func)
4591{
4592 static int count = 0;
4593 int c;
4594
4595 // Don't check when reading keys from a script, :normal or feedkeys().
4596 // That would break the test scripts. But do check for keys when called
4597 // from complete_check().
4598 if (!in_compl_func && (using_script() || ex_normal_busy))
4599 return;
4600
4601 // Only do this at regular intervals
4602 if (++count < frequency)
4603 return;
4604 count = 0;
4605
4606 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4607 // can't do its work correctly.
4608 c = vpeekc_any();
4609 if (c != NUL)
4610 {
4611 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4612 {
4613 c = safe_vgetc(); // Eat the character
4614 compl_shows_dir = ins_compl_key2dir(c);
4615 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4616 c != K_UP && c != K_DOWN, in_compl_func);
4617 }
4618 else
4619 {
4620 // Need to get the character to have KeyTyped set. We'll put it
4621 // back with vungetc() below. But skip K_IGNORE.
4622 c = safe_vgetc();
4623 if (c != K_IGNORE)
4624 {
4625 // Don't interrupt completion when the character wasn't typed,
4626 // e.g., when doing @q to replay keys.
4627 if (c != Ctrl_R && KeyTyped)
4628 compl_interrupted = TRUE;
4629
4630 vungetc(c);
4631 }
4632 }
4633 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004634 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004635 {
4636 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4637
4638 compl_pending = 0;
4639 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4640 }
4641}
4642
4643/*
4644 * Decide the direction of Insert mode complete from the key typed.
4645 * Returns BACKWARD or FORWARD.
4646 */
4647 static int
4648ins_compl_key2dir(int c)
4649{
4650 if (c == Ctrl_P || c == Ctrl_L
4651 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4652 return BACKWARD;
4653 return FORWARD;
4654}
4655
4656/*
4657 * Return TRUE for keys that are used for completion only when the popup menu
4658 * is visible.
4659 */
4660 static int
4661ins_compl_pum_key(int c)
4662{
4663 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4664 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4665 || c == K_UP || c == K_DOWN);
4666}
4667
4668/*
4669 * Decide the number of completions to move forward.
4670 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4671 */
4672 static int
4673ins_compl_key2count(int c)
4674{
4675 int h;
4676
4677 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4678 {
4679 h = pum_get_height();
4680 if (h > 3)
4681 h -= 2; // keep some context
4682 return h;
4683 }
4684 return 1;
4685}
4686
4687/*
4688 * Return TRUE if completion with "c" should insert the match, FALSE if only
4689 * to change the currently selected completion.
4690 */
4691 static int
4692ins_compl_use_match(int c)
4693{
4694 switch (c)
4695 {
4696 case K_UP:
4697 case K_DOWN:
4698 case K_PAGEDOWN:
4699 case K_KPAGEDOWN:
4700 case K_S_DOWN:
4701 case K_PAGEUP:
4702 case K_KPAGEUP:
4703 case K_S_UP:
4704 return FALSE;
4705 }
4706 return TRUE;
4707}
4708
4709/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004710 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4711 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004712 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004713 * Uses the global variables: compl_cont_status and ctrl_x_mode
4714 */
4715 static int
4716get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4717{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004718 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004719 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004720 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004721 {
4722 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4723 ;
4724 compl_col += ++startcol;
4725 compl_length = curs_col - startcol;
4726 }
4727 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004728 {
John Marriott5e6ea922024-11-23 14:01:57 +01004729 compl_pattern.string = str_foldcase(line + compl_col,
4730 compl_length, NULL, 0);
4731 if (compl_pattern.string == NULL)
4732 {
4733 compl_pattern.length = 0;
4734 return FAIL;
4735 }
4736 compl_pattern.length = STRLEN(compl_pattern.string);
4737 }
4738 else
4739 {
4740 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4741 if (compl_pattern.string == NULL)
4742 {
4743 compl_pattern.length = 0;
4744 return FAIL;
4745 }
4746 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02004747 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004748 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004749 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004750 {
4751 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004752 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01004753 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004754
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004755 if (!vim_iswordp(line + compl_col)
4756 || (compl_col > 0
4757 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004758 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004759 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004760 prefixlen = 0;
4761 }
John Marriott5e6ea922024-11-23 14:01:57 +01004762
4763 // we need up to 2 extra chars for the prefix
4764 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
4765 compl_pattern.string = alloc(n);
4766 if (compl_pattern.string == NULL)
4767 {
4768 compl_pattern.length = 0;
4769 return FAIL;
4770 }
4771 STRCPY((char *)compl_pattern.string, prefix);
4772 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004773 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004774 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004775 }
4776 else if (--startcol < 0
4777 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4778 {
John Marriott5e6ea922024-11-23 14:01:57 +01004779 size_t len = STRLEN_LITERAL("\\<\\k\\k");
4780
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004781 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01004782 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
4783 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004784 {
John Marriott5e6ea922024-11-23 14:01:57 +01004785 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004786 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004787 }
John Marriott5e6ea922024-11-23 14:01:57 +01004788 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004789 compl_col += curs_col;
4790 compl_length = 0;
4791 }
4792 else
4793 {
4794 // Search the point of change class of multibyte character
4795 // or not a word single byte character backward.
4796 if (has_mbyte)
4797 {
4798 int base_class;
4799 int head_off;
4800
4801 startcol -= (*mb_head_off)(line, line + startcol);
4802 base_class = mb_get_class(line + startcol);
4803 while (--startcol >= 0)
4804 {
4805 head_off = (*mb_head_off)(line, line + startcol);
4806 if (base_class != mb_get_class(line + startcol
4807 - head_off))
4808 break;
4809 startcol -= head_off;
4810 }
4811 }
4812 else
4813 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4814 ;
4815 compl_col += ++startcol;
4816 compl_length = (int)curs_col - startcol;
4817 if (compl_length == 1)
4818 {
4819 // Only match word with at least two chars -- webb
4820 // there's no need to call quote_meta,
4821 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01004822 compl_pattern.string = alloc(7);
4823 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004824 {
John Marriott5e6ea922024-11-23 14:01:57 +01004825 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004826 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004827 }
John Marriott5e6ea922024-11-23 14:01:57 +01004828 STRCPY((char *)compl_pattern.string, "\\<");
4829 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
4830 STRCAT((char *)compl_pattern.string, "\\k");
4831 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004832 }
4833 else
4834 {
John Marriott5e6ea922024-11-23 14:01:57 +01004835 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
4836
4837 compl_pattern.string = alloc(n);
4838 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004839 {
John Marriott5e6ea922024-11-23 14:01:57 +01004840 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004841 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004842 }
John Marriott5e6ea922024-11-23 14:01:57 +01004843 STRCPY((char *)compl_pattern.string, "\\<");
4844 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004845 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01004846 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004847 }
4848 }
4849
4850 return OK;
4851}
4852
4853/*
4854 * Get the pattern, column and length for whole line completion or for the
4855 * complete() function.
4856 * Sets the global variables: compl_col, compl_length and compl_pattern.
4857 */
4858 static int
4859get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4860{
4861 compl_col = (colnr_T)getwhitecols(line);
4862 compl_length = (int)curs_col - (int)compl_col;
4863 if (compl_length < 0) // cursor in indent: empty pattern
4864 compl_length = 0;
4865 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02004866 {
John Marriott5e6ea922024-11-23 14:01:57 +01004867 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
4868 NULL, 0);
4869 if (compl_pattern.string == NULL)
4870 {
4871 compl_pattern.length = 0;
4872 return FAIL;
4873 }
4874 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02004875 }
John Marriott5e6ea922024-11-23 14:01:57 +01004876 else
4877 {
4878 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
4879 if (compl_pattern.string == NULL)
4880 {
4881 compl_pattern.length = 0;
4882 return FAIL;
4883 }
4884 compl_pattern.length = (size_t)compl_length;
4885 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004886
4887 return OK;
4888}
4889
4890/*
4891 * Get the pattern, column and length for filename completion.
4892 * Sets the global variables: compl_col, compl_length and compl_pattern.
4893 */
4894 static int
4895get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4896{
4897 // Go back to just before the first filename character.
4898 if (startcol > 0)
4899 {
4900 char_u *p = line + startcol;
4901
4902 MB_PTR_BACK(line, p);
4903 while (p > line && vim_isfilec(PTR2CHAR(p)))
4904 MB_PTR_BACK(line, p);
4905 if (p == line && vim_isfilec(PTR2CHAR(p)))
4906 startcol = 0;
4907 else
4908 startcol = (int)(p - line) + 1;
4909 }
4910
4911 compl_col += startcol;
4912 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01004913 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
4914 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004915 {
John Marriott5e6ea922024-11-23 14:01:57 +01004916 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004917 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004918 }
4919
John Marriott5e6ea922024-11-23 14:01:57 +01004920 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004921
4922 return OK;
4923}
4924
4925/*
4926 * Get the pattern, column and length for command-line completion.
4927 * Sets the global variables: compl_col, compl_length and compl_pattern.
4928 */
4929 static int
4930get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4931{
John Marriott5e6ea922024-11-23 14:01:57 +01004932 compl_pattern.string = vim_strnsave(line, curs_col);
4933 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004934 {
John Marriott5e6ea922024-11-23 14:01:57 +01004935 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004936 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004937 }
John Marriott5e6ea922024-11-23 14:01:57 +01004938 compl_pattern.length = curs_col;
4939 set_cmd_context(&compl_xp, compl_pattern.string,
4940 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004941 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4942 || compl_xp.xp_context == EXPAND_NOTHING)
4943 // No completion possible, use an empty pattern to get a
4944 // "pattern not found" message.
4945 compl_col = curs_col;
4946 else
John Marriott5e6ea922024-11-23 14:01:57 +01004947 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004948 compl_length = curs_col - compl_col;
4949
4950 return OK;
4951}
4952
4953/*
4954 * Get the pattern, column and length for user defined completion ('omnifunc',
4955 * 'completefunc' and 'thesaurusfunc')
4956 * Sets the global variables: compl_col, compl_length and compl_pattern.
4957 * Uses the global variable: spell_bad_len
4958 */
4959 static int
4960get_userdefined_compl_info(colnr_T curs_col UNUSED)
4961{
4962 int ret = FAIL;
4963
4964#ifdef FEAT_COMPL_FUNC
4965 // Call user defined function 'completefunc' with "a:findstart"
4966 // set to 1 to obtain the length of text to use for completion.
4967 char_u *line;
4968 typval_T args[3];
4969 int col;
4970 char_u *funcname;
4971 pos_T pos;
4972 int save_State = State;
4973 callback_T *cb;
4974
4975 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4976 // length as a string
4977 funcname = get_complete_funcname(ctrl_x_mode);
4978 if (*funcname == NUL)
4979 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004980 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004981 ? "completefunc" : "omnifunc");
4982 return FAIL;
4983 }
4984
4985 args[0].v_type = VAR_NUMBER;
4986 args[0].vval.v_number = 1;
4987 args[1].v_type = VAR_STRING;
4988 args[1].vval.v_string = (char_u *)"";
4989 args[2].v_type = VAR_UNKNOWN;
4990 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004991 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004992 cb = get_insert_callback(ctrl_x_mode);
4993 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004994 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004995
4996 State = save_State;
4997 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004998 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004999 validate_cursor();
5000 if (!EQUAL_POS(curwin->w_cursor, pos))
5001 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005002 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005003 return FAIL;
5004 }
5005
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005006 // Return value -2 means the user complete function wants to cancel the
5007 // complete without an error, do the same if the function did not execute
5008 // successfully.
5009 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005010 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005011 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005012 if (col == -3)
5013 {
5014 ctrl_x_mode = CTRL_X_NORMAL;
5015 edit_submode = NULL;
5016 if (!shortmess(SHM_COMPLETIONMENU))
5017 msg_clr_cmdline();
5018 return FAIL;
5019 }
5020
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005021 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005022 // completion.
5023 compl_opt_refresh_always = FALSE;
5024 compl_opt_suppress_empty = FALSE;
5025
5026 if (col < 0)
5027 col = curs_col;
5028 compl_col = col;
5029 if (compl_col > curs_col)
5030 compl_col = curs_col;
5031
5032 // Setup variables for completion. Need to obtain "line" again,
5033 // it may have become invalid.
5034 line = ml_get(curwin->w_cursor.lnum);
5035 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005036 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5037 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005038 {
John Marriott5e6ea922024-11-23 14:01:57 +01005039 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005040 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005041 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005042
John Marriott5e6ea922024-11-23 14:01:57 +01005043 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005044 ret = OK;
5045#endif
5046
5047 return ret;
5048}
5049
5050/*
5051 * Get the pattern, column and length for spell completion.
5052 * Sets the global variables: compl_col, compl_length and compl_pattern.
5053 * Uses the global variable: spell_bad_len
5054 */
5055 static int
5056get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5057{
5058 int ret = FAIL;
5059#ifdef FEAT_SPELL
5060 char_u *line;
5061
5062 if (spell_bad_len > 0)
5063 compl_col = curs_col - spell_bad_len;
5064 else
5065 compl_col = spell_word_start(startcol);
5066 if (compl_col >= (colnr_T)startcol)
5067 {
5068 compl_length = 0;
5069 compl_col = curs_col;
5070 }
5071 else
5072 {
5073 spell_expand_check_cap(compl_col);
5074 compl_length = (int)curs_col - compl_col;
5075 }
5076 // Need to obtain "line" again, it may have become invalid.
5077 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005078 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5079 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005080 {
John Marriott5e6ea922024-11-23 14:01:57 +01005081 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005082 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005083 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005084
John Marriott5e6ea922024-11-23 14:01:57 +01005085 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005086 ret = OK;
5087#endif
5088
5089 return ret;
5090}
5091
5092/*
5093 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005094 * "startcol" - start column number of the completion pattern/text
5095 * "cur_col" - current cursor column
5096 * On return, "line_invalid" is set to TRUE, if the current line may have
5097 * become invalid and needs to be fetched again.
5098 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005099 */
5100 static int
5101compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5102{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005103 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005104 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5105 && !thesaurus_func_complete(ctrl_x_mode)))
5106 {
5107 return get_normal_compl_info(line, startcol, curs_col);
5108 }
5109 else if (ctrl_x_mode_line_or_eval())
5110 {
5111 return get_wholeline_compl_info(line, curs_col);
5112 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005113 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005114 {
5115 return get_filename_compl_info(line, startcol, curs_col);
5116 }
5117 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5118 {
5119 return get_cmdline_compl_info(line, curs_col);
5120 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005121 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005122 || thesaurus_func_complete(ctrl_x_mode))
5123 {
5124 if (get_userdefined_compl_info(curs_col) == FAIL)
5125 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005126 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005127 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005128 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005129 {
5130 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5131 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005132 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005133 }
5134 else
5135 {
5136 internal_error("ins_complete()");
5137 return FAIL;
5138 }
5139
5140 return OK;
5141}
5142
5143/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005144 * Continue an interrupted completion mode search in "line".
5145 *
5146 * If this same ctrl_x_mode has been interrupted use the text from
5147 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5148 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5149 * the same line as the cursor then fix it (the line has been split because it
5150 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5151 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005152 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005153 static void
5154ins_compl_continue_search(char_u *line)
5155{
5156 // it is a continued search
5157 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005158 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5159 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005160 {
5161 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5162 {
5163 // line (probably) wrapped, set compl_startpos to the
5164 // first non_blank in the line, if it is not a wordchar
5165 // include it to get a better pattern, but then we don't
5166 // want the "\\<" prefix, check it below
5167 compl_col = (colnr_T)getwhitecols(line);
5168 compl_startpos.col = compl_col;
5169 compl_startpos.lnum = curwin->w_cursor.lnum;
5170 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5171 }
5172 else
5173 {
5174 // S_IPOS was set when we inserted a word that was at the
5175 // beginning of the line, which means that we'll go to SOL
5176 // mode but first we need to redefine compl_startpos
5177 if (compl_cont_status & CONT_S_IPOS)
5178 {
5179 compl_cont_status |= CONT_SOL;
5180 compl_startpos.col = (colnr_T)(skipwhite(
5181 line + compl_length
5182 + compl_startpos.col) - line);
5183 }
5184 compl_col = compl_startpos.col;
5185 }
5186 compl_length = curwin->w_cursor.col - (int)compl_col;
5187 // IObuff is used to add a "word from the next line" would we
5188 // have enough space? just being paranoid
5189#define MIN_SPACE 75
5190 if (compl_length > (IOSIZE - MIN_SPACE))
5191 {
5192 compl_cont_status &= ~CONT_SOL;
5193 compl_length = (IOSIZE - MIN_SPACE);
5194 compl_col = curwin->w_cursor.col - compl_length;
5195 }
5196 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5197 if (compl_length < 1)
5198 compl_cont_status &= CONT_LOCAL;
5199 }
5200 else if (ctrl_x_mode_line_or_eval())
5201 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5202 else
5203 compl_cont_status = 0;
5204}
5205
5206/*
5207 * start insert mode completion
5208 */
5209 static int
5210ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005211{
5212 char_u *line;
5213 int startcol = 0; // column where searched text starts
5214 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005215 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005216 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005217 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005218
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005219 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005220
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005221 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005222 did_si = FALSE;
5223 can_si = FALSE;
5224 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005225 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005226 return FAIL;
5227
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005228 line = ml_get(curwin->w_cursor.lnum);
5229 curs_col = curwin->w_cursor.col;
5230 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005231
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005232 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5233 && compl_cont_mode == ctrl_x_mode)
5234 // this same ctrl-x_mode was interrupted previously. Continue the
5235 // completion.
5236 ins_compl_continue_search(line);
5237 else
5238 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005239
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005240 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005241 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005242 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005243 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005244 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5245 compl_cont_status = 0;
5246 compl_cont_status |= CONT_N_ADDS;
5247 compl_startpos = curwin->w_cursor;
5248 startcol = (int)curs_col;
5249 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005250 }
5251
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005252 // Work out completion pattern and original text -- webb
5253 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5254 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005255 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5256 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005257 // restore did_ai, so that adding comment leader works
5258 did_ai = save_did_ai;
5259 return FAIL;
5260 }
5261 // If "line" was changed while getting completion info get it again.
5262 if (line_invalid)
5263 line = ml_get(curwin->w_cursor.lnum);
5264
glepnir7cfe6932024-09-15 20:06:28 +02005265 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005266 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005267 {
5268 edit_submode_pre = (char_u *)_(" Adding");
5269 if (ctrl_x_mode_line_or_eval())
5270 {
5271 // Insert a new line, keep indentation but ignore 'comments'.
5272 char_u *old = curbuf->b_p_com;
5273
5274 curbuf->b_p_com = (char_u *)"";
5275 compl_startpos.lnum = curwin->w_cursor.lnum;
5276 compl_startpos.col = compl_col;
5277 ins_eol('\r');
5278 curbuf->b_p_com = old;
5279 compl_length = 0;
5280 compl_col = curwin->w_cursor.col;
5281 }
glepnir7cfe6932024-09-15 20:06:28 +02005282 else if (ctrl_x_mode_normal() && in_fuzzy)
5283 {
5284 compl_startpos = curwin->w_cursor;
5285 compl_cont_status &= CONT_S_IPOS;
5286 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005287 }
5288 else
5289 {
5290 edit_submode_pre = NULL;
5291 compl_startpos.col = compl_col;
5292 }
5293
5294 if (compl_cont_status & CONT_LOCAL)
5295 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5296 else
5297 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5298
5299 // If any of the original typed text has been changed we need to fix
5300 // the redo buffer.
5301 ins_compl_fixRedoBufForLeader(NULL);
5302
5303 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005304 VIM_CLEAR_STRING(compl_orig_text);
5305 compl_orig_text.length = (size_t)compl_length;
5306 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005307 if (p_ic)
5308 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005309 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5310 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005311 {
John Marriott5e6ea922024-11-23 14:01:57 +01005312 VIM_CLEAR_STRING(compl_pattern);
5313 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005314 return FAIL;
5315 }
5316
5317 // showmode might reset the internal line pointers, so it must
5318 // be called before line = ml_get(), or when this address is no
5319 // longer needed. -- Acevedo.
5320 edit_submode_extra = (char_u *)_("-- Searching...");
5321 edit_submode_highl = HLF_COUNT;
5322 showmode();
5323 edit_submode_extra = NULL;
5324 out_flush();
5325
5326 return OK;
5327}
5328
5329/*
5330 * display the completion status message
5331 */
5332 static void
5333ins_compl_show_statusmsg(void)
5334{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005335 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005336 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005337 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005338 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005339 ? (char_u *)_("Hit end of paragraph")
5340 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005341 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005342 }
5343
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005344 if (edit_submode_extra == NULL)
5345 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005346 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005347 {
5348 edit_submode_extra = (char_u *)_("Back at original");
5349 edit_submode_highl = HLF_W;
5350 }
5351 else if (compl_cont_status & CONT_S_IPOS)
5352 {
5353 edit_submode_extra = (char_u *)_("Word from other line");
5354 edit_submode_highl = HLF_COUNT;
5355 }
5356 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5357 {
5358 edit_submode_extra = (char_u *)_("The only match");
5359 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005360 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005361 }
5362 else
5363 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005364#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005365 // Update completion sequence number when needed.
5366 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005367 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005368#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005369 // The match should always have a sequence number now, this is
5370 // just a safety check.
5371 if (compl_curr_match->cp_number != -1)
5372 {
5373 // Space for 10 text chars. + 2x10-digit no.s = 31.
5374 // Translations may need more than twice that.
5375 static char_u match_ref[81];
5376
5377 if (compl_matches > 0)
5378 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005379 _("match %d of %d"),
5380 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005381 else
5382 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005383 _("match %d"),
5384 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005385 edit_submode_extra = match_ref;
5386 edit_submode_highl = HLF_R;
5387 if (dollar_vcol >= 0)
5388 curs_columns(FALSE);
5389 }
5390 }
5391 }
5392
5393 // Show a message about what (completion) mode we're in.
5394 if (!compl_opt_suppress_empty)
5395 {
5396 showmode();
5397 if (!shortmess(SHM_COMPLETIONMENU))
5398 {
5399 if (edit_submode_extra != NULL)
5400 {
5401 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005402 {
5403 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005404 msg_attr((char *)edit_submode_extra,
5405 edit_submode_highl < HLF_COUNT
5406 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005407 msg_hist_off = FALSE;
5408 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005409 }
5410 else
5411 msg_clr_cmdline(); // necessary for "noshowmode"
5412 }
5413 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005414}
5415
5416/*
5417 * Do Insert mode completion.
5418 * Called when character "c" was typed, which has a meaning for completion.
5419 * Returns OK if completion was done, FAIL if something failed (out of mem).
5420 */
5421 int
5422ins_complete(int c, int enable_pum)
5423{
5424 int n;
5425 int save_w_wrow;
5426 int save_w_leftcol;
5427 int insert_match;
5428
5429 compl_direction = ins_compl_key2dir(c);
5430 insert_match = ins_compl_use_match(c);
5431
5432 if (!compl_started)
5433 {
5434 if (ins_compl_start() == FAIL)
5435 return FAIL;
5436 }
5437 else if (insert_match && stop_arrow() == FAIL)
5438 return FAIL;
5439
5440 compl_shown_match = compl_curr_match;
5441 compl_shows_dir = compl_direction;
5442
5443 // Find next match (and following matches).
5444 save_w_wrow = curwin->w_wrow;
5445 save_w_leftcol = curwin->w_leftcol;
5446 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5447
5448 // may undisplay the popup menu
5449 ins_compl_upd_pum();
5450
5451 if (n > 1) // all matches have been found
5452 compl_matches = n;
5453 compl_curr_match = compl_shown_match;
5454 compl_direction = compl_shows_dir;
5455
5456 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5457 // mode.
5458 if (got_int && !global_busy)
5459 {
5460 (void)vgetc();
5461 got_int = FALSE;
5462 }
5463
5464 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005465 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005466 {
5467 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5468 // because we couldn't expand anything at first place, but if we used
5469 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5470 // (such as M in M'exico) if not tried already. -- Acevedo
5471 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005472 || compl_status_adding()
5473 || (ctrl_x_mode_not_default()
5474 && !ctrl_x_mode_path_patterns()
5475 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005476 compl_cont_status &= ~CONT_N_ADDS;
5477 }
5478
5479 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5480 compl_cont_status |= CONT_S_IPOS;
5481 else
5482 compl_cont_status &= ~CONT_S_IPOS;
5483
5484 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005485
5486 // Show the popup menu, unless we got interrupted.
5487 if (enable_pum && !compl_interrupted)
5488 show_pum(save_w_wrow, save_w_leftcol);
5489
5490 compl_was_interrupted = compl_interrupted;
5491 compl_interrupted = FALSE;
5492
5493 return OK;
5494}
5495
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005496/*
5497 * Remove (if needed) and show the popup menu
5498 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005499 static void
5500show_pum(int prev_w_wrow, int prev_w_leftcol)
5501{
5502 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005503 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005504 RedrawingDisabled = 0;
5505
5506 // If the cursor moved or the display scrolled we need to remove the pum
5507 // first.
5508 setcursor();
5509 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5510 ins_compl_del_pum();
5511
5512 ins_compl_show_pum();
5513 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005514
5515 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005516}
5517
5518/*
5519 * Looks in the first "len" chars. of "src" for search-metachars.
5520 * If dest is not NULL the chars. are copied there quoting (with
5521 * a backslash) the metachars, and dest would be NUL terminated.
5522 * Returns the length (needed) of dest
5523 */
5524 static unsigned
5525quote_meta(char_u *dest, char_u *src, int len)
5526{
5527 unsigned m = (unsigned)len + 1; // one extra for the NUL
5528
5529 for ( ; --len >= 0; src++)
5530 {
5531 switch (*src)
5532 {
5533 case '.':
5534 case '*':
5535 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005536 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005537 break;
5538 // FALLTHROUGH
5539 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005540 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005541 break;
5542 // FALLTHROUGH
5543 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005544 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005545 break;
5546 // FALLTHROUGH
5547 case '^': // currently it's not needed.
5548 case '$':
5549 m++;
5550 if (dest != NULL)
5551 *dest++ = '\\';
5552 break;
5553 }
5554 if (dest != NULL)
5555 *dest++ = *src;
5556 // Copy remaining bytes of a multibyte character.
5557 if (has_mbyte)
5558 {
5559 int i, mb_len;
5560
5561 mb_len = (*mb_ptr2len)(src) - 1;
5562 if (mb_len > 0 && len >= mb_len)
5563 for (i = 0; i < mb_len; ++i)
5564 {
5565 --len;
5566 ++src;
5567 if (dest != NULL)
5568 *dest++ = *src;
5569 }
5570 }
5571 }
5572 if (dest != NULL)
5573 *dest = NUL;
5574
5575 return m;
5576}
5577
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005578#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005579 void
5580free_insexpand_stuff(void)
5581{
John Marriott5e6ea922024-11-23 14:01:57 +01005582 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005583# ifdef FEAT_EVAL
5584 free_callback(&cfu_cb);
5585 free_callback(&ofu_cb);
5586 free_callback(&tsrfu_cb);
5587# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005588}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005589#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005590
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005591#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005592/*
5593 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5594 * spelled word, if there is one.
5595 */
5596 static void
5597spell_back_to_badword(void)
5598{
5599 pos_T tpos = curwin->w_cursor;
5600
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005601 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005602 if (curwin->w_cursor.col != tpos.col)
5603 start_arrow(&tpos);
5604}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005605#endif