blob: 8a6f8afd8f31ed03c206fbd9bc131ddfcfb842d5 [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
glepnird4088ed2024-12-31 10:55:22 +0100109 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200110 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200111 int cp_user_kind_hlattr; // highlight attribute for kind
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100112};
113
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200114// values for cp_flags
115# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
116# define CP_FREE_FNAME 2 // cp_fname is allocated
117# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
118# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
119# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200120# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100121
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100122/*
123 * All the current matches are stored in a list.
124 * "compl_first_match" points to the start of the list.
125 * "compl_curr_match" points to the currently selected entry.
126 * "compl_shown_match" is different from compl_curr_match during
127 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000128 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100129 */
130static compl_T *compl_first_match = NULL;
131static compl_T *compl_curr_match = NULL;
132static compl_T *compl_shown_match = NULL;
133static compl_T *compl_old_match = NULL;
134
135// After using a cursor key <Enter> selects a match in the popup menu,
136// otherwise it inserts a line break.
137static int compl_enter_selects = FALSE;
138
139// When "compl_leader" is not NULL only matches that start with this string
140// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100141static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100142
143static int compl_get_longest = FALSE; // put longest common string
144 // in compl_leader
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// Selected one of the matches. When FALSE the match was edited or using the
147// longest common string.
148static int compl_used_match;
149
150// didn't finish finding completions.
151static int compl_was_interrupted = FALSE;
152
153// Set when character typed while looking for matches and it means we should
154// stop looking for matches.
155static int compl_interrupted = FALSE;
156
157static int compl_restarting = FALSE; // don't insert match
158
159// When the first completion is done "compl_started" is set. When it's
160// FALSE the word to be completed must be located.
161static int compl_started = FALSE;
162
163// Which Ctrl-X mode are we in?
164static int ctrl_x_mode = CTRL_X_NORMAL;
165
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000166static int compl_matches = 0; // number of completion matches
John Marriott5e6ea922024-11-23 14:01:57 +0100167static string_T compl_pattern = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100168static int compl_direction = FORWARD;
169static int compl_shows_dir = FORWARD;
170static int compl_pending = 0; // > 1 for postponed CTRL-N
171static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000172// Length in bytes of the text being completed (this is deleted to be replaced
173// by the match.)
174static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100175static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100176static colnr_T compl_col = 0; // column where the text starts
177 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100178static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100179static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100180 // completion started
181static int compl_cont_mode = 0;
182static expand_T compl_xp;
183
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000184// List of flags for method of completion.
185static int compl_cont_status = 0;
186# define CONT_ADDING 1 // "normal" or "adding" expansion
187# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
188 // it's set only iff N_ADDS is set
189# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
190# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
191 // if so, word-wise-expansion will set SOL
192# define CONT_SOL 16 // pattern includes start of line, just for
193 // word-wise expansion, not set for ^X^L
194# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
195 // expansion, (eg use complete=.)
196
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100197static int compl_opt_refresh_always = FALSE;
198static int compl_opt_suppress_empty = FALSE;
199
glepnira218cc62024-06-03 19:32:39 +0200200static int compl_selected_item = -1;
201
glepnir8159fb12024-07-17 20:32:54 +0200202static int *compl_fuzzy_scores;
203
glepnir6a38aff2024-12-16 21:56:16 +0100204// "compl_match_array" points the currently displayed list of entries in the
205// popup menu. It is NULL when there is no popup menu.
206static pumitem_T *compl_match_array = NULL;
207static int compl_match_arraysize;
208
glepnir80b66202024-11-27 21:53:53 +0100209static 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 +0100210static void ins_compl_longest_match(compl_T *match);
211static void ins_compl_del_pum(void);
212static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
213static char_u *find_line_end(char_u *ptr);
214static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100215static int ins_compl_need_restart(void);
216static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000217static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100218static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100219static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100220static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
221# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
222static void ins_compl_add_list(list_T *list);
223static void ins_compl_add_dict(dict_T *dict);
224# endif
225static int ins_compl_key2dir(int c);
226static int ins_compl_pum_key(int c);
227static int ins_compl_key2count(int c);
228static void show_pum(int prev_w_wrow, int prev_w_leftcol);
229static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100230static int ins_compl_has_multiple(void);
231static void ins_compl_expand_multiple(char_u *str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100232
233#ifdef FEAT_SPELL
234static void spell_back_to_badword(void);
235static int spell_bad_len = 0; // length of located bad word
236#endif
237
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100238/*
239 * CTRL-X pressed in Insert mode.
240 */
241 void
242ins_ctrl_x(void)
243{
zeertzjqdca29d92021-08-31 19:12:51 +0200244 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100245 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000246 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100247 if (compl_cont_status & CONT_N_ADDS)
248 compl_cont_status |= CONT_INTRPT;
249 else
250 compl_cont_status = 0;
251 // We're not sure which CTRL-X mode it will be yet
252 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
253 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
254 edit_submode_pre = NULL;
255 showmode();
256 }
zeertzjqdca29d92021-08-31 19:12:51 +0200257 else
258 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
259 // CTRL-V look like CTRL-N
260 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100261
LemonBoy2bf52dd2022-04-09 18:17:34 +0100262 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100263}
264
265/*
266 * Functions to check the current CTRL-X mode.
267 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000268int ctrl_x_mode_none(void)
269 { return ctrl_x_mode == 0; }
270int ctrl_x_mode_normal(void)
271 { return ctrl_x_mode == CTRL_X_NORMAL; }
272int ctrl_x_mode_scroll(void)
273 { return ctrl_x_mode == CTRL_X_SCROLL; }
274int ctrl_x_mode_whole_line(void)
275 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
276int ctrl_x_mode_files(void)
277 { return ctrl_x_mode == CTRL_X_FILES; }
278int ctrl_x_mode_tags(void)
279 { return ctrl_x_mode == CTRL_X_TAGS; }
280int ctrl_x_mode_path_patterns(void)
281 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
282int ctrl_x_mode_path_defines(void)
283 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
284int ctrl_x_mode_dictionary(void)
285 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
286int ctrl_x_mode_thesaurus(void)
287 { return ctrl_x_mode == CTRL_X_THESAURUS; }
288int ctrl_x_mode_cmdline(void)
289 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200290 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000291int ctrl_x_mode_function(void)
292 { return ctrl_x_mode == CTRL_X_FUNCTION; }
293int ctrl_x_mode_omni(void)
294 { return ctrl_x_mode == CTRL_X_OMNI; }
295int ctrl_x_mode_spell(void)
296 { return ctrl_x_mode == CTRL_X_SPELL; }
297static int ctrl_x_mode_eval(void)
298 { return ctrl_x_mode == CTRL_X_EVAL; }
299int ctrl_x_mode_line_or_eval(void)
300 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301
302/*
303 * Whether other than default completion has been selected.
304 */
305 int
306ctrl_x_mode_not_default(void)
307{
308 return ctrl_x_mode != CTRL_X_NORMAL;
309}
310
311/*
zeertzjqdca29d92021-08-31 19:12:51 +0200312 * Whether CTRL-X was typed without a following character,
313 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100314 */
315 int
316ctrl_x_mode_not_defined_yet(void)
317{
318 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
319}
320
321/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000322 * Return TRUE if currently in "normal" or "adding" insert completion matches
323 * state
324 */
325 int
326compl_status_adding(void)
327{
328 return compl_cont_status & CONT_ADDING;
329}
330
331/*
332 * Return TRUE if the completion pattern includes start of line, just for
333 * word-wise expansion.
334 */
335 int
336compl_status_sol(void)
337{
338 return compl_cont_status & CONT_SOL;
339}
340
341/*
342 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
343 */
344 int
345compl_status_local(void)
346{
347 return compl_cont_status & CONT_LOCAL;
348}
349
350/*
351 * Clear the completion status flags
352 */
353 void
354compl_status_clear(void)
355{
356 compl_cont_status = 0;
357}
358
359/*
360 * Return TRUE if completion is using the forward direction matches
361 */
362 static int
363compl_dir_forward(void)
364{
365 return compl_direction == FORWARD;
366}
367
368/*
369 * Return TRUE if currently showing forward completion matches
370 */
371 static int
372compl_shows_dir_forward(void)
373{
374 return compl_shows_dir == FORWARD;
375}
376
377/*
378 * Return TRUE if currently showing backward completion matches
379 */
380 static int
381compl_shows_dir_backward(void)
382{
383 return compl_shows_dir == BACKWARD;
384}
385
386/*
387 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100388 */
389 int
390has_compl_option(int dict_opt)
391{
392 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200393#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100394 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200395#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100396 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100397 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
398#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100399 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100400#endif
401 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100402 {
403 ctrl_x_mode = CTRL_X_NORMAL;
404 edit_submode = NULL;
405 msg_attr(dict_opt ? _("'dictionary' option is empty")
406 : _("'thesaurus' option is empty"),
407 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100408 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100409 {
410 vim_beep(BO_COMPL);
411 setcursor();
412 out_flush();
413#ifdef FEAT_EVAL
414 if (!get_vim_var_nr(VV_TESTING))
415#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100416 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100417 }
418 return FALSE;
419 }
420 return TRUE;
421}
422
423/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000424 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100425 * This depends on the current mode.
426 */
427 int
428vim_is_ctrl_x_key(int c)
429{
430 // Always allow ^R - let its results then be checked
431 if (c == Ctrl_R)
432 return TRUE;
433
434 // Accept <PageUp> and <PageDown> if the popup menu is visible.
435 if (ins_compl_pum_key(c))
436 return TRUE;
437
438 switch (ctrl_x_mode)
439 {
440 case 0: // Not in any CTRL-X mode
441 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
442 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200443 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100444 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
445 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
446 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
447 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
448 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200449 || c == Ctrl_S || c == Ctrl_K || c == 's'
450 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100451 case CTRL_X_SCROLL:
452 return (c == Ctrl_Y || c == Ctrl_E);
453 case CTRL_X_WHOLE_LINE:
454 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
455 case CTRL_X_FILES:
456 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
457 case CTRL_X_DICTIONARY:
458 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
459 case CTRL_X_THESAURUS:
460 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
461 case CTRL_X_TAGS:
462 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
463#ifdef FEAT_FIND_ID
464 case CTRL_X_PATH_PATTERNS:
465 return (c == Ctrl_P || c == Ctrl_N);
466 case CTRL_X_PATH_DEFINES:
467 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
468#endif
469 case CTRL_X_CMDLINE:
470 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
471 || c == Ctrl_X);
472#ifdef FEAT_COMPL_FUNC
473 case CTRL_X_FUNCTION:
474 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
475 case CTRL_X_OMNI:
476 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
477#endif
478 case CTRL_X_SPELL:
479 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
480 case CTRL_X_EVAL:
481 return (c == Ctrl_P || c == Ctrl_N);
482 }
483 internal_error("vim_is_ctrl_x_key()");
484 return FALSE;
485}
486
487/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000488 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000489 */
490 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000491match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000492{
493 return match->cp_flags & CP_ORIGINAL_TEXT;
494}
495
496/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000497 * Returns TRUE if "match" is the first match in the completion list.
498 */
499 static int
500is_first_match(compl_T *match)
501{
502 return match == compl_first_match;
503}
504
505/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100506 * Return TRUE when character "c" is part of the item currently being
507 * completed. Used to decide whether to abandon complete mode when the menu
508 * is visible.
509 */
510 int
511ins_compl_accept_char(int c)
512{
513 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
514 // When expanding an identifier only accept identifier chars.
515 return vim_isIDc(c);
516
517 switch (ctrl_x_mode)
518 {
519 case CTRL_X_FILES:
520 // When expanding file name only accept file name chars. But not
521 // path separators, so that "proto/<Tab>" expands files in
522 // "proto", not "proto/" as a whole
523 return vim_isfilec(c) && !vim_ispathsep(c);
524
525 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200526 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100527 case CTRL_X_OMNI:
528 // Command line and Omni completion can work with just about any
529 // printable character, but do stop at white space.
530 return vim_isprintc(c) && !VIM_ISWHITE(c);
531
532 case CTRL_X_WHOLE_LINE:
533 // For while line completion a space can be part of the line.
534 return vim_isprintc(c);
535 }
536 return vim_iswordc(c);
537}
538
539/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000540 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100541 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000542 */
543 static char_u *
544ins_compl_infercase_gettext(
545 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100546 int char_len,
547 int compl_char_len,
548 int min_len,
549 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000550{
551 int *wca; // Wide character array.
552 char_u *p;
553 int i, c;
554 int has_lower = FALSE;
555 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100556 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000557
558 IObuff[0] = NUL;
559
560 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100561 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000562 if (wca == NULL)
563 return IObuff;
564
565 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100566 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100567 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000568 if (has_mbyte)
569 wca[i] = mb_ptr2char_adv(&p);
570 else
571 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100572 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000573
574 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100575 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000576 for (i = 0; i < min_len; ++i)
577 {
glepnir6e199932024-12-14 21:13:27 +0100578 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000579 if (MB_ISLOWER(c))
580 {
581 has_lower = TRUE;
582 if (MB_ISUPPER(wca[i]))
583 {
584 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100585 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000586 wca[i] = MB_TOLOWER(wca[i]);
587 break;
588 }
589 }
590 }
591
592 // Rule 2: No lower case, 2nd consecutive letter converted to
593 // upper case.
594 if (!has_lower)
595 {
John Marriott5e6ea922024-11-23 14:01:57 +0100596 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000597 for (i = 0; i < min_len; ++i)
598 {
glepnir6e199932024-12-14 21:13:27 +0100599 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000600 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
601 {
602 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100603 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000604 wca[i] = MB_TOUPPER(wca[i]);
605 break;
606 }
607 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
608 }
609 }
610
611 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100612 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000613 for (i = 0; i < min_len; ++i)
614 {
glepnir6e199932024-12-14 21:13:27 +0100615 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000616 if (MB_ISLOWER(c))
617 wca[i] = MB_TOLOWER(wca[i]);
618 else if (MB_ISUPPER(c))
619 wca[i] = MB_TOUPPER(wca[i]);
620 }
621
622 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000623 p = IObuff;
624 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100625 ga_init2(&gap, 1, 500);
626 while (i < char_len)
627 {
628 if (gap.ga_data != NULL)
629 {
630 if (ga_grow(&gap, 10) == FAIL)
631 {
632 ga_clear(&gap);
633 return (char_u *)"[failed]";
634 }
635 p = (char_u *)gap.ga_data + gap.ga_len;
636 if (has_mbyte)
637 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
638 else
639 {
640 *p = wca[i++];
641 ++gap.ga_len;
642 }
643 }
644 else if ((p - IObuff) + 6 >= IOSIZE)
645 {
646 // Multi-byte characters can occupy up to five bytes more than
647 // ASCII characters, and we also need one byte for NUL, so when
648 // getting to six bytes from the edge of IObuff switch to using a
649 // growarray. Add the character in the next round.
650 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100651 {
652 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100653 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100654 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100655 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100656 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100657 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100658 }
659 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000660 p += (*mb_char2bytes)(wca[i++], p);
661 else
662 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100663 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000664 vim_free(wca);
665
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100666 if (gap.ga_data != NULL)
667 {
668 *tofree = gap.ga_data;
669 return gap.ga_data;
670 }
671
672 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000673 return IObuff;
674}
675
676/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100677 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
678 * case of the originally typed text is used, and the case of the completed
679 * text is inferred, ie this tries to work out what case you probably wanted
680 * the rest of the word to be in -- webb
681 */
682 int
683ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200684 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100685 int len,
686 int icase,
687 char_u *fname,
688 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200689 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100690{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200691 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100693 int char_len; // count multi-byte characters
694 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100695 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200696 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100697 int res;
698 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100699
700 if (p_ic && curbuf->b_p_inf && len > 0)
701 {
702 // Infer case of completed part.
703
704 // Find actual length of completion.
705 if (has_mbyte)
706 {
707 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100708 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100709 while (*p != NUL)
710 {
711 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100712 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100713 }
714 }
715 else
glepnir6e199932024-12-14 21:13:27 +0100716 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100717 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100718 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719
720 // Find actual length of original text.
721 if (has_mbyte)
722 {
John Marriott5e6ea922024-11-23 14:01:57 +0100723 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100724 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 while (*p != NUL)
726 {
727 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100728 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100729 }
730 }
731 else
glepnir6e199932024-12-14 21:13:27 +0100732 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100733 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100734 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100737 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100738 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100739
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 str = ins_compl_infercase_gettext(str, char_len,
741 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200743 if (cont_s_ipos)
744 flags |= CP_CONT_S_IPOS;
745 if (icase)
746 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200747
glepnir5c66e232024-11-15 19:58:27 +0100748 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100749 vim_free(tofree);
750 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100751}
752
753/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000754 * Add a match to the list of matches. The arguments are:
755 * str - text of the match to add
756 * len - length of "str". If -1, then the length of "str" is
757 * computed.
758 * fname - file name to associate with this match.
759 * cptext - list of strings to use with this match (for abbr, menu, info
760 * and kind)
761 * user_data - user supplied data (any vim type) for this match
762 * cdir - match direction. If 0, use "compl_direction".
763 * flags_arg - match flags (cp_flags)
764 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100765 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000766 * If "cdir" is FORWARD, then the match is added after the current match.
767 * Otherwise, it is added before the current match.
768 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100769 * If the given string is already in the list of completions, then return
770 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
771 * maybe because alloc() returns NULL, then FAIL is returned.
772 */
773 static int
774ins_compl_add(
775 char_u *str,
776 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100778 char_u **cptext, // extra text for popup menu or NULL
779 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200781 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200782 int adup, // accept duplicate match
glepnir80b66202024-11-27 21:53:53 +0100783 int *user_hl) // user abbr/kind hlattr
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784{
785 compl_T *match;
786 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200787 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100788
Bram Moolenaarceb06192021-04-04 15:05:22 +0200789 if (flags & CP_FAST)
790 fast_breakcheck();
791 else
792 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100793 if (got_int)
794 return FAIL;
795 if (len < 0)
796 len = (int)STRLEN(str);
797
798 // If the same match is already present, don't add it.
799 if (compl_first_match != NULL && !adup)
800 {
801 match = compl_first_match;
802 do
803 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000804 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100805 && STRNCMP(match->cp_str.string, str, len) == 0
806 && ((int)match->cp_str.length <= len
807 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100808 return NOTDONE;
809 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000810 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100811 }
812
813 // Remove any popup menu before changing the list of matches.
814 ins_compl_del_pum();
815
816 // Allocate a new match structure.
817 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200818 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 if (match == NULL)
820 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100821 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100822 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100823 {
824 vim_free(match);
825 return FAIL;
826 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100827
John Marriott5e6ea922024-11-23 14:01:57 +0100828 match->cp_str.length = len;
829
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100830 // match-fname is:
831 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200832 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100833 // - NULL otherwise. --Acevedo
834 if (fname != NULL
835 && compl_curr_match != NULL
836 && compl_curr_match->cp_fname != NULL
837 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
838 match->cp_fname = compl_curr_match->cp_fname;
839 else if (fname != NULL)
840 {
841 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200842 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100843 }
844 else
845 match->cp_fname = NULL;
846 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100847 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
848 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100849
850 if (cptext != NULL)
851 {
852 int i;
853
854 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100855 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856 if (cptext[i] != NULL && *cptext[i] != NUL)
857 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100858 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100860#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100861 if (user_data != NULL)
862 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100863#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100864
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000865 // Link the new match structure after (FORWARD) or before (BACKWARD) the
866 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100867 if (compl_first_match == NULL)
868 match->cp_next = match->cp_prev = NULL;
869 else if (dir == FORWARD)
870 {
871 match->cp_next = compl_curr_match->cp_next;
872 match->cp_prev = compl_curr_match;
873 }
874 else // BACKWARD
875 {
876 match->cp_next = compl_curr_match;
877 match->cp_prev = compl_curr_match->cp_prev;
878 }
879 if (match->cp_next)
880 match->cp_next->cp_prev = match;
881 if (match->cp_prev)
882 match->cp_prev->cp_next = match;
883 else // if there's nothing before, it is the first match
884 compl_first_match = match;
885 compl_curr_match = match;
886
887 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 ins_compl_longest_match(match);
890
891 return OK;
892}
893
894/*
895 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200896 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100897 */
898 static int
899ins_compl_equal(compl_T *match, char_u *str, int len)
900{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200901 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200902 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200903 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100904 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
905 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100906}
907
908/*
glepnir6a38aff2024-12-16 21:56:16 +0100909 * when len is -1 mean use whole length of p otherwise part of p
910 */
911 static void
912ins_compl_insert_bytes(char_u *p, int len)
913{
914 if (len == -1)
915 len = (int)STRLEN(p);
916 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +0100917 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +0100918}
919
920/*
zeertzjqd32bf0a2024-12-17 20:55:13 +0100921 * Checks if the column is within the currently inserted completion text
922 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +0100923 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +0100924 */
925 int
glepnir76bdb822025-02-08 19:04:51 +0100926ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +0100927{
glepnir76bdb822025-02-08 19:04:51 +0100928 int start_col;
929 int attr;
930
931 if ((get_cot_flags() & COT_FUZZY)
932 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +0100933 return -1;
934
glepnir76bdb822025-02-08 19:04:51 +0100935 start_col = compl_col + (int)ins_compl_leader_len();
936 if (!ins_compl_has_multiple())
937 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
938
939 // Multiple lines
940 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
941 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
942 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
943 return attr;
glepnir6a38aff2024-12-16 21:56:16 +0100944
945 return -1;
946}
947
948/*
glepnir76bdb822025-02-08 19:04:51 +0100949 * Returns TRUE if the current completion string contains newline characters,
950 * indicating it's a multi-line completion.
951 */
952 static int
953ins_compl_has_multiple(void)
954{
955 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
956}
957
958/*
959 * Returns TRUE if the given line number falls within the range of a multi-line
960 * completion, i.e. between the starting line (compl_lnum) and current cursor
961 * line. Always returns FALSE for single-line completions.
962 */
963 int
964ins_compl_lnum_in_range(linenr_T lnum)
965{
966 if (!ins_compl_has_multiple())
967 return FALSE;
968 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
969}
970
971/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100972 * Reduce the longest common string for match "match".
973 */
974 static void
975ins_compl_longest_match(compl_T *match)
976{
977 char_u *p, *s;
978 int c1, c2;
979 int had_match;
980
John Marriott5e6ea922024-11-23 14:01:57 +0100981 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100982 {
983 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +0100984 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
985 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000986 return;
987
John Marriott5e6ea922024-11-23 14:01:57 +0100988 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000989 had_match = (curwin->w_cursor.col > compl_col);
990 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +0100991 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000992 ins_redraw(FALSE);
993
994 // When the match isn't there (to avoid matching itself) remove it
995 // again after redrawing.
996 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100997 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100998 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000999
1000 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001001 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001002
1003 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001004 p = compl_leader.string;
1005 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001006 while (*p != NUL)
1007 {
1008 if (has_mbyte)
1009 {
1010 c1 = mb_ptr2char(p);
1011 c2 = mb_ptr2char(s);
1012 }
1013 else
1014 {
1015 c1 = *p;
1016 c2 = *s;
1017 }
1018 if ((match->cp_flags & CP_ICASE)
1019 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1020 break;
1021 if (has_mbyte)
1022 {
1023 MB_PTR_ADV(p);
1024 MB_PTR_ADV(s);
1025 }
1026 else
1027 {
1028 ++p;
1029 ++s;
1030 }
1031 }
1032
1033 if (*p != NUL)
1034 {
1035 // Leader was shortened, need to change the inserted text.
1036 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001037 compl_leader.length = (size_t)(p - compl_leader.string);
1038
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001039 had_match = (curwin->w_cursor.col > compl_col);
1040 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01001041 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001042 ins_redraw(FALSE);
1043
1044 // When the match isn't there (to avoid matching itself) remove it
1045 // again after redrawing.
1046 if (!had_match)
1047 ins_compl_delete();
1048 }
1049
1050 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001051}
1052
1053/*
1054 * Add an array of matches to the list of matches.
1055 * Frees matches[].
1056 */
1057 static void
1058ins_compl_add_matches(
1059 int num_matches,
1060 char_u **matches,
1061 int icase)
1062{
1063 int i;
1064 int add_r = OK;
1065 int dir = compl_direction;
1066
1067 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001068 {
1069 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
1070 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL);
1071 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001072 // if dir was BACKWARD then honor it just once
1073 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001074 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001075 FreeWild(num_matches, matches);
1076}
1077
1078/*
1079 * Make the completion list cyclic.
1080 * Return the number of matches (excluding the original).
1081 */
1082 static int
1083ins_compl_make_cyclic(void)
1084{
1085 compl_T *match;
1086 int count = 0;
1087
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001088 if (compl_first_match == NULL)
1089 return 0;
1090
1091 // Find the end of the list.
1092 match = compl_first_match;
1093 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001094 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001095 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001096 match = match->cp_next;
1097 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001098 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001099 match->cp_next = compl_first_match;
1100 compl_first_match->cp_prev = match;
1101
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001102 return count;
1103}
1104
1105/*
1106 * Return whether there currently is a shown match.
1107 */
1108 int
1109ins_compl_has_shown_match(void)
1110{
1111 return compl_shown_match == NULL
1112 || compl_shown_match != compl_shown_match->cp_next;
1113}
1114
1115/*
1116 * Return whether the shown match is long enough.
1117 */
1118 int
1119ins_compl_long_shown_match(void)
1120{
John Marriott5e6ea922024-11-23 14:01:57 +01001121 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001122 > curwin->w_cursor.col - compl_col;
1123}
1124
1125/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001126 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001127 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001128 unsigned int
1129get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001130{
zeertzjq529b9ad2024-06-05 20:27:06 +02001131 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001132}
1133
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134/*
1135 * Update the screen and when there is any scrolling remove the popup menu.
1136 */
1137 static void
1138ins_compl_upd_pum(void)
1139{
1140 int h;
1141
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001142 if (compl_match_array == NULL)
1143 return;
1144
1145 h = curwin->w_cline_height;
1146 // Update the screen later, before drawing the popup menu over it.
1147 pum_call_update_screen();
1148 if (h != curwin->w_cline_height)
1149 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001150}
1151
1152/*
1153 * Remove any popup menu.
1154 */
1155 static void
1156ins_compl_del_pum(void)
1157{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 if (compl_match_array == NULL)
1159 return;
1160
1161 pum_undisplay();
1162 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001163}
1164
1165/*
1166 * Return TRUE if the popup menu should be displayed.
1167 */
1168 int
1169pum_wanted(void)
1170{
1171 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001172 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001173 return FALSE;
1174
1175 // The display looks bad on a B&W display.
1176 if (t_colors < 8
1177#ifdef FEAT_GUI
1178 && !gui.in_use
1179#endif
1180 )
1181 return FALSE;
1182 return TRUE;
1183}
1184
1185/*
1186 * Return TRUE if there are two or more matches to be shown in the popup menu.
1187 * One if 'completopt' contains "menuone".
1188 */
1189 static int
1190pum_enough_matches(void)
1191{
1192 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001193 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001194
1195 // Don't display the popup menu if there are no matches or there is only
1196 // one (ignoring the original text).
1197 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001198 do
1199 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001200 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001201 break;
1202 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001203 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001204
zeertzjq529b9ad2024-06-05 20:27:06 +02001205 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001206 return (i >= 1);
1207 return (i >= 2);
1208}
1209
Bram Moolenaar3075a452021-11-17 15:51:52 +00001210#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001211/*
1212 * Allocate Dict for the completed item.
1213 * { word, abbr, menu, kind, info }
1214 */
1215 static dict_T *
1216ins_compl_dict_alloc(compl_T *match)
1217{
1218 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1219
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001220 if (dict == NULL)
1221 return NULL;
1222
John Marriott5e6ea922024-11-23 14:01:57 +01001223 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001224 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1225 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1226 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1227 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1228 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1229 dict_add_string(dict, "user_data", (char_u *)"");
1230 else
1231 dict_add_tv(dict, "user_data", &match->cp_user_data);
1232
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001233 return dict;
1234}
1235
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001236/*
1237 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1238 * completion menu is changed.
1239 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001240 static void
1241trigger_complete_changed_event(int cur)
1242{
1243 dict_T *v_event;
1244 dict_T *item;
1245 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001246 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001247
1248 if (recursive)
1249 return;
1250
glepnir40891ba2025-02-10 22:18:00 +01001251 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001252 if (item == NULL)
1253 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001254 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001255 dict_add_dict(v_event, "completed_item", item);
1256 pum_set_event_info(v_event);
1257 dict_set_items_ro(v_event);
1258
1259 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001260 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001261 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001262 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001263 recursive = FALSE;
1264
Bram Moolenaar3075a452021-11-17 15:51:52 +00001265 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001266}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001267#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001268
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001269/*
glepnira218cc62024-06-03 19:32:39 +02001270 * pumitem qsort compare func
1271 */
1272 static int
zeertzjq8e567472024-06-14 20:04:42 +02001273ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001274{
1275 const int sa = (*(pumitem_T *)a).pum_score;
1276 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001277 const int ia = (*(pumitem_T *)a).pum_idx;
1278 const int ib = (*(pumitem_T *)b).pum_idx;
1279 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001280}
1281
1282/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001283 * Build a popup menu to show the completion matches.
1284 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1285 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001286 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001287 static int
1288ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001289{
1290 compl_T *compl;
1291 compl_T *shown_compl = NULL;
1292 int did_find_shown_match = FALSE;
1293 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001294 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001295 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001296 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001297 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001298 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001299 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1300 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001301 compl_T *match_head = NULL;
1302 compl_T *match_tail = NULL;
1303 compl_T *match_next = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001304
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001305 // Need to build the popup menu list.
1306 compl_match_arraysize = 0;
1307 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001308
glepnira49c0772024-11-30 10:56:30 +01001309 // If the current match is the original text don't find the first
1310 // match after it, don't highlight anything.
1311 if (match_at_original_text(compl_shown_match))
1312 shown_match_ok = TRUE;
1313
1314 if (compl_leader.string != NULL
1315 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1316 && shown_match_ok == FALSE)
1317 compl_shown_match = compl_no_select ? compl_first_match
1318 : compl_first_match->cp_next;
1319
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001320 do
1321 {
glepnird4088ed2024-12-31 10:55:22 +01001322 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001323 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1324 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001325 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001326 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001327
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001328 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001329 && (compl_leader.string == NULL
1330 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001331 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001332 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001333 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001334 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001335 if (match_head == NULL)
1336 match_head = compl;
1337 else
glepnira49c0772024-11-30 10:56:30 +01001338 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001339 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001340
glepnirf400a0c2025-01-23 19:55:14 +01001341 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001342 {
1343 if (compl == compl_shown_match || did_find_shown_match)
1344 {
1345 // This item is the shown match or this is the
1346 // first displayed item after the shown match.
1347 compl_shown_match = compl;
1348 did_find_shown_match = TRUE;
1349 shown_match_ok = TRUE;
1350 }
1351 else
1352 // Remember this displayed match for when the
1353 // shown match is just below it.
1354 shown_compl = compl;
1355 cur = i;
1356 }
glepnirf400a0c2025-01-23 19:55:14 +01001357 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001358 {
1359 if (i == 0)
1360 shown_compl = compl;
1361 // Update the maximum fuzzy score and the shown match
1362 // if the current item's score is higher
zeertzjqd65aa1b2025-01-25 15:29:03 +01001363 if (fuzzy_sort && compl->cp_score > max_fuzzy_score)
glepnira49c0772024-11-30 10:56:30 +01001364 {
1365 did_find_shown_match = TRUE;
1366 max_fuzzy_score = compl->cp_score;
1367 if (!compl_no_select)
1368 compl_shown_match = compl;
1369 }
1370
glepnir3af0a8d2025-02-20 22:06:16 +01001371 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001372 {
1373 cur = i;
1374 shown_match_ok = TRUE;
1375 }
1376 }
1377 i++;
glepnir80b66202024-11-27 21:53:53 +01001378 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001379
glepnirf400a0c2025-01-23 19:55:14 +01001380 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001381 {
1382 did_find_shown_match = TRUE;
1383
1384 // When the original text is the shown match don't set
1385 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001386 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001387 shown_match_ok = TRUE;
1388
1389 if (!shown_match_ok && shown_compl != NULL)
1390 {
1391 // The shown match isn't displayed, set it to the
1392 // previously displayed match.
1393 compl_shown_match = shown_compl;
1394 shown_match_ok = TRUE;
1395 }
1396 }
glepnira49c0772024-11-30 10:56:30 +01001397 compl = compl->cp_next;
1398 } while (compl != NULL && !is_first_match(compl));
1399
1400 if (compl_match_arraysize == 0)
1401 return -1;
1402
glepnirc0b7ca42025-02-13 20:27:44 +01001403 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1404 {
1405 compl_shown_match = shown_compl;
1406 shown_match_ok = TRUE;
1407 cur = 0;
1408 }
1409
glepnira49c0772024-11-30 10:56:30 +01001410 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1411 if (compl_match_array == NULL)
1412 return -1;
1413
1414 compl = match_head;
1415 i = 0;
1416 while (compl != NULL)
1417 {
glepnir6e199932024-12-14 21:13:27 +01001418 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1419 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001420 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1421 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1422 compl_match_array[i].pum_score = compl->cp_score;
1423 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1424 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001425 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1426 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001427 match_next = compl->cp_match_next;
1428 compl->cp_match_next = NULL;
1429 compl = match_next;
1430 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001431
zeertzjqd65aa1b2025-01-25 15:29:03 +01001432 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001433 {
1434 for (i = 0; i < compl_match_arraysize; i++)
1435 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001436 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001437 qsort(compl_match_array, (size_t)compl_match_arraysize,
1438 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001439 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001440 }
glepnira218cc62024-06-03 19:32:39 +02001441
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001442 if (!shown_match_ok) // no displayed match at all
1443 cur = -1;
1444
1445 return cur;
1446}
1447
1448/*
1449 * Show the popup menu for the list of matches.
1450 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1451 */
1452 void
1453ins_compl_show_pum(void)
1454{
1455 int i;
1456 int cur = -1;
1457 colnr_T col;
1458
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001459 if (!pum_wanted() || !pum_enough_matches())
1460 return;
1461
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001462 // Update the screen later, before drawing the popup menu over it.
1463 pum_call_update_screen();
1464
1465 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001466 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001467 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001468 else
1469 {
1470 // popup menu already exists, only need to find the current item.
1471 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001472 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001473 || compl_match_array[i].pum_text
1474 == compl_shown_match->cp_text[CPT_ABBR])
1475 {
1476 cur = i;
1477 break;
1478 }
1479 }
1480
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001481 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001482 {
1483#ifdef FEAT_EVAL
1484 if (compl_started && has_completechanged())
1485 trigger_complete_changed_event(cur);
1486#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001487 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001488 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001489
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001490 // In Replace mode when a $ is displayed at the end of the line only
1491 // part of the screen would be updated. We do need to redraw here.
1492 dollar_vcol = -1;
1493
1494 // Compute the screen column of the start of the completed text.
1495 // Use the cursor to get all wrapping and other settings right.
1496 col = curwin->w_cursor.col;
1497 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001498 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001499 pum_display(compl_match_array, compl_match_arraysize, cur);
1500 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001501
glepnircbb46b42024-02-03 18:11:13 +01001502 // After adding leader, set the current match to shown match.
1503 if (compl_started && compl_curr_match != compl_shown_match)
1504 compl_curr_match = compl_shown_match;
1505
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001506#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001507 if (has_completechanged())
1508 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001509#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001510}
1511
1512#define DICT_FIRST (1) // use just first element in "dict"
1513#define DICT_EXACT (2) // "dict" is the exact name of a file
1514
1515/*
glepnir40c1c332024-06-11 19:37:04 +02001516 * Get current completion leader
1517 */
1518 char_u *
1519ins_compl_leader(void)
1520{
John Marriott5e6ea922024-11-23 14:01:57 +01001521 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1522}
1523
1524/*
1525 * Get current completion leader length
1526 */
1527 size_t
1528ins_compl_leader_len(void)
1529{
1530 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001531}
1532
1533/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001534 * Add any identifiers that match the given pattern "pat" in the list of
1535 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001536 */
1537 static void
1538ins_compl_dictionaries(
1539 char_u *dict_start,
1540 char_u *pat,
1541 int flags, // DICT_FIRST and/or DICT_EXACT
1542 int thesaurus) // Thesaurus completion
1543{
1544 char_u *dict = dict_start;
1545 char_u *ptr;
1546 char_u *buf;
1547 regmatch_T regmatch;
1548 char_u **files;
1549 int count;
1550 int save_p_scs;
1551 int dir = compl_direction;
1552
1553 if (*dict == NUL)
1554 {
1555#ifdef FEAT_SPELL
1556 // When 'dictionary' is empty and spell checking is enabled use
1557 // "spell".
1558 if (!thesaurus && curwin->w_p_spell)
1559 dict = (char_u *)"spell";
1560 else
1561#endif
1562 return;
1563 }
1564
1565 buf = alloc(LSIZE);
1566 if (buf == NULL)
1567 return;
1568 regmatch.regprog = NULL; // so that we can goto theend
1569
1570 // If 'infercase' is set, don't use 'smartcase' here
1571 save_p_scs = p_scs;
1572 if (curbuf->b_p_inf)
1573 p_scs = FALSE;
1574
1575 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1576 // to only match at the start of a line. Otherwise just match the
1577 // pattern. Also need to double backslashes.
1578 if (ctrl_x_mode_line_or_eval())
1579 {
1580 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1581 size_t len;
1582
1583 if (pat_esc == NULL)
1584 goto theend;
1585 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001586 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001587 if (ptr == NULL)
1588 {
1589 vim_free(pat_esc);
1590 goto theend;
1591 }
1592 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1593 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1594 vim_free(pat_esc);
1595 vim_free(ptr);
1596 }
1597 else
1598 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001599 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001600 if (regmatch.regprog == NULL)
1601 goto theend;
1602 }
1603
1604 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1605 regmatch.rm_ic = ignorecase(pat);
1606 while (*dict != NUL && !got_int && !compl_interrupted)
1607 {
1608 // copy one dictionary file name into buf
1609 if (flags == DICT_EXACT)
1610 {
1611 count = 1;
1612 files = &dict;
1613 }
1614 else
1615 {
1616 // Expand wildcards in the dictionary name, but do not allow
1617 // backticks (for security, the 'dict' option may have been set in
1618 // a modeline).
1619 copy_option_part(&dict, buf, LSIZE, ",");
1620# ifdef FEAT_SPELL
1621 if (!thesaurus && STRCMP(buf, "spell") == 0)
1622 count = -1;
1623 else
1624# endif
1625 if (vim_strchr(buf, '`') != NULL
1626 || expand_wildcards(1, &buf, &count, &files,
1627 EW_FILE|EW_SILENT) != OK)
1628 count = 0;
1629 }
1630
1631# ifdef FEAT_SPELL
1632 if (count == -1)
1633 {
1634 // Complete from active spelling. Skip "\<" in the pattern, we
1635 // don't use it as a RE.
1636 if (pat[0] == '\\' && pat[1] == '<')
1637 ptr = pat + 2;
1638 else
1639 ptr = pat;
1640 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1641 }
1642 else
1643# endif
1644 if (count > 0) // avoid warning for using "files" uninit
1645 {
1646 ins_compl_files(count, files, thesaurus, flags,
1647 &regmatch, buf, &dir);
1648 if (flags != DICT_EXACT)
1649 FreeWild(count, files);
1650 }
1651 if (flags != 0)
1652 break;
1653 }
1654
1655theend:
1656 p_scs = save_p_scs;
1657 vim_regfree(regmatch.regprog);
1658 vim_free(buf);
1659}
1660
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001661/*
1662 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1663 * skipping the word at 'skip_word'. Returns OK on success.
1664 */
1665 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001666thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001667 char_u *fname,
1668 char_u **buf_arg,
1669 int dir,
1670 char_u *skip_word)
1671{
1672 int status = OK;
1673 char_u *ptr;
1674 char_u *wstart;
1675
1676 // Add the other matches on the line
1677 ptr = *buf_arg;
1678 while (!got_int)
1679 {
1680 // Find start of the next word. Skip white
1681 // space and punctuation.
1682 ptr = find_word_start(ptr);
1683 if (*ptr == NUL || *ptr == NL)
1684 break;
1685 wstart = ptr;
1686
1687 // Find end of the word.
1688 if (has_mbyte)
1689 // Japanese words may have characters in
1690 // different classes, only separate words
1691 // with single-byte non-word characters.
1692 while (*ptr != NUL)
1693 {
1694 int l = (*mb_ptr2len)(ptr);
1695
1696 if (l < 2 && !vim_iswordc(*ptr))
1697 break;
1698 ptr += l;
1699 }
1700 else
1701 ptr = find_word_end(ptr);
1702
1703 // Add the word. Skip the regexp match.
1704 if (wstart != skip_word)
1705 {
1706 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1707 fname, dir, FALSE);
1708 if (status == FAIL)
1709 break;
1710 }
1711 }
1712
1713 *buf_arg = ptr;
1714 return status;
1715}
1716
1717/*
1718 * Process "count" dictionary/thesaurus "files" and add the text matching
1719 * "regmatch".
1720 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001721 static void
1722ins_compl_files(
1723 int count,
1724 char_u **files,
1725 int thesaurus,
1726 int flags,
1727 regmatch_T *regmatch,
1728 char_u *buf,
1729 int *dir)
1730{
1731 char_u *ptr;
1732 int i;
1733 FILE *fp;
1734 int add_r;
1735
1736 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1737 {
1738 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001739 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001740 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001741 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001742 vim_snprintf((char *)IObuff, IOSIZE,
1743 _("Scanning dictionary: %s"), (char *)files[i]);
1744 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1745 }
1746
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001747 if (fp == NULL)
1748 continue;
1749
1750 // Read dictionary file line by line.
1751 // Check each line for a match.
1752 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001753 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001754 ptr = buf;
1755 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001756 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001757 ptr = regmatch->startp[0];
glepnir6e199932024-12-14 21:13:27 +01001758 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1759 : find_word_end(ptr);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001760 add_r = ins_compl_add_infercase(regmatch->startp[0],
1761 (int)(ptr - regmatch->startp[0]),
1762 p_ic, files[i], *dir, FALSE);
1763 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001764 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001765 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001766 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001767 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001768 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001769 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001770 if (add_r == OK)
1771 // if dir was BACKWARD then honor it just once
1772 *dir = FORWARD;
1773 else if (add_r == FAIL)
1774 break;
1775 // avoid expensive call to vim_regexec() when at end
1776 // of line
1777 if (*ptr == '\n' || got_int)
1778 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001779 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001780 line_breakcheck();
1781 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001782 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001783 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001784 }
1785}
1786
1787/*
1788 * Find the start of the next word.
1789 * Returns a pointer to the first char of the word. Also stops at a NUL.
1790 */
1791 char_u *
1792find_word_start(char_u *ptr)
1793{
1794 if (has_mbyte)
1795 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1796 ptr += (*mb_ptr2len)(ptr);
1797 else
1798 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1799 ++ptr;
1800 return ptr;
1801}
1802
1803/*
1804 * Find the end of the word. Assumes it starts inside a word.
1805 * Returns a pointer to just after the word.
1806 */
1807 char_u *
1808find_word_end(char_u *ptr)
1809{
1810 int start_class;
1811
1812 if (has_mbyte)
1813 {
1814 start_class = mb_get_class(ptr);
1815 if (start_class > 1)
1816 while (*ptr != NUL)
1817 {
1818 ptr += (*mb_ptr2len)(ptr);
1819 if (mb_get_class(ptr) != start_class)
1820 break;
1821 }
1822 }
1823 else
1824 while (vim_iswordc(*ptr))
1825 ++ptr;
1826 return ptr;
1827}
1828
1829/*
1830 * Find the end of the line, omitting CR and NL at the end.
1831 * Returns a pointer to just after the line.
1832 */
1833 static char_u *
1834find_line_end(char_u *ptr)
1835{
1836 char_u *s;
1837
1838 s = ptr + STRLEN(ptr);
1839 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1840 --s;
1841 return s;
1842}
1843
1844/*
1845 * Free the list of completions
1846 */
1847 static void
1848ins_compl_free(void)
1849{
1850 compl_T *match;
1851 int i;
1852
John Marriott5e6ea922024-11-23 14:01:57 +01001853 VIM_CLEAR_STRING(compl_pattern);
1854 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001855
1856 if (compl_first_match == NULL)
1857 return;
1858
1859 ins_compl_del_pum();
1860 pum_clear();
1861
1862 compl_curr_match = compl_first_match;
1863 do
1864 {
1865 match = compl_curr_match;
1866 compl_curr_match = compl_curr_match->cp_next;
John Marriott5e6ea922024-11-23 14:01:57 +01001867 VIM_CLEAR_STRING(match->cp_str);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001868 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001869 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001870 vim_free(match->cp_fname);
1871 for (i = 0; i < CPT_COUNT; ++i)
1872 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001873#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001874 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001875#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001876 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001877 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001878 compl_first_match = compl_curr_match = NULL;
1879 compl_shown_match = NULL;
1880 compl_old_match = NULL;
1881}
1882
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001883/*
1884 * Reset/clear the completion state.
1885 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001886 void
1887ins_compl_clear(void)
1888{
1889 compl_cont_status = 0;
1890 compl_started = FALSE;
1891 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01001892 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01001893 compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01001894 VIM_CLEAR_STRING(compl_pattern);
1895 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001896 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01001897 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001898 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001899#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001900 // clear v:completed_item
1901 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001902#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001903}
1904
1905/*
1906 * Return TRUE when Insert completion is active.
1907 */
1908 int
1909ins_compl_active(void)
1910{
1911 return compl_started;
1912}
1913
1914/*
glepnir8d0bb6d2024-12-24 09:44:35 +01001915 * Return True when wp is the actual completion window
1916 */
1917 int
1918ins_compl_win_active(win_T *wp UNUSED)
1919{
1920 return ins_compl_active()
1921#if defined(FEAT_QUICKFIX)
1922 && (!wp->w_p_pvw
1923# ifdef FEAT_PROP_POPUP
1924 && !(wp->w_popup_flags & POPF_INFO)
1925# endif
1926 )
1927#endif
1928 ;
1929}
1930
1931/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001932 * Selected one of the matches. When FALSE the match was edited or using the
1933 * longest common string.
1934 */
1935 int
1936ins_compl_used_match(void)
1937{
1938 return compl_used_match;
1939}
1940
1941/*
1942 * Initialize get longest common string.
1943 */
1944 void
1945ins_compl_init_get_longest(void)
1946{
1947 compl_get_longest = FALSE;
1948}
1949
1950/*
1951 * Returns TRUE when insert completion is interrupted.
1952 */
1953 int
1954ins_compl_interrupted(void)
1955{
1956 return compl_interrupted;
1957}
1958
1959/*
1960 * Returns TRUE if the <Enter> key selects a match in the completion popup
1961 * menu.
1962 */
1963 int
1964ins_compl_enter_selects(void)
1965{
1966 return compl_enter_selects;
1967}
1968
1969/*
1970 * Return the column where the text starts that is being completed
1971 */
1972 colnr_T
1973ins_compl_col(void)
1974{
1975 return compl_col;
1976}
1977
1978/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001979 * Return the length in bytes of the text being completed
1980 */
1981 int
1982ins_compl_len(void)
1983{
1984 return compl_length;
1985}
1986
1987/*
glepnira2c55592025-02-28 17:43:42 +01001988 * Return TRUE when preinsert is set AND both 'menu' and 'menuone' flags
1989 * are also set, otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01001990 */
1991 static int
1992ins_compl_has_preinsert(void)
1993{
glepnira2c55592025-02-28 17:43:42 +01001994 int cur_cot_flags = get_cot_flags();
1995 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENU | COT_MENUONE))
1996 == (COT_PREINSERT | COT_MENU | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01001997}
1998
1999/*
2000 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2001 * the `compl_ins_end_col` range.
2002 */
2003 int
2004ins_compl_preinsert_effect(void)
2005{
2006 if (!ins_compl_has_preinsert())
2007 return FALSE;
2008
2009 return curwin->w_cursor.col < compl_ins_end_col;
2010}
2011
2012/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002013 * Delete one character before the cursor and show the subset of the matches
2014 * that match the word that is now before the cursor.
2015 * Returns the character to be used, NUL if the work is done and another char
2016 * to be got from the user.
2017 */
2018 int
2019ins_compl_bs(void)
2020{
2021 char_u *line;
2022 char_u *p;
2023
glepniredd4ac32025-01-29 18:53:51 +01002024 if (ins_compl_preinsert_effect())
2025 ins_compl_delete();
2026
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002027 line = ml_get_curline();
2028 p = line + curwin->w_cursor.col;
2029 MB_PTR_BACK(line, p);
2030
2031 // Stop completion when the whole word was deleted. For Omni completion
2032 // allow the word to be deleted, we won't match everything.
2033 // Respect the 'backspace' option.
2034 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002035 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2036 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002037 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2038 - compl_length < 0))
2039 return K_BS;
2040
2041 // Deleted more than what was used to find matches or didn't finish
2042 // finding all matches: need to look for matches all over again.
2043 if (curwin->w_cursor.col <= compl_col + compl_length
2044 || ins_compl_need_restart())
2045 ins_compl_restart();
2046
John Marriott5e6ea922024-11-23 14:01:57 +01002047 VIM_CLEAR_STRING(compl_leader);
2048 compl_leader.length = (size_t)((p - line) - compl_col);
2049 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2050 if (compl_leader.string == NULL)
2051 {
2052 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002053 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002054 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002055
2056 ins_compl_new_leader();
2057 if (compl_shown_match != NULL)
2058 // Make sure current match is not a hidden item.
2059 compl_curr_match = compl_shown_match;
2060 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002061}
2062
2063/*
2064 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2065 * be called.
2066 */
2067 static int
2068ins_compl_need_restart(void)
2069{
2070 // Return TRUE if we didn't complete finding matches or when the
2071 // 'completefunc' returned "always" in the "refresh" dictionary item.
2072 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002073 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002074 && compl_opt_refresh_always);
2075}
2076
2077/*
2078 * Called after changing "compl_leader".
2079 * Show the popup menu with a different set of matches.
2080 * May also search for matches again if the previous search was interrupted.
2081 */
2082 static void
2083ins_compl_new_leader(void)
2084{
2085 ins_compl_del_pum();
2086 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002087 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002088 compl_used_match = FALSE;
2089
2090 if (compl_started)
John Marriott5e6ea922024-11-23 14:01:57 +01002091 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002092 else
2093 {
2094#ifdef FEAT_SPELL
2095 spell_bad_len = 0; // need to redetect bad word
2096#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002097 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098 // the popup menu display the changed text before the cursor. Set
2099 // "compl_restarting" to avoid that the first match is inserted.
2100 pum_call_update_screen();
2101#ifdef FEAT_GUI
2102 if (gui.in_use)
2103 {
2104 // Show the cursor after the match, not after the redrawn text.
2105 setcursor();
2106 out_flush_cursor(FALSE, FALSE);
2107 }
2108#endif
2109 compl_restarting = TRUE;
2110 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2111 compl_cont_status = 0;
2112 compl_restarting = FALSE;
2113 }
2114
glepnir44180412025-02-20 22:09:48 +01002115 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002116
2117 // Show the popup menu with a different set of matches.
2118 ins_compl_show_pum();
2119
2120 // Don't let Enter select the original text when there is no popup menu.
2121 if (compl_match_array == NULL)
2122 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002123 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2124 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002125}
2126
2127/*
2128 * Return the length of the completion, from the completion start column to
2129 * the cursor column. Making sure it never goes below zero.
2130 */
2131 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002132get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133{
2134 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002135 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002136}
2137
2138/*
2139 * Append one character to the match leader. May reduce the number of
2140 * matches.
2141 */
2142 void
2143ins_compl_addleader(int c)
2144{
2145 int cc;
2146
glepniredd4ac32025-01-29 18:53:51 +01002147 if (ins_compl_preinsert_effect())
2148 ins_compl_delete();
2149
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002150 if (stop_arrow() == FAIL)
2151 return;
2152 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2153 {
2154 char_u buf[MB_MAXBYTES + 1];
2155
2156 (*mb_char2bytes)(c, buf);
2157 buf[cc] = NUL;
2158 ins_char_bytes(buf, cc);
2159 if (compl_opt_refresh_always)
2160 AppendToRedobuff(buf);
2161 }
2162 else
2163 {
2164 ins_char(c);
2165 if (compl_opt_refresh_always)
2166 AppendCharToRedobuff(c);
2167 }
2168
2169 // If we didn't complete finding matches we must search again.
2170 if (ins_compl_need_restart())
2171 ins_compl_restart();
2172
2173 // When 'always' is set, don't reset compl_leader. While completing,
2174 // cursor doesn't point original position, changing compl_leader would
2175 // break redo.
2176 if (!compl_opt_refresh_always)
2177 {
John Marriott5e6ea922024-11-23 14:01:57 +01002178 VIM_CLEAR_STRING(compl_leader);
2179 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2180 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2181 compl_leader.length);
2182 if (compl_leader.string == NULL)
2183 {
2184 compl_leader.length = 0;
2185 return;
2186 }
2187
2188 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002189 }
2190}
2191
2192/*
2193 * Setup for finding completions again without leaving CTRL-X mode. Used when
2194 * BS or a key was typed while still searching for matches.
2195 */
2196 static void
2197ins_compl_restart(void)
2198{
2199 ins_compl_free();
2200 compl_started = FALSE;
2201 compl_matches = 0;
2202 compl_cont_status = 0;
2203 compl_cont_mode = 0;
2204}
2205
2206/*
2207 * Set the first match, the original text.
2208 */
2209 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002210ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002211{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002212 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002213 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2214 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002215 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002216 {
John Marriott5e6ea922024-11-23 14:01:57 +01002217 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002218 if (p != NULL)
2219 {
John Marriott5e6ea922024-11-23 14:01:57 +01002220 VIM_CLEAR_STRING(compl_first_match->cp_str);
2221 compl_first_match->cp_str.string = p;
2222 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002223 }
2224 }
2225 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002226 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002227 {
John Marriott5e6ea922024-11-23 14:01:57 +01002228 char_u *p = vim_strnsave(str, len);
2229 if (p != NULL)
2230 {
2231 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2232 compl_first_match->cp_prev->cp_str.string = p;
2233 compl_first_match->cp_prev->cp_str.length = len;
2234 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002235 }
2236}
2237
2238/*
2239 * Append one character to the match leader. May reduce the number of
2240 * matches.
2241 */
2242 void
2243ins_compl_addfrommatch(void)
2244{
2245 char_u *p;
2246 int len = (int)curwin->w_cursor.col - (int)compl_col;
2247 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002248
John Marriott5e6ea922024-11-23 14:01:57 +01002249 p = compl_shown_match->cp_str.string;
2250 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002251 {
John Marriott5e6ea922024-11-23 14:01:57 +01002252 size_t plen;
2253 compl_T *cp;
2254
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002255 // When still at the original match use the first entry that matches
2256 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002257 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002258 return;
2259
2260 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002261 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002262 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002263 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002264 {
John Marriott5e6ea922024-11-23 14:01:57 +01002265 if (compl_leader.string == NULL
2266 || ins_compl_equal(cp, compl_leader.string,
2267 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002268 {
John Marriott5e6ea922024-11-23 14:01:57 +01002269 p = cp->cp_str.string;
2270 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002271 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002272 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002273 }
John Marriott5e6ea922024-11-23 14:01:57 +01002274 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002275 return;
2276 }
2277 p += len;
2278 c = PTR2CHAR(p);
2279 ins_compl_addleader(c);
2280}
2281
2282/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002283 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002284 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2285 * compl_cont_mode and compl_cont_status.
2286 * Returns TRUE when the character is not to be inserted.
2287 */
2288 static int
2289set_ctrl_x_mode(int c)
2290{
2291 int retval = FALSE;
2292
2293 switch (c)
2294 {
2295 case Ctrl_E:
2296 case Ctrl_Y:
2297 // scroll the window one line up or down
2298 ctrl_x_mode = CTRL_X_SCROLL;
2299 if (!(State & REPLACE_FLAG))
2300 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2301 else
2302 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2303 edit_submode_pre = NULL;
2304 showmode();
2305 break;
2306 case Ctrl_L:
2307 // complete whole line
2308 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2309 break;
2310 case Ctrl_F:
2311 // complete filenames
2312 ctrl_x_mode = CTRL_X_FILES;
2313 break;
2314 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002315 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002316 ctrl_x_mode = CTRL_X_DICTIONARY;
2317 break;
2318 case Ctrl_R:
2319 // Register insertion without exiting CTRL-X mode
2320 // Simply allow ^R to happen without affecting ^X mode
2321 break;
2322 case Ctrl_T:
2323 // complete words from a thesaurus
2324 ctrl_x_mode = CTRL_X_THESAURUS;
2325 break;
2326#ifdef FEAT_COMPL_FUNC
2327 case Ctrl_U:
2328 // user defined completion
2329 ctrl_x_mode = CTRL_X_FUNCTION;
2330 break;
2331 case Ctrl_O:
2332 // omni completion
2333 ctrl_x_mode = CTRL_X_OMNI;
2334 break;
2335#endif
2336 case 's':
2337 case Ctrl_S:
2338 // complete spelling suggestions
2339 ctrl_x_mode = CTRL_X_SPELL;
2340#ifdef FEAT_SPELL
2341 ++emsg_off; // Avoid getting the E756 error twice.
2342 spell_back_to_badword();
2343 --emsg_off;
2344#endif
2345 break;
2346 case Ctrl_RSB:
2347 // complete tag names
2348 ctrl_x_mode = CTRL_X_TAGS;
2349 break;
2350#ifdef FEAT_FIND_ID
2351 case Ctrl_I:
2352 case K_S_TAB:
2353 // complete keywords from included files
2354 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2355 break;
2356 case Ctrl_D:
2357 // complete definitions from included files
2358 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2359 break;
2360#endif
2361 case Ctrl_V:
2362 case Ctrl_Q:
2363 // complete vim commands
2364 ctrl_x_mode = CTRL_X_CMDLINE;
2365 break;
2366 case Ctrl_Z:
2367 // stop completion
2368 ctrl_x_mode = CTRL_X_NORMAL;
2369 edit_submode = NULL;
2370 showmode();
2371 retval = TRUE;
2372 break;
2373 case Ctrl_P:
2374 case Ctrl_N:
2375 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2376 // just started ^X mode, or there were enough ^X's to cancel
2377 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2378 // do normal expansion when interrupting a different mode (say
2379 // ^X^F^X^P or ^P^X^X^P, see below)
2380 // nothing changes if interrupting mode 0, (eg, the flag
2381 // doesn't change when going to ADDING mode -- Acevedo
2382 if (!(compl_cont_status & CONT_INTRPT))
2383 compl_cont_status |= CONT_LOCAL;
2384 else if (compl_cont_mode != 0)
2385 compl_cont_status &= ~CONT_LOCAL;
2386 // FALLTHROUGH
2387 default:
2388 // If we have typed at least 2 ^X's... for modes != 0, we set
2389 // compl_cont_status = 0 (eg, as if we had just started ^X
2390 // mode).
2391 // For mode 0, we set "compl_cont_mode" to an impossible
2392 // value, in both cases ^X^X can be used to restart the same
2393 // mode (avoiding ADDING mode).
2394 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2395 // 'complete' and local ^P expansions respectively.
2396 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2397 // mode -- Acevedo
2398 if (c == Ctrl_X)
2399 {
2400 if (compl_cont_mode != 0)
2401 compl_cont_status = 0;
2402 else
2403 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2404 }
2405 ctrl_x_mode = CTRL_X_NORMAL;
2406 edit_submode = NULL;
2407 showmode();
2408 break;
2409 }
2410
2411 return retval;
2412}
2413
2414/*
glepnir1c5a1202024-12-04 20:27:34 +01002415 * Trigger CompleteDone event and adds relevant information to v:event
2416 */
2417 static void
2418trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2419{
2420#if defined(FEAT_EVAL)
2421 save_v_event_T save_v_event;
2422 dict_T *v_event = get_v_event(&save_v_event);
2423 char_u *mode_str = NULL;
2424
2425 mode = mode & ~CTRL_X_WANT_IDENT;
2426 if (ctrl_x_mode_names[mode])
2427 mode_str = (char_u *)ctrl_x_mode_names[mode];
2428
2429 (void)dict_add_string(v_event, "complete_word",
2430 word == NULL ? (char_u *)"" : word);
2431 (void)dict_add_string(v_event, "complete_type",
2432 mode_str != NULL ? mode_str : (char_u *)"");
2433
2434 dict_set_items_ro(v_event);
2435#endif
2436 ins_apply_autocmds(EVENT_COMPLETEDONE);
2437
2438#if defined(FEAT_EVAL)
2439 restore_v_event(v_event, &save_v_event);
2440#endif
2441}
2442
2443/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002444 * Stop insert completion mode
2445 */
2446 static int
2447ins_compl_stop(int c, int prev_mode, int retval)
2448{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002449 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002450 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002451
2452 // Get here when we have finished typing a sequence of ^N and
2453 // ^P or other completion characters in CTRL-X mode. Free up
2454 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002455 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002456 {
glepnir40891ba2025-02-10 22:18:00 +01002457 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002458
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002459 // If any of the original typed text has been changed, eg when
2460 // ignorecase is set, we must add back-spaces to the redo
2461 // buffer. We add as few as necessary to delete just the part
2462 // of the original text that has changed.
2463 // When using the longest match, edited the match or used
2464 // CTRL-E then don't use the current match.
2465 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002466 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002467 ins_compl_fixRedoBufForLeader(ptr);
2468 }
2469
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002470 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002471
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002472 // When completing whole lines: fix indent for 'cindent'.
2473 // Otherwise, break line if it's too long.
2474 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2475 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002476 // re-indent the current line
2477 if (want_cindent)
2478 {
2479 do_c_expr_indent();
2480 want_cindent = FALSE; // don't do it again
2481 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002482 }
2483 else
2484 {
2485 int prev_col = curwin->w_cursor.col;
2486
2487 // put the cursor on the last char, for 'tw' formatting
2488 if (prev_col > 0)
2489 dec_cursor();
2490 // only format when something was inserted
2491 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2492 insertchar(NUL, 0, -1);
2493 if (prev_col > 0
2494 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2495 inc_cursor();
2496 }
2497
2498 // If the popup menu is displayed pressing CTRL-Y means accepting
2499 // the selection without inserting anything. When
2500 // compl_enter_selects is set the Enter key does the same.
2501 if ((c == Ctrl_Y || (compl_enter_selects
2502 && (c == CAR || c == K_KENTER || c == NL)))
2503 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002504 {
2505 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002506 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002507 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002508
2509 // CTRL-E means completion is Ended, go back to the typed text.
2510 // but only do this, if the Popup is still visible
2511 if (c == Ctrl_E)
2512 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002513 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002514 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002515
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002516 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002517 if (compl_leader.string != NULL)
2518 {
2519 p = compl_leader.string;
2520 plen = compl_leader.length;
2521 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002522 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002523 {
2524 p = compl_orig_text.string;
2525 plen = compl_orig_text.length;
2526 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002527 if (p != NULL)
2528 {
2529 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002530
John Marriott5e6ea922024-11-23 14:01:57 +01002531 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002532 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002533 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002534 retval = TRUE;
2535 }
2536
glepnir001c26c2025-02-02 09:36:22 +01002537 if ((c == Ctrl_W || c == Ctrl_U) && ins_compl_preinsert_effect())
2538 ins_compl_delete();
2539
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002540 auto_format(FALSE, TRUE);
2541
2542 // Trigger the CompleteDonePre event to give scripts a chance to
2543 // act upon the completion before clearing the info, and restore
2544 // ctrl_x_mode, so that complete_info() can be used.
2545 ctrl_x_mode = prev_mode;
2546 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2547
2548 ins_compl_free();
2549 compl_started = FALSE;
2550 compl_matches = 0;
2551 if (!shortmess(SHM_COMPLETIONMENU))
2552 msg_clr_cmdline(); // necessary for "noshowmode"
2553 ctrl_x_mode = CTRL_X_NORMAL;
2554 compl_enter_selects = FALSE;
2555 if (edit_submode != NULL)
2556 {
2557 edit_submode = NULL;
2558 showmode();
2559 }
2560
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002561 if (c == Ctrl_C && cmdwin_type != 0)
2562 // Avoid the popup menu remains displayed when leaving the
2563 // command line window.
2564 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002565 // Indent now if a key was typed that is in 'cinkeys'.
2566 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2567 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002568 // Trigger the CompleteDone event to give scripts a chance to act
2569 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002570 trigger_complete_done_event(prev_mode, word);
2571 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002572
2573 return retval;
2574}
2575
2576/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002577 * Prepare for Insert mode completion, or stop it.
2578 * Called just after typing a character in Insert mode.
2579 * Returns TRUE when the character is not to be inserted;
2580 */
2581 int
2582ins_compl_prep(int c)
2583{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002584 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002585 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002586
2587 // Forget any previous 'special' messages if this is actually
2588 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2589 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2590 edit_submode_extra = NULL;
2591
zeertzjq440d4cb2023-03-02 17:51:32 +00002592 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002593 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002594 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002595 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002596 return retval;
2597
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002598#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002599 // Ignore mouse events in a popup window
2600 if (is_mouse_key(c))
2601 {
2602 // Ignore drag and release events, the position does not need to be in
2603 // the popup and it may have just closed.
2604 if (c == K_LEFTRELEASE
2605 || c == K_LEFTRELEASE_NM
2606 || c == K_MIDDLERELEASE
2607 || c == K_RIGHTRELEASE
2608 || c == K_X1RELEASE
2609 || c == K_X2RELEASE
2610 || c == K_LEFTDRAG
2611 || c == K_MIDDLEDRAG
2612 || c == K_RIGHTDRAG
2613 || c == K_X1DRAG
2614 || c == K_X2DRAG)
2615 return retval;
2616 if (popup_visible)
2617 {
2618 int row = mouse_row;
2619 int col = mouse_col;
2620 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2621
2622 if (wp != NULL && WIN_IS_POPUP(wp))
2623 return retval;
2624 }
2625 }
2626#endif
2627
zeertzjqdca29d92021-08-31 19:12:51 +02002628 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2629 {
2630 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2631 || !vim_is_ctrl_x_key(c))
2632 {
2633 // Not starting another completion mode.
2634 ctrl_x_mode = CTRL_X_CMDLINE;
2635
2636 // CTRL-X CTRL-Z should stop completion without inserting anything
2637 if (c == Ctrl_Z)
2638 retval = TRUE;
2639 }
2640 else
2641 {
2642 ctrl_x_mode = CTRL_X_CMDLINE;
2643
2644 // Other CTRL-X keys first stop completion, then start another
2645 // completion mode.
2646 ins_compl_prep(' ');
2647 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2648 }
2649 }
2650
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002651 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002652 if (ctrl_x_mode_not_defined_yet()
2653 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002654 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002655 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002656 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002657 }
2658
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002659 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002660 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2661 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002662 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002663 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002664 {
2665 // We're already in CTRL-X mode, do we stay in it?
2666 if (!vim_is_ctrl_x_key(c))
2667 {
glepnir40891ba2025-02-10 22:18:00 +01002668 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002669 edit_submode = NULL;
2670 }
2671 showmode();
2672 }
2673
2674 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2675 {
2676 // Show error message from attempted keyword completion (probably
2677 // 'Pattern not found') until another key is hit, then go back to
2678 // showing what mode we are in.
2679 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002680 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002681 && c != Ctrl_R && !ins_compl_pum_key(c))
2682 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002683 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002684 }
2685 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2686 // Trigger the CompleteDone event to give scripts a chance to act
2687 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002688 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002689
LemonBoy2bf52dd2022-04-09 18:17:34 +01002690 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002691
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002692 // reset continue_* if we left expansion-mode, if we stay they'll be
2693 // (re)set properly in ins_complete()
2694 if (!vim_is_ctrl_x_key(c))
2695 {
2696 compl_cont_status = 0;
2697 compl_cont_mode = 0;
2698 }
2699
2700 return retval;
2701}
2702
2703/*
2704 * Fix the redo buffer for the completion leader replacing some of the typed
2705 * text. This inserts backspaces and appends the changed text.
2706 * "ptr" is the known leader text or NUL.
2707 */
2708 static void
2709ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2710{
John Marriott5e6ea922024-11-23 14:01:57 +01002711 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002712 char_u *p;
2713 char_u *ptr = ptr_arg;
2714
2715 if (ptr == NULL)
2716 {
John Marriott5e6ea922024-11-23 14:01:57 +01002717 if (compl_leader.string != NULL)
2718 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002719 else
2720 return; // nothing to do
2721 }
John Marriott5e6ea922024-11-23 14:01:57 +01002722 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002723 {
John Marriott5e6ea922024-11-23 14:01:57 +01002724 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002725 // Find length of common prefix between original text and new completion
2726 while (p[len] != NUL && p[len] == ptr[len])
2727 len++;
2728 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002729 if (len > 0)
2730 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002731 // Add backspace characters for each remaining character in
2732 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002733 for (p += len; *p != NUL; MB_PTR_ADV(p))
2734 AppendCharToRedobuff(K_BS);
2735 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002736 if (ptr != NULL)
2737 AppendToRedobuffLit(ptr + len, -1);
2738}
2739
2740/*
2741 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2742 * (depending on flag) starting from buf and looking for a non-scanned
2743 * buffer (other than curbuf). curbuf is special, if it is called with
2744 * buf=curbuf then it has to be the first call for a given flag/expansion.
2745 *
2746 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2747 */
2748 static buf_T *
2749ins_compl_next_buf(buf_T *buf, int flag)
2750{
2751 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01002752 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002753
2754 if (flag == 'w') // just windows
2755 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002756 if (buf == curbuf || !win_valid(wp))
2757 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002758 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01002759
2760 while (TRUE)
2761 {
2762 // Move to next window (wrap to first window if at the end)
2763 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
2764 // Break if we're back at start or found an unscanned buffer
2765 if (wp == curwin || !wp->w_buffer->b_scanned)
2766 break;
2767 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002768 buf = wp->w_buffer;
2769 }
2770 else
glepnir40891ba2025-02-10 22:18:00 +01002771 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002772 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2773 // (unlisted buffers)
2774 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01002775 while (TRUE)
2776 {
2777 // Move to next buffer (wrap to first buffer if at the end)
2778 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
2779 // Break if we're back at start buffer
2780 if (buf == curbuf)
2781 break;
2782
2783 // Check buffer conditions based on flag
2784 if (flag == 'U')
2785 skip_buffer = buf->b_p_bl;
2786 else
2787 skip_buffer = !buf->b_p_bl ||
2788 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
2789
2790 // Break if we found a buffer that matches our criteria
2791 if (!skip_buffer && !buf->b_scanned)
2792 break;
2793 }
2794 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002795 return buf;
2796}
2797
2798#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002799
2800# ifdef FEAT_EVAL
2801static callback_T cfu_cb; // 'completefunc' callback function
2802static callback_T ofu_cb; // 'omnifunc' callback function
2803static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2804# endif
2805
2806/*
2807 * Copy a global callback function to a buffer local callback.
2808 */
2809 static void
2810copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2811{
2812 free_callback(bufcb);
2813 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2814 copy_callback(bufcb, globcb);
2815}
2816
2817/*
2818 * Parse the 'completefunc' option value and set the callback function.
2819 * Invoked when the 'completefunc' option is set. The option value can be a
2820 * name of a function (string), or function(<name>) or funcref(<name>) or a
2821 * lambda expression.
2822 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002823 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002824did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002825{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002826 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2827 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002828
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002829 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002830
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002831 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002832}
2833
2834/*
2835 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002836 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002837 */
2838 void
2839set_buflocal_cfu_callback(buf_T *buf UNUSED)
2840{
2841# ifdef FEAT_EVAL
2842 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2843# endif
2844}
2845
2846/*
2847 * Parse the 'omnifunc' option value and set the callback function.
2848 * Invoked when the 'omnifunc' option is set. The option value can be a
2849 * name of a function (string), or function(<name>) or funcref(<name>) or a
2850 * lambda expression.
2851 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002852 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002853did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002854{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002855 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2856 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002857
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002858 set_buflocal_ofu_callback(curbuf);
2859 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002860}
2861
2862/*
2863 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002864 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002865 */
2866 void
2867set_buflocal_ofu_callback(buf_T *buf UNUSED)
2868{
2869# ifdef FEAT_EVAL
2870 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2871# endif
2872}
2873
2874/*
2875 * Parse the 'thesaurusfunc' option value and set the callback function.
2876 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2877 * name of a function (string), or function(<name>) or funcref(<name>) or a
2878 * lambda expression.
2879 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002880 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002881did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002882{
2883 int retval;
2884
zeertzjq6eda2692024-11-03 09:23:33 +01002885 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002886 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002887 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2888 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002889 else
2890 {
2891 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002892 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01002893 // when using :set, free the local callback
2894 if (!(args->os_flags & OPT_GLOBAL))
2895 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002896 }
2897
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002898 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002899}
2900
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002901/*
2902 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002903 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002904 */
2905 int
2906set_ref_in_insexpand_funcs(int copyID)
2907{
2908 int abort = FALSE;
2909
2910 abort = set_ref_in_callback(&cfu_cb, copyID);
2911 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2912 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2913
2914 return abort;
2915}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002916
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002917/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002918 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002919 */
2920 static char_u *
2921get_complete_funcname(int type)
2922{
2923 switch (type)
2924 {
2925 case CTRL_X_FUNCTION:
2926 return curbuf->b_p_cfu;
2927 case CTRL_X_OMNI:
2928 return curbuf->b_p_ofu;
2929 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002930 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002931 default:
2932 return (char_u *)"";
2933 }
2934}
2935
2936/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002937 * Get the callback to use for insert mode completion.
2938 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002939 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002940get_insert_callback(int type)
2941{
2942 if (type == CTRL_X_FUNCTION)
2943 return &curbuf->b_cfu_cb;
2944 if (type == CTRL_X_OMNI)
2945 return &curbuf->b_ofu_cb;
2946 // CTRL_X_THESAURUS
2947 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2948}
2949
2950/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002951 * Execute user defined complete function 'completefunc', 'omnifunc' or
2952 * 'thesaurusfunc', and get matches in "matches".
2953 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002954 */
2955 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002956expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002957{
2958 list_T *matchlist = NULL;
2959 dict_T *matchdict = NULL;
2960 typval_T args[3];
2961 char_u *funcname;
2962 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002963 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002964 typval_T rettv;
2965 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002966 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002967
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002968 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002969 if (*funcname == NUL)
2970 return;
2971
2972 // Call 'completefunc' to obtain the list of matches.
2973 args[0].v_type = VAR_NUMBER;
2974 args[0].vval.v_number = 0;
2975 args[1].v_type = VAR_STRING;
2976 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2977 args[2].v_type = VAR_UNKNOWN;
2978
2979 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002980 // Lock the text to avoid weird things from happening. Also disallow
2981 // switching to another window, it should not be needed and may end up in
2982 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002983 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002984
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002985 cb = get_insert_callback(type);
2986 retval = call_callback(cb, 0, &rettv, 2, args);
2987
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002988 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002989 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002990 {
2991 switch (rettv.v_type)
2992 {
2993 case VAR_LIST:
2994 matchlist = rettv.vval.v_list;
2995 break;
2996 case VAR_DICT:
2997 matchdict = rettv.vval.v_dict;
2998 break;
2999 case VAR_SPECIAL:
3000 if (rettv.vval.v_number == VVAL_NONE)
3001 compl_opt_suppress_empty = TRUE;
3002 // FALLTHROUGH
3003 default:
3004 // TODO: Give error message?
3005 clear_tv(&rettv);
3006 break;
3007 }
3008 }
zeertzjqcfe45652022-05-27 17:26:55 +01003009 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003010
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003011 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003012 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003013 validate_cursor();
3014 if (!EQUAL_POS(curwin->w_cursor, pos))
3015 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003016 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003017 goto theend;
3018 }
3019
3020 if (matchlist != NULL)
3021 ins_compl_add_list(matchlist);
3022 else if (matchdict != NULL)
3023 ins_compl_add_dict(matchdict);
3024
3025theend:
3026 // Restore State, it might have been changed.
3027 State = save_State;
3028
3029 if (matchdict != NULL)
3030 dict_unref(matchdict);
3031 if (matchlist != NULL)
3032 list_unref(matchlist);
3033}
3034#endif // FEAT_COMPL_FUNC
3035
3036#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003037
3038 static inline int
3039get_user_highlight_attr(char_u *hlname)
3040{
3041 if (hlname != NULL && *hlname != NUL)
3042 return syn_name2attr(hlname);
3043 return -1;
3044}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003045/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003046 * Add a match to the list of matches from a typeval_T.
3047 * If the given string is already in the list of completions, then return
3048 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3049 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003050 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003051 */
3052 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003053ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003054{
3055 char_u *word;
3056 int dup = FALSE;
3057 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003058 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003059 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003060 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003061 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003062 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003063 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003064 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003065
Bram Moolenaar08928322020-01-04 14:32:48 +01003066 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003067 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3068 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003069 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3070 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3071 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3072 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3073 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003074
glepnir0fe17f82024-10-08 22:26:44 +02003075 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003076 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003077
3078 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003079 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003080
Bram Moolenaard61efa52022-07-23 09:52:04 +01003081 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3082 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3083 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003084 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003085 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3086 dup = dict_get_number(tv->vval.v_dict, "dup");
3087 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3088 empty = dict_get_number(tv->vval.v_dict, "empty");
3089 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3090 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003091 flags |= CP_EQUAL;
3092 }
3093 else
3094 {
3095 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003096 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003097 }
3098 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003099 {
3100 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003101 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003102 }
glepnir508e7852024-07-25 21:39:08 +02003103 status = ins_compl_add(word, -1, NULL, cptext,
glepnir80b66202024-11-27 21:53:53 +01003104 &user_data, dir, flags, dup, user_hl);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003105 if (status != OK)
3106 clear_tv(&user_data);
3107 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003108}
3109
3110/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003111 * Add completions from a list.
3112 */
3113 static void
3114ins_compl_add_list(list_T *list)
3115{
3116 listitem_T *li;
3117 int dir = compl_direction;
3118
3119 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003120 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003121 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003122 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003123 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003124 // if dir was BACKWARD then honor it just once
3125 dir = FORWARD;
3126 else if (did_emsg)
3127 break;
3128 }
3129}
3130
3131/*
3132 * Add completions from a dict.
3133 */
3134 static void
3135ins_compl_add_dict(dict_T *dict)
3136{
3137 dictitem_T *di_refresh;
3138 dictitem_T *di_words;
3139
3140 // Check for optional "refresh" item.
3141 compl_opt_refresh_always = FALSE;
3142 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3143 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3144 {
3145 char_u *v = di_refresh->di_tv.vval.v_string;
3146
3147 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3148 compl_opt_refresh_always = TRUE;
3149 }
3150
3151 // Add completions from a "words" list.
3152 di_words = dict_find(dict, (char_u *)"words", 5);
3153 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3154 ins_compl_add_list(di_words->di_tv.vval.v_list);
3155}
3156
3157/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003158 * Start completion for the complete() function.
3159 * "startcol" is where the matched text starts (1 is first column).
3160 * "list" is the list of matches.
3161 */
3162 static void
3163set_completion(colnr_T startcol, list_T *list)
3164{
3165 int save_w_wrow = curwin->w_wrow;
3166 int save_w_leftcol = curwin->w_leftcol;
3167 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003168 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003169 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3170 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3171 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003172
3173 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003174 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003175 ins_compl_prep(' ');
3176 ins_compl_clear();
3177 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003178 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003179
3180 compl_direction = FORWARD;
3181 if (startcol > curwin->w_cursor.col)
3182 startcol = curwin->w_cursor.col;
3183 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003184 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003185 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3186 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003187 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3188 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003189 if (p_ic)
3190 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003191 if (compl_orig_text.string == NULL)
3192 {
3193 compl_orig_text.length = 0;
3194 return;
3195 }
3196 compl_orig_text.length = (size_t)compl_length;
3197 if (ins_compl_add(compl_orig_text.string,
3198 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3199 flags | CP_FAST, FALSE, NULL) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003200 return;
3201
3202 ctrl_x_mode = CTRL_X_EVAL;
3203
3204 ins_compl_add_list(list);
3205 compl_matches = ins_compl_make_cyclic();
3206 compl_started = TRUE;
3207 compl_used_match = TRUE;
3208 compl_cont_status = 0;
3209
3210 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003211 int no_select = compl_no_select || compl_longest;
3212 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003213 {
3214 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003215 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003216 // Down/Up has no real effect.
3217 ins_complete(K_UP, FALSE);
3218 }
3219 else
3220 ins_complete(Ctrl_N, FALSE);
3221 compl_enter_selects = compl_no_insert;
3222
3223 // Lazily show the popup menu, unless we got interrupted.
3224 if (!compl_interrupted)
3225 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003226 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003227 out_flush();
3228}
3229
3230/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003231 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003232 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003233 void
3234f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003235{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003236 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003237
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003238 if (in_vim9script()
3239 && (check_for_number_arg(argvars, 0) == FAIL
3240 || check_for_list_arg(argvars, 1) == FAIL))
3241 return;
3242
Bram Moolenaar24959102022-05-07 20:01:16 +01003243 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003244 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003245 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003246 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003247 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003248
3249 // Check for undo allowed here, because if something was already inserted
3250 // the line was already saved for undo and this check isn't done.
3251 if (!undo_allowed())
3252 return;
3253
Bram Moolenaard83392a2022-09-01 12:22:46 +01003254 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003255 {
3256 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3257 if (startcol > 0)
3258 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003259 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003260}
3261
3262/*
3263 * "complete_add()" function
3264 */
3265 void
3266f_complete_add(typval_T *argvars, typval_T *rettv)
3267{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003268 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003269 return;
3270
Bram Moolenaar440cf092021-04-03 20:13:30 +02003271 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003272}
3273
3274/*
3275 * "complete_check()" function
3276 */
3277 void
3278f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3279{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003280 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003281 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003282
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003283 ins_compl_check_keys(0, TRUE);
3284 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003285
3286 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003287}
3288
3289/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003290 * Return Insert completion mode name string
3291 */
3292 static char_u *
3293ins_compl_mode(void)
3294{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003295 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003296 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3297
3298 return (char_u *)"";
3299}
3300
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003301/*
3302 * Assign the sequence number to all the completion matches which don't have
3303 * one assigned yet.
3304 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003305 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003306ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003307{
3308 int number = 0;
3309 compl_T *match;
3310
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003311 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003312 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003313 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003314 // This should normally succeed already at the first loop
3315 // cycle, so it's fast!
3316 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003317 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003318 if (match->cp_number != -1)
3319 {
3320 number = match->cp_number;
3321 break;
3322 }
3323 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003324 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003325 for (match = match->cp_next;
3326 match != NULL && match->cp_number == -1;
3327 match = match->cp_next)
3328 match->cp_number = ++number;
3329 }
3330 else // BACKWARD
3331 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003332 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003333 // number. This should normally succeed already at the
3334 // first loop cycle, so it's fast!
3335 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003336 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003337 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003338 if (match->cp_number != -1)
3339 {
3340 number = match->cp_number;
3341 break;
3342 }
glepnir40891ba2025-02-10 22:18:00 +01003343 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003344 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003345 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003346 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003347 for (match = match->cp_prev; match
3348 && match->cp_number == -1;
3349 match = match->cp_prev)
3350 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003351 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003352 }
3353}
3354
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003355/*
glepnir037b0282025-01-16 14:37:44 +01003356 * Fill the dict of complete_info
3357 */
3358 static void
3359fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3360{
3361 dict_add_string(di, "word", match->cp_str.string);
3362 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3363 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3364 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3365 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3366 if (add_match)
3367 dict_add_bool(di, "match", match->cp_in_match_array);
3368 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3369 // Add an empty string for backwards compatibility
3370 dict_add_string(di, "user_data", (char_u *)"");
3371 else
3372 dict_add_tv(di, "user_data", &match->cp_user_data);
3373}
3374
3375/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003376 * Get complete information
3377 */
3378 static void
3379get_complete_info(list_T *what_list, dict_T *retdict)
3380{
3381 int ret = OK;
3382 listitem_T *item;
3383#define CI_WHAT_MODE 0x01
3384#define CI_WHAT_PUM_VISIBLE 0x02
3385#define CI_WHAT_ITEMS 0x04
3386#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003387#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003388#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003389#define CI_WHAT_ALL 0xff
3390 int what_flag;
3391
3392 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003393 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003394 else
3395 {
3396 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003397 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003398 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003399 {
3400 char_u *what = tv_get_string(&item->li_tv);
3401
3402 if (STRCMP(what, "mode") == 0)
3403 what_flag |= CI_WHAT_MODE;
3404 else if (STRCMP(what, "pum_visible") == 0)
3405 what_flag |= CI_WHAT_PUM_VISIBLE;
3406 else if (STRCMP(what, "items") == 0)
3407 what_flag |= CI_WHAT_ITEMS;
3408 else if (STRCMP(what, "selected") == 0)
3409 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003410 else if (STRCMP(what, "completed") == 0)
3411 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003412 else if (STRCMP(what, "matches") == 0)
3413 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003414 }
3415 }
3416
3417 if (ret == OK && (what_flag & CI_WHAT_MODE))
3418 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3419
3420 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3421 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3422
glepnir037b0282025-01-16 14:37:44 +01003423 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3424 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003425 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003426 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003427 dict_T *di;
3428 compl_T *match;
3429 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003430 int has_items = what_flag & CI_WHAT_ITEMS;
3431 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003432 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003433
glepnird4088ed2024-12-31 10:55:22 +01003434 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003435 {
3436 li = list_alloc();
3437 if (li == NULL)
3438 return;
glepnird4088ed2024-12-31 10:55:22 +01003439 ret = dict_add_list(retdict, (has_matches && !has_items)
3440 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003441 }
3442 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3443 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3444 ins_compl_update_sequence_numbers();
3445 if (ret == OK && compl_first_match != NULL)
3446 {
3447 int list_idx = 0;
3448 match = compl_first_match;
3449 do
3450 {
3451 if (!match_at_original_text(match))
3452 {
glepnird4088ed2024-12-31 10:55:22 +01003453 if (has_items
3454 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003455 {
3456 di = dict_alloc();
3457 if (di == NULL)
3458 return;
3459 ret = list_append_dict(li, di);
3460 if (ret != OK)
3461 return;
glepnir037b0282025-01-16 14:37:44 +01003462 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003463 }
glepnird4088ed2024-12-31 10:55:22 +01003464 if (compl_curr_match != NULL
3465 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003466 selected_idx = list_idx;
3467 list_idx += 1;
3468 }
3469 match = match->cp_next;
3470 }
3471 while (match != NULL && !is_first_match(match));
3472 }
3473 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3474 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003475
glepnir037b0282025-01-16 14:37:44 +01003476 if (ret == OK && selected_idx != -1 && has_completed)
3477 {
3478 di = dict_alloc();
3479 if (di == NULL)
3480 return;
3481 fill_complete_info_dict(di, compl_curr_match, FALSE);
3482 ret = dict_add_dict(retdict, "completed", di);
3483 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003484 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003485}
3486
3487/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003488 * "complete_info()" function
3489 */
3490 void
3491f_complete_info(typval_T *argvars, typval_T *rettv)
3492{
3493 list_T *what_list = NULL;
3494
Bram Moolenaar93a10962022-06-16 11:42:09 +01003495 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003496 return;
3497
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003498 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3499 return;
3500
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003501 if (argvars[0].v_type != VAR_UNKNOWN)
3502 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003503 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003504 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003505 what_list = argvars[0].vval.v_list;
3506 }
3507 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003508}
3509#endif
3510
3511/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003512 * Returns TRUE when using a user-defined function for thesaurus completion.
3513 */
3514 static int
3515thesaurus_func_complete(int type UNUSED)
3516{
3517#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003518 return type == CTRL_X_THESAURUS
3519 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003520#else
3521 return FALSE;
3522#endif
3523}
3524
3525/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003526 * Return value of process_next_cpt_value()
3527 */
3528enum
3529{
3530 INS_COMPL_CPT_OK = 1,
3531 INS_COMPL_CPT_CONT,
3532 INS_COMPL_CPT_END
3533};
3534
3535/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003536 * state information used for getting the next set of insert completion
3537 * matches.
3538 */
3539typedef struct
3540{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003541 char_u *e_cpt_copy; // copy of 'complete'
3542 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003543 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003544 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003545 pos_T prev_match_pos; // previous match position
3546 int set_match_pos; // save first_match_pos/last_match_pos
3547 pos_T first_match_pos; // first match position
3548 pos_T last_match_pos; // last match position
3549 int found_all; // found all matches of a certain type.
3550 char_u *dict; // dictionary file to search
3551 int dict_f; // "dict" is an exact file name or not
3552} ins_compl_next_state_T;
3553
3554/*
3555 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003556 *
3557 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003558 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003559 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003560 * st->found_all - all matches of this type are found
3561 * st->ins_buf - search for completions in this buffer
3562 * st->first_match_pos - position of the first completion match
3563 * st->last_match_pos - position of the last completion match
3564 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003565 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003566 * st->dict - name of the dictionary or thesaurus file to search
3567 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003568 *
3569 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003570 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3571 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003572 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003573 */
3574 static int
3575process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003576 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003577 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003578 pos_T *start_match_pos,
3579 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003580{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003581 int compl_type = -1;
3582 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003583
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003584 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003585
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003586 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3587 st->e_cpt++;
3588
3589 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003590 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003591 st->ins_buf = curbuf;
3592 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003593 // Move the cursor back one character so that ^N can match the
3594 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003595 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003596 {
3597 // Move the cursor to after the last character in the
3598 // buffer, so that word at start of buffer is found
3599 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003600 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003601 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003602 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003603 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003604 compl_type = 0;
3605
3606 // Remember the first match so that the loop stops when we
3607 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003608 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003609 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003610 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003611 && (st->ins_buf = ins_compl_next_buf(
3612 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003613 {
3614 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003615 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003616 {
3617 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003618 st->first_match_pos.col = st->last_match_pos.col = 0;
3619 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3620 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003621 compl_type = 0;
3622 }
3623 else // unloaded buffer, scan like dictionary
3624 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003625 st->found_all = TRUE;
3626 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003627 {
3628 status = INS_COMPL_CPT_CONT;
3629 goto done;
3630 }
3631 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003632 st->dict = st->ins_buf->b_fname;
3633 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003634 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003635 if (!shortmess(SHM_COMPLETIONSCAN))
3636 {
3637 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3638 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3639 st->ins_buf->b_fname == NULL
3640 ? buf_spname(st->ins_buf)
3641 : st->ins_buf->b_sfname == NULL
3642 ? st->ins_buf->b_fname
3643 : st->ins_buf->b_sfname);
3644 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3645 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003646 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003647 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003648 status = INS_COMPL_CPT_END;
3649 else
3650 {
3651 if (ctrl_x_mode_line_or_eval())
3652 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003653 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003654 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003655 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003656 compl_type = CTRL_X_DICTIONARY;
3657 else
3658 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003659 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003660 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003661 st->dict = st->e_cpt;
3662 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003663 }
3664 }
3665#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003666 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003667 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003668 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003669 compl_type = CTRL_X_PATH_DEFINES;
3670#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003671 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003672 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003673 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003674 if (!shortmess(SHM_COMPLETIONSCAN))
3675 {
3676 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3677 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3678 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3679 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003680 }
3681 else
3682 compl_type = -1;
3683
3684 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003685 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003686
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003687 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003688 if (compl_type == -1)
3689 status = INS_COMPL_CPT_CONT;
3690 }
3691
3692done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003693 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003694 return status;
3695}
3696
3697#ifdef FEAT_FIND_ID
3698/*
3699 * Get the next set of identifiers or defines matching "compl_pattern" in
3700 * included files.
3701 */
3702 static void
3703get_next_include_file_completion(int compl_type)
3704{
John Marriott5e6ea922024-11-23 14:01:57 +01003705 find_pattern_in_path(compl_pattern.string, compl_direction,
3706 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003707 (compl_type == CTRL_X_PATH_DEFINES
3708 && !(compl_cont_status & CONT_SOL))
3709 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003710 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003711}
3712#endif
3713
3714/*
3715 * Get the next set of words matching "compl_pattern" in dictionary or
3716 * thesaurus files.
3717 */
3718 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003719get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003720{
3721#ifdef FEAT_COMPL_FUNC
3722 if (thesaurus_func_complete(compl_type))
John Marriott5e6ea922024-11-23 14:01:57 +01003723 expand_by_function(compl_type, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003724 else
3725#endif
3726 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003727 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003728 : (compl_type == CTRL_X_THESAURUS
3729 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3730 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003731 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003732 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003733 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003734}
3735
3736/*
3737 * Get the next set of tag names matching "compl_pattern".
3738 */
3739 static void
3740get_next_tag_completion(void)
3741{
3742 int save_p_ic;
3743 char_u **matches;
3744 int num_matches;
3745
3746 // set p_ic according to p_ic, p_scs and pat for find_tags().
3747 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003748 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003749
3750 // Find up to TAG_MANY matches. Avoids that an enormous number
3751 // of matches is found when compl_pattern is empty
3752 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003753 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003754 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003755 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003756 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3757 ins_compl_add_matches(num_matches, matches, p_ic);
3758 g_tag_at_cursor = FALSE;
3759 p_ic = save_p_ic;
3760}
3761
3762/*
glepnir8159fb12024-07-17 20:32:54 +02003763 * Compare function for qsort
3764 */
3765static int compare_scores(const void *a, const void *b)
3766{
3767 int idx_a = *(const int *)a;
3768 int idx_b = *(const int *)b;
3769 int score_a = compl_fuzzy_scores[idx_a];
3770 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003771 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3772 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003773}
3774
3775/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003776 * Get the next set of filename matching "compl_pattern".
3777 */
3778 static void
3779get_next_filename_completion(void)
3780{
3781 char_u **matches;
3782 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003783 char_u *ptr;
3784 garray_T fuzzy_indices;
3785 int i;
3786 int score;
3787 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01003788 size_t leader_len = ins_compl_leader_len();;
glepnir8159fb12024-07-17 20:32:54 +02003789 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3790 char_u **sorted_matches;
3791 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003792 char_u *last_sep = NULL;
glepnir8159fb12024-07-17 20:32:54 +02003793
glepnirb9de1a02024-08-02 19:14:38 +02003794#ifdef BACKSLASH_IN_FILENAME
3795 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3796 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3797#else
3798 char pathsep = PATHSEP;
3799#endif
3800
glepnir8159fb12024-07-17 20:32:54 +02003801 if (in_fuzzy)
3802 {
glepnirb9de1a02024-08-02 19:14:38 +02003803#ifdef BACKSLASH_IN_FILENAME
3804 if (curbuf->b_p_csl[0] == 's')
3805 {
John Marriott5e6ea922024-11-23 14:01:57 +01003806 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003807 {
3808 if (leader[i] == '\\')
3809 leader[i] = '/';
3810 }
3811 }
3812 else if (curbuf->b_p_csl[0] == 'b')
3813 {
John Marriott5e6ea922024-11-23 14:01:57 +01003814 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02003815 {
3816 if (leader[i] == '/')
3817 leader[i] = '\\';
3818 }
3819 }
3820#endif
3821 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003822 if (last_sep == NULL)
3823 {
3824 // No path separator or separator is the last character,
3825 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01003826 VIM_CLEAR_STRING(compl_pattern);
3827 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
3828 if (compl_pattern.string == NULL)
3829 return;
3830 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02003831 }
3832 else if (*(last_sep + 1) == '\0')
3833 in_fuzzy = FALSE;
3834 else
3835 {
3836 // Split leader into path and file parts
3837 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003838 char_u *path_with_wildcard;
3839
3840 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02003841 if (path_with_wildcard != NULL)
3842 {
John Marriott5e6ea922024-11-23 14:01:57 +01003843 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
3844 VIM_CLEAR_STRING(compl_pattern);
3845 compl_pattern.string = path_with_wildcard;
3846 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02003847
3848 // Move leader to the file part
3849 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01003850 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02003851 }
3852 }
glepnir8159fb12024-07-17 20:32:54 +02003853 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003854
John Marriott5e6ea922024-11-23 14:01:57 +01003855 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003856 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3857 return;
3858
3859 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01003860 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003861#ifdef BACKSLASH_IN_FILENAME
3862 if (curbuf->b_p_csl[0] != NUL)
3863 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003864 for (i = 0; i < num_matches; ++i)
3865 {
glepnir8159fb12024-07-17 20:32:54 +02003866 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003867 while (*ptr != NUL)
3868 {
3869 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3870 *ptr = '/';
3871 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3872 *ptr = '\\';
3873 ptr += (*mb_ptr2len)(ptr);
3874 }
3875 }
3876 }
3877#endif
glepnir8159fb12024-07-17 20:32:54 +02003878
3879 if (in_fuzzy)
3880 {
3881 ga_init2(&fuzzy_indices, sizeof(int), 10);
3882 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3883
3884 for (i = 0; i < num_matches; i++)
3885 {
3886 ptr = matches[i];
3887 score = fuzzy_match_str(ptr, leader);
3888 if (score > 0)
3889 {
3890 if (ga_grow(&fuzzy_indices, 1) == OK)
3891 {
3892 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3893 compl_fuzzy_scores[i] = score;
3894 fuzzy_indices.ga_len++;
3895 }
3896 }
3897 }
3898
Christian Brabandt220474d2024-07-20 13:26:44 +02003899 // prevent qsort from deref NULL pointer
3900 if (fuzzy_indices.ga_len > 0)
3901 {
3902 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3903 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003904
Christian Brabandt220474d2024-07-20 13:26:44 +02003905 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3906 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3907 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003908
Christian Brabandt220474d2024-07-20 13:26:44 +02003909 FreeWild(num_matches, matches);
3910 matches = sorted_matches;
3911 num_matches = fuzzy_indices.ga_len;
3912 }
glepnir6b6280c2024-07-27 16:25:45 +02003913 else if (leader_len > 0)
3914 {
3915 FreeWild(num_matches, matches);
3916 num_matches = 0;
3917 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003918
glepnir8159fb12024-07-17 20:32:54 +02003919 vim_free(compl_fuzzy_scores);
3920 ga_clear(&fuzzy_indices);
3921 }
3922
glepnir6b6280c2024-07-27 16:25:45 +02003923 if (num_matches > 0)
3924 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003925}
3926
3927/*
3928 * Get the next set of command-line completions matching "compl_pattern".
3929 */
3930 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003931get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003932{
3933 char_u **matches;
3934 int num_matches;
3935
John Marriott5e6ea922024-11-23 14:01:57 +01003936 if (expand_cmdline(&compl_xp, compl_pattern.string,
3937 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003938 ins_compl_add_matches(num_matches, matches, FALSE);
3939}
3940
3941/*
3942 * Get the next set of spell suggestions matching "compl_pattern".
3943 */
3944 static void
3945get_next_spell_completion(linenr_T lnum UNUSED)
3946{
3947#ifdef FEAT_SPELL
3948 char_u **matches;
3949 int num_matches;
3950
John Marriott5e6ea922024-11-23 14:01:57 +01003951 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003952 if (num_matches > 0)
3953 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003954 else
3955 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003956#endif
3957}
3958
3959/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003960 * Return the next word or line from buffer "ins_buf" at position
3961 * "cur_match_pos" for completion. The length of the match is set in "len".
3962 */
3963 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003964ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003965 buf_T *ins_buf, // buffer being scanned
3966 pos_T *cur_match_pos, // current match position
3967 int *match_len,
3968 int *cont_s_ipos) // next ^X<> will set initial_pos
3969{
3970 char_u *ptr;
3971 int len;
3972
3973 *match_len = 0;
3974 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3975 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01003976 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003977 if (ctrl_x_mode_line_or_eval())
3978 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003979 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003980 {
3981 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3982 return NULL;
3983 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01003984 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003985 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01003986 {
3987 char_u *tmp_ptr = ptr;
3988
3989 ptr = skipwhite(tmp_ptr);
3990 len -= (int)(ptr - tmp_ptr);
3991 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003992 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003993 }
3994 else
3995 {
3996 char_u *tmp_ptr = ptr;
3997
John Marriott5e6ea922024-11-23 14:01:57 +01003998 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003999 {
4000 tmp_ptr += compl_length;
4001 // Skip if already inside a word.
4002 if (vim_iswordp(tmp_ptr))
4003 return NULL;
4004 // Find start of next word.
4005 tmp_ptr = find_word_start(tmp_ptr);
4006 }
4007 // Find end of this word.
4008 tmp_ptr = find_word_end(tmp_ptr);
4009 len = (int)(tmp_ptr - ptr);
4010
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004011 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004012 {
4013 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4014 {
4015 // Try next line, if any. the new word will be
4016 // "join" as if the normal command "J" was used.
4017 // IOSIZE is always greater than
4018 // compl_length, so the next STRNCPY always
4019 // works -- Acevedo
4020 STRNCPY(IObuff, ptr, len);
4021 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4022 tmp_ptr = ptr = skipwhite(ptr);
4023 // Find start of next word.
4024 tmp_ptr = find_word_start(tmp_ptr);
4025 // Find end of next word.
4026 tmp_ptr = find_word_end(tmp_ptr);
4027 if (tmp_ptr > ptr)
4028 {
4029 if (*ptr != ')' && IObuff[len - 1] != TAB)
4030 {
4031 if (IObuff[len - 1] != ' ')
4032 IObuff[len++] = ' ';
4033 // IObuf =~ "\k.* ", thus len >= 2
4034 if (p_js
4035 && (IObuff[len - 2] == '.'
4036 || (vim_strchr(p_cpo, CPO_JOINSP)
4037 == NULL
4038 && (IObuff[len - 2] == '?'
4039 || IObuff[len - 2] == '!'))))
4040 IObuff[len++] = ' ';
4041 }
4042 // copy as much as possible of the new word
4043 if (tmp_ptr - ptr >= IOSIZE - len)
4044 tmp_ptr = ptr + IOSIZE - len - 1;
4045 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4046 len += (int)(tmp_ptr - ptr);
4047 *cont_s_ipos = TRUE;
4048 }
4049 IObuff[len] = NUL;
4050 ptr = IObuff;
4051 }
4052 if (len == compl_length)
4053 return NULL;
4054 }
4055 }
4056
4057 *match_len = len;
4058 return ptr;
4059}
4060
4061/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004062 * Get the next set of words matching "compl_pattern" for default completion(s)
4063 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004064 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4065 * position "st->start_pos" in the "compl_direction" direction. If
4066 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4067 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004068 * Returns OK if a new next match is found, otherwise returns FAIL.
4069 */
4070 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004072{
4073 int found_new_match = FAIL;
4074 int save_p_scs;
4075 int save_p_ws;
4076 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004077 char_u *ptr = NULL;
4078 int len = 0;
4079 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
4080 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004081
4082 // If 'infercase' is set, don't use 'smartcase' here
4083 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004084 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004085 p_scs = FALSE;
4086
4087 // Buffers other than curbuf are scanned from the beginning or the
4088 // end but never from the middle, thus setting nowrapscan in this
4089 // buffer is a good idea, on the other hand, we always set
4090 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4091 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004092 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004093 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004094 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004095 p_ws = TRUE;
4096 looped_around = FALSE;
4097 for (;;)
4098 {
4099 int cont_s_ipos = FALSE;
4100
4101 ++msg_silent; // Don't want messages for wrapscan.
4102
4103 // ctrl_x_mode_line_or_eval() || word-wise search that
4104 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02004105 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004106 found_new_match = search_for_exact_line(st->ins_buf,
John Marriott5e6ea922024-11-23 14:01:57 +01004107 st->cur_match_pos, compl_direction, compl_pattern.string);
glepnir8159fb12024-07-17 20:32:54 +02004108 else if (in_fuzzy)
4109 found_new_match = search_for_fuzzy_match(st->ins_buf,
4110 st->cur_match_pos, leader, compl_direction,
4111 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004112 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004113 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004114 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004115 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004116 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004117 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004118 {
4119 // set "compl_started" even on fail
4120 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004121 st->first_match_pos = *st->cur_match_pos;
4122 st->last_match_pos = *st->cur_match_pos;
4123 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004125 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4126 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004127 {
4128 found_new_match = FAIL;
4129 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004130 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004131 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4132 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4133 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004134 {
4135 if (looped_around)
4136 found_new_match = FAIL;
4137 else
4138 looped_around = TRUE;
4139 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004140 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004141 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4142 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4143 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004144 {
4145 if (looped_around)
4146 found_new_match = FAIL;
4147 else
4148 looped_around = TRUE;
4149 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004150 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004151 if (found_new_match == FAIL)
4152 break;
4153
4154 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004155 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004156 && start_pos->lnum == st->cur_match_pos->lnum
4157 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004158 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004159
glepnir8159fb12024-07-17 20:32:54 +02004160 if (!in_fuzzy)
4161 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4162 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004163 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004164 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004165
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004166 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004167 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004168 0, cont_s_ipos) != NOTDONE)
4169 {
4170 found_new_match = OK;
4171 break;
4172 }
4173 }
4174 p_scs = save_p_scs;
4175 p_ws = save_p_ws;
4176
4177 return found_new_match;
4178}
4179
4180/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004181 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004182 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004183 */
4184 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004185get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004186{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004187 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004188
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004189 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004190 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004191 case -1:
4192 break;
4193#ifdef FEAT_FIND_ID
4194 case CTRL_X_PATH_PATTERNS:
4195 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004196 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004197 break;
4198#endif
4199
4200 case CTRL_X_DICTIONARY:
4201 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004202 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4203 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004204 break;
4205
4206 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004207 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004208 break;
4209
4210 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004211 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004212 break;
4213
4214 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004215 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004216 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004217 break;
4218
4219#ifdef FEAT_COMPL_FUNC
4220 case CTRL_X_FUNCTION:
4221 case CTRL_X_OMNI:
John Marriott5e6ea922024-11-23 14:01:57 +01004222 expand_by_function(type, compl_pattern.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004223 break;
4224#endif
4225
4226 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004227 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004228 break;
4229
4230 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004231 found_new_match = get_next_default_completion(st, ini);
4232 if (found_new_match == FAIL && st->ins_buf == curbuf)
4233 st->found_all = TRUE;
4234 }
4235
4236 // check if compl_curr_match has changed, (e.g. other type of
4237 // expansion added something)
4238 if (type != 0 && compl_curr_match != compl_old_match)
4239 found_new_match = OK;
4240
4241 return found_new_match;
4242}
4243
4244/*
4245 * Get the next expansion(s), using "compl_pattern".
4246 * The search starts at position "ini" in curbuf and in the direction
4247 * compl_direction.
4248 * When "compl_started" is FALSE start at that position, otherwise continue
4249 * where we stopped searching before.
4250 * This may return before finding all the matches.
4251 * Return the total number of matches or -1 if still unknown -- Acevedo
4252 */
4253 static int
4254ins_compl_get_exp(pos_T *ini)
4255{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004256 static ins_compl_next_state_T st;
4257 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004258 int i;
4259 int found_new_match;
4260 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004261 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004262
4263 if (!compl_started)
4264 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004265 buf_T *buf;
4266
4267 FOR_ALL_BUFFERS(buf)
4268 buf->b_scanned = 0;
4269 if (!st_cleared)
4270 {
4271 CLEAR_FIELD(st);
4272 st_cleared = TRUE;
4273 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004274 st.found_all = FALSE;
4275 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004276 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004277 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004278 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4279 ? (char_u *)"." : curbuf->b_p_cpt);
4280 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004281 st.last_match_pos = st.first_match_pos = *ini;
4282 }
4283 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4284 st.ins_buf = curbuf; // In case the buffer was wiped out.
4285
4286 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004287 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004288 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004289
4290 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4291 for (;;)
4292 {
4293 found_new_match = FAIL;
4294 st.set_match_pos = FALSE;
4295
4296 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4297 // or if found_all says this entry is done. For ^X^L only use the
4298 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004299 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004300 && (!compl_started || st.found_all))
4301 {
glepnir8159fb12024-07-17 20:32:54 +02004302 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004303
4304 if (status == INS_COMPL_CPT_END)
4305 break;
4306 if (status == INS_COMPL_CPT_CONT)
4307 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004308 }
4309
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004310 // If complete() was called then compl_pattern has been reset. The
4311 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004312 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004313 break;
4314
4315 // get the next set of completion matches
4316 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004317
4318 // break the loop for specialized modes (use 'complete' just for the
4319 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4320 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004321 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4322 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004323 {
4324 if (got_int)
4325 break;
4326 // Fill the popup menu as soon as possible.
4327 if (type != -1)
4328 ins_compl_check_keys(0, FALSE);
4329
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004330 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004331 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4332 break;
4333 compl_started = TRUE;
4334 }
4335 else
4336 {
4337 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004338 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004339 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004340
4341 compl_started = FALSE;
4342 }
4343 }
4344 compl_started = TRUE;
4345
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004346 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004347 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004348 found_new_match = FAIL;
4349
4350 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004351 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004352 && !ctrl_x_mode_line_or_eval()))
4353 i = ins_compl_make_cyclic();
4354
4355 if (compl_old_match != NULL)
4356 {
4357 // If several matches were added (FORWARD) or the search failed and has
4358 // just been made cyclic then we have to move compl_curr_match to the
4359 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004360 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004361 : compl_old_match->cp_prev;
4362 if (compl_curr_match == NULL)
4363 compl_curr_match = compl_old_match;
4364 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004365 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004366
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004367 return i;
4368}
4369
4370/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004371 * Update "compl_shown_match" to the actually shown match, it may differ when
4372 * "compl_leader" is used to omit some of the matches.
4373 */
4374 static void
4375ins_compl_update_shown_match(void)
4376{
4377 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004378 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004379 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004380 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004381 compl_shown_match = compl_shown_match->cp_next;
4382
4383 // If we didn't find it searching forward, and compl_shows_dir is
4384 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004385 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004386 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004387 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004388 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004389 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004390 {
4391 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004392 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004393 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004394 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004395 compl_shown_match = compl_shown_match->cp_prev;
4396 }
4397}
4398
4399/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004400 * Delete the old text being completed.
4401 */
4402 void
4403ins_compl_delete(void)
4404{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004405 // In insert mode: Delete the typed part.
4406 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004407 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01004408 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01004409 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004410 int has_preinsert = ins_compl_preinsert_effect();
4411 if (has_preinsert)
4412 {
glepnirbfb4eea2025-01-31 15:28:29 +01004413 col += ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004414 curwin->w_cursor.col = compl_ins_end_col;
4415 }
4416
glepnir76bdb822025-02-08 19:04:51 +01004417 if (curwin->w_cursor.lnum > compl_lnum)
4418 {
4419 if (curwin->w_cursor.col < ml_get_curline_len())
4420 {
John Marriottf4b36412025-02-23 09:09:59 +01004421 char_u *line = ml_get_cursor();
4422 remaining.length = ml_get_cursor_len();
4423 remaining.string = vim_strnsave(line, remaining.length);
4424 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01004425 return;
4426 }
4427 while (curwin->w_cursor.lnum > compl_lnum)
4428 {
4429 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4430 {
John Marriottf4b36412025-02-23 09:09:59 +01004431 if (remaining.string)
4432 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004433 return;
4434 }
zeertzjq060e6552025-02-21 20:06:26 +01004435 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01004436 curwin->w_cursor.lnum--;
4437 }
4438 // move cursor to end of line
4439 curwin->w_cursor.col = ml_get_curline_len();
4440 }
4441
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004442 if ((int)curwin->w_cursor.col > col)
4443 {
4444 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004445 {
John Marriottf4b36412025-02-23 09:09:59 +01004446 if (remaining.string)
4447 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004448 return;
glepnire3647c82025-02-10 21:16:32 +01004449 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004450 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004451 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004452 }
4453
John Marriottf4b36412025-02-23 09:09:59 +01004454 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01004455 {
4456 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01004457 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01004458 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01004459 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004460 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004461 // TODO: is this sufficient for redrawing? Redrawing everything causes
4462 // flicker, thus we can't do that.
4463 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004464#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004465 // clear v:completed_item
4466 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004467#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004468}
4469
4470/*
glepnir76bdb822025-02-08 19:04:51 +01004471 * Insert a completion string that contains newlines.
4472 * The string is split and inserted line by line.
4473 */
4474 static void
4475ins_compl_expand_multiple(char_u *str)
4476{
4477 char_u *start = str;
4478 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01004479 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01004480
4481 while (*curr != NUL)
4482 {
4483 if (*curr == '\n')
4484 {
4485 // Insert the text chunk before newline
4486 if (curr > start)
4487 ins_char_bytes(start, (int)(curr - start));
4488
4489 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01004490 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01004491 start = curr + 1;
4492 }
4493 curr++;
4494 }
4495
4496 // Handle remaining text after last newline (if any)
4497 if (curr > start)
4498 ins_char_bytes(start, (int)(curr - start));
4499
4500 compl_ins_end_col = curwin->w_cursor.col;
4501}
4502
4503/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004504 * Insert the new text being completed.
4505 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004506 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4507 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004508 */
4509 void
glepniredd4ac32025-01-29 18:53:51 +01004510ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004511{
glepnir76bdb822025-02-08 19:04:51 +01004512 int compl_len = get_compl_len();
4513 int preinsert = ins_compl_has_preinsert();
4514 char_u *cp_str = compl_shown_match->cp_str.string;
4515 size_t cp_str_len = compl_shown_match->cp_str.length;
4516 size_t leader_len = ins_compl_leader_len();
4517 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004518
4519 // Make sure we don't go over the end of the string, this can happen with
4520 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004521 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004522 {
glepnir76bdb822025-02-08 19:04:51 +01004523 if (has_multiple)
4524 ins_compl_expand_multiple(cp_str + compl_len);
4525 else
4526 {
4527 ins_compl_insert_bytes(cp_str + compl_len, -1);
4528 if (preinsert && move_cursor)
4529 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4530 }
glepniredd4ac32025-01-29 18:53:51 +01004531 }
4532 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004533 compl_used_match = FALSE;
4534 else
4535 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004536#ifdef FEAT_EVAL
4537 {
4538 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4539
4540 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4541 }
4542#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004543 if (!in_compl_func)
4544 compl_curr_match = compl_shown_match;
4545}
4546
4547/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004548 * show the file name for the completion match (if any). Truncate the file
4549 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004550 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004551 static void
4552ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004553{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004554 char *lead = _("match in file");
4555 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4556 char_u *s;
4557 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004558
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004559 if (space <= 0)
4560 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004561
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004562 // We need the tail that fits. With double-byte encoding going
4563 // back from the end is very slow, thus go from the start and keep
4564 // the text that fits in "space" between "s" and "e".
4565 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004566 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004567 space -= ptr2cells(e);
4568 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004569 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004570 space += ptr2cells(s);
4571 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004572 }
4573 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004574 msg_hist_off = TRUE;
4575 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4576 s > compl_shown_match->cp_fname ? "<" : "", s);
4577 msg((char *)IObuff);
4578 msg_hist_off = FALSE;
4579 redraw_cmdline = FALSE; // don't overwrite!
4580}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004581
glepnirdca57fb2024-06-04 22:01:21 +02004582/*
zeertzjq551d8c32024-06-05 19:53:32 +02004583 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004584 */
glepnira218cc62024-06-03 19:32:39 +02004585 static compl_T *
4586find_comp_when_fuzzy(void)
4587{
4588 int score;
4589 char_u* str;
4590 int target_idx = -1;
4591 int is_forward = compl_shows_dir_forward();
4592 int is_backward = compl_shows_dir_backward();
4593 compl_T *comp = NULL;
4594
glepnir43eef882024-06-19 20:20:48 +02004595 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004596 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004597 return compl_first_match != compl_shown_match ? compl_first_match :
4598 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004599
4600 if (is_forward)
4601 target_idx = compl_selected_item + 1;
4602 else if (is_backward)
4603 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004604 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004605
4606 score = compl_match_array[target_idx].pum_score;
4607 str = compl_match_array[target_idx].pum_text;
4608
4609 comp = compl_first_match;
4610 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004611 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004612 return comp;
4613 comp = comp->cp_next;
4614 } while (comp != NULL && !is_first_match(comp));
4615
4616 return NULL;
4617}
4618
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004619/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004620 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004621 * times. The number of matches found is returned in 'num_matches'.
4622 *
4623 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4624 * get more completions. If it is FALSE, then do nothing when there are no more
4625 * completions in the given direction.
4626 *
4627 * If "advance" is TRUE, then completion will move to the first match.
4628 * Otherwise, the original text will be shown.
4629 *
4630 * Returns OK on success and -1 if the number of matches are unknown.
4631 */
4632 static int
4633find_next_completion_match(
4634 int allow_get_expansion,
4635 int todo, // repeat completion this many times
4636 int advance,
4637 int *num_matches)
4638{
4639 int found_end = FALSE;
4640 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004641 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004642 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4643 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004644
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004645 while (--todo >= 0)
4646 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004647 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004648 {
glepniraced8c22024-06-15 15:13:05 +02004649 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4650 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004651 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004652 && (is_first_match(compl_shown_match->cp_next)
4653 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004654 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004655 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004656 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004657 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004658 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004659 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4660 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004661 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004662 }
4663 else
4664 {
4665 if (!allow_get_expansion)
4666 {
4667 if (advance)
4668 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004669 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004670 compl_pending -= todo + 1;
4671 else
4672 compl_pending += todo + 1;
4673 }
4674 return -1;
4675 }
4676
4677 if (!compl_no_select && advance)
4678 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004679 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004680 --compl_pending;
4681 else
4682 ++compl_pending;
4683 }
4684
4685 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004686 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004687
4688 // handle any pending completions
4689 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004690 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004691 {
4692 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4693 {
4694 compl_shown_match = compl_shown_match->cp_next;
4695 --compl_pending;
4696 }
4697 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4698 {
4699 compl_shown_match = compl_shown_match->cp_prev;
4700 ++compl_pending;
4701 }
4702 else
4703 break;
4704 }
4705 found_end = FALSE;
4706 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004707 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01004708 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004709 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004710 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02004711 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004712 ++todo;
4713 else
4714 // Remember a matching item.
4715 found_compl = compl_shown_match;
4716
4717 // Stop at the end of the list when we found a usable match.
4718 if (found_end)
4719 {
4720 if (found_compl != NULL)
4721 {
4722 compl_shown_match = found_compl;
4723 break;
4724 }
4725 todo = 1; // use first usable match after wrapping around
4726 }
4727 }
4728
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004729 return OK;
4730}
4731
4732/*
4733 * Fill in the next completion in the current direction.
4734 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4735 * get more completions. If it is FALSE, then we just do nothing when there
4736 * are no more completions in a given direction. The latter case is used when
4737 * we are still in the middle of finding completions, to allow browsing
4738 * through the ones found so far.
4739 * Return the total number of matches, or -1 if still unknown -- webb.
4740 *
4741 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4742 * compl_shown_match here.
4743 *
4744 * Note that this function may be called recursively once only. First with
4745 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4746 * calls this function with "allow_get_expansion" FALSE.
4747 */
4748 static int
4749ins_compl_next(
4750 int allow_get_expansion,
4751 int count, // repeat completion this many times; should
4752 // be at least 1
4753 int insert_match, // Insert the newly selected match
4754 int in_compl_func) // called from complete_check()
4755{
4756 int num_matches = -1;
4757 int todo = count;
4758 int advance;
4759 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004760 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004761 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004762 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4763 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01004764 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004765
4766 // When user complete function return -1 for findstart which is next
4767 // time of 'always', compl_shown_match become NULL.
4768 if (compl_shown_match == NULL)
4769 return -1;
4770
John Marriott5e6ea922024-11-23 14:01:57 +01004771 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02004772 && !match_at_original_text(compl_shown_match)
4773 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004774 // Update "compl_shown_match" to the actually shown match
4775 ins_compl_update_shown_match();
4776
4777 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004778 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004779 // Delete old text to be replaced
4780 ins_compl_delete();
4781
4782 // When finding the longest common text we stick at the original text,
4783 // don't let CTRL-N or CTRL-P move to the first match.
4784 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4785
4786 // When restarting the search don't insert the first match either.
4787 if (compl_restarting)
4788 {
4789 advance = FALSE;
4790 compl_restarting = FALSE;
4791 }
4792
4793 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4794 // around.
4795 if (find_next_completion_match(allow_get_expansion, todo, advance,
4796 &num_matches) == -1)
4797 return -1;
4798
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004799 if (curbuf != orig_curbuf)
4800 {
4801 // In case some completion function switched buffer, don't want to
4802 // insert the completion elsewhere.
4803 return -1;
4804 }
4805
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004806 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01004807 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004808 {
glepnir6a38aff2024-12-16 21:56:16 +01004809 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004810 compl_used_match = FALSE;
4811 }
4812 else if (insert_match)
4813 {
4814 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01004815 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004816 else
glepnir6a38aff2024-12-16 21:56:16 +01004817 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004818 }
4819 else
4820 compl_used_match = FALSE;
4821
4822 if (!allow_get_expansion)
4823 {
4824 // may undisplay the popup menu first
4825 ins_compl_upd_pum();
4826
4827 if (pum_enough_matches())
4828 // Will display the popup menu, don't redraw yet to avoid flicker.
4829 pum_call_update_screen();
4830 else
4831 // Not showing the popup menu yet, redraw to show the user what was
4832 // inserted.
4833 update_screen(0);
4834
4835 // display the updated popup menu
4836 ins_compl_show_pum();
4837#ifdef FEAT_GUI
4838 if (gui.in_use)
4839 {
4840 // Show the cursor after the match, not after the redrawn text.
4841 setcursor();
4842 out_flush_cursor(FALSE, FALSE);
4843 }
4844#endif
4845
4846 // Delete old text to be replaced, since we're still searching and
4847 // don't want to match ourselves!
4848 ins_compl_delete();
4849 }
4850
4851 // Enter will select a match when the match wasn't inserted and the popup
4852 // menu is visible.
4853 if (compl_no_insert && !started)
4854 compl_enter_selects = TRUE;
4855 else
4856 compl_enter_selects = !insert_match && compl_match_array != NULL;
4857
4858 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004859 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004860 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004861
4862 return num_matches;
4863}
4864
4865/*
4866 * Call this while finding completions, to check whether the user has hit a key
4867 * that should change the currently displayed completion, or exit completion
4868 * mode. Also, when compl_pending is not zero, show a completion as soon as
4869 * possible. -- webb
4870 * "frequency" specifies out of how many calls we actually check.
4871 * "in_compl_func" is TRUE when called from complete_check(), don't set
4872 * compl_curr_match.
4873 */
4874 void
4875ins_compl_check_keys(int frequency, int in_compl_func)
4876{
4877 static int count = 0;
4878 int c;
4879
4880 // Don't check when reading keys from a script, :normal or feedkeys().
4881 // That would break the test scripts. But do check for keys when called
4882 // from complete_check().
4883 if (!in_compl_func && (using_script() || ex_normal_busy))
4884 return;
4885
4886 // Only do this at regular intervals
4887 if (++count < frequency)
4888 return;
4889 count = 0;
4890
4891 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4892 // can't do its work correctly.
4893 c = vpeekc_any();
4894 if (c != NUL)
4895 {
4896 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4897 {
4898 c = safe_vgetc(); // Eat the character
4899 compl_shows_dir = ins_compl_key2dir(c);
4900 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4901 c != K_UP && c != K_DOWN, in_compl_func);
4902 }
4903 else
4904 {
4905 // Need to get the character to have KeyTyped set. We'll put it
4906 // back with vungetc() below. But skip K_IGNORE.
4907 c = safe_vgetc();
4908 if (c != K_IGNORE)
4909 {
4910 // Don't interrupt completion when the character wasn't typed,
4911 // e.g., when doing @q to replay keys.
4912 if (c != Ctrl_R && KeyTyped)
4913 compl_interrupted = TRUE;
4914
4915 vungetc(c);
4916 }
4917 }
4918 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004919 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004920 {
4921 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4922
4923 compl_pending = 0;
4924 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4925 }
4926}
4927
4928/*
4929 * Decide the direction of Insert mode complete from the key typed.
4930 * Returns BACKWARD or FORWARD.
4931 */
4932 static int
4933ins_compl_key2dir(int c)
4934{
4935 if (c == Ctrl_P || c == Ctrl_L
4936 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4937 return BACKWARD;
4938 return FORWARD;
4939}
4940
4941/*
4942 * Return TRUE for keys that are used for completion only when the popup menu
4943 * is visible.
4944 */
4945 static int
4946ins_compl_pum_key(int c)
4947{
4948 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4949 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4950 || c == K_UP || c == K_DOWN);
4951}
4952
4953/*
4954 * Decide the number of completions to move forward.
4955 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4956 */
4957 static int
4958ins_compl_key2count(int c)
4959{
4960 int h;
4961
4962 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4963 {
4964 h = pum_get_height();
4965 if (h > 3)
4966 h -= 2; // keep some context
4967 return h;
4968 }
4969 return 1;
4970}
4971
4972/*
4973 * Return TRUE if completion with "c" should insert the match, FALSE if only
4974 * to change the currently selected completion.
4975 */
4976 static int
4977ins_compl_use_match(int c)
4978{
4979 switch (c)
4980 {
4981 case K_UP:
4982 case K_DOWN:
4983 case K_PAGEDOWN:
4984 case K_KPAGEDOWN:
4985 case K_S_DOWN:
4986 case K_PAGEUP:
4987 case K_KPAGEUP:
4988 case K_S_UP:
4989 return FALSE;
4990 }
4991 return TRUE;
4992}
4993
4994/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004995 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4996 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01004997 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004998 * Uses the global variables: compl_cont_status and ctrl_x_mode
4999 */
5000 static int
5001get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5002{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005003 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005004 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005005 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005006 {
5007 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5008 ;
5009 compl_col += ++startcol;
5010 compl_length = curs_col - startcol;
5011 }
5012 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005013 {
John Marriott5e6ea922024-11-23 14:01:57 +01005014 compl_pattern.string = str_foldcase(line + compl_col,
5015 compl_length, NULL, 0);
5016 if (compl_pattern.string == NULL)
5017 {
5018 compl_pattern.length = 0;
5019 return FAIL;
5020 }
5021 compl_pattern.length = STRLEN(compl_pattern.string);
5022 }
5023 else
5024 {
5025 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5026 if (compl_pattern.string == NULL)
5027 {
5028 compl_pattern.length = 0;
5029 return FAIL;
5030 }
5031 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005032 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005033 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005034 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005035 {
5036 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005037 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005038 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005039
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005040 if (!vim_iswordp(line + compl_col)
5041 || (compl_col > 0
5042 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005043 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005044 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005045 prefixlen = 0;
5046 }
John Marriott5e6ea922024-11-23 14:01:57 +01005047
5048 // we need up to 2 extra chars for the prefix
5049 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5050 compl_pattern.string = alloc(n);
5051 if (compl_pattern.string == NULL)
5052 {
5053 compl_pattern.length = 0;
5054 return FAIL;
5055 }
5056 STRCPY((char *)compl_pattern.string, prefix);
5057 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005058 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005059 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005060 }
5061 else if (--startcol < 0
5062 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5063 {
John Marriott5e6ea922024-11-23 14:01:57 +01005064 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5065
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005066 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005067 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5068 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005069 {
John Marriott5e6ea922024-11-23 14:01:57 +01005070 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005071 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005072 }
John Marriott5e6ea922024-11-23 14:01:57 +01005073 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005074 compl_col += curs_col;
5075 compl_length = 0;
5076 }
5077 else
5078 {
5079 // Search the point of change class of multibyte character
5080 // or not a word single byte character backward.
5081 if (has_mbyte)
5082 {
5083 int base_class;
5084 int head_off;
5085
5086 startcol -= (*mb_head_off)(line, line + startcol);
5087 base_class = mb_get_class(line + startcol);
5088 while (--startcol >= 0)
5089 {
5090 head_off = (*mb_head_off)(line, line + startcol);
5091 if (base_class != mb_get_class(line + startcol
5092 - head_off))
5093 break;
5094 startcol -= head_off;
5095 }
5096 }
5097 else
5098 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5099 ;
5100 compl_col += ++startcol;
5101 compl_length = (int)curs_col - startcol;
5102 if (compl_length == 1)
5103 {
5104 // Only match word with at least two chars -- webb
5105 // there's no need to call quote_meta,
5106 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005107 compl_pattern.string = alloc(7);
5108 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005109 {
John Marriott5e6ea922024-11-23 14:01:57 +01005110 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005111 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005112 }
John Marriott5e6ea922024-11-23 14:01:57 +01005113 STRCPY((char *)compl_pattern.string, "\\<");
5114 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5115 STRCAT((char *)compl_pattern.string, "\\k");
5116 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005117 }
5118 else
5119 {
John Marriott5e6ea922024-11-23 14:01:57 +01005120 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5121
5122 compl_pattern.string = alloc(n);
5123 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005124 {
John Marriott5e6ea922024-11-23 14:01:57 +01005125 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005126 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005127 }
John Marriott5e6ea922024-11-23 14:01:57 +01005128 STRCPY((char *)compl_pattern.string, "\\<");
5129 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005130 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005131 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005132 }
5133 }
5134
5135 return OK;
5136}
5137
5138/*
5139 * Get the pattern, column and length for whole line completion or for the
5140 * complete() function.
5141 * Sets the global variables: compl_col, compl_length and compl_pattern.
5142 */
5143 static int
5144get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5145{
5146 compl_col = (colnr_T)getwhitecols(line);
5147 compl_length = (int)curs_col - (int)compl_col;
5148 if (compl_length < 0) // cursor in indent: empty pattern
5149 compl_length = 0;
5150 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005151 {
John Marriott5e6ea922024-11-23 14:01:57 +01005152 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5153 NULL, 0);
5154 if (compl_pattern.string == NULL)
5155 {
5156 compl_pattern.length = 0;
5157 return FAIL;
5158 }
5159 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005160 }
John Marriott5e6ea922024-11-23 14:01:57 +01005161 else
5162 {
5163 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5164 if (compl_pattern.string == NULL)
5165 {
5166 compl_pattern.length = 0;
5167 return FAIL;
5168 }
5169 compl_pattern.length = (size_t)compl_length;
5170 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005171
5172 return OK;
5173}
5174
5175/*
5176 * Get the pattern, column and length for filename completion.
5177 * Sets the global variables: compl_col, compl_length and compl_pattern.
5178 */
5179 static int
5180get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5181{
5182 // Go back to just before the first filename character.
5183 if (startcol > 0)
5184 {
5185 char_u *p = line + startcol;
5186
5187 MB_PTR_BACK(line, p);
5188 while (p > line && vim_isfilec(PTR2CHAR(p)))
5189 MB_PTR_BACK(line, p);
5190 if (p == line && vim_isfilec(PTR2CHAR(p)))
5191 startcol = 0;
5192 else
5193 startcol = (int)(p - line) + 1;
5194 }
5195
5196 compl_col += startcol;
5197 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005198 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5199 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005200 {
John Marriott5e6ea922024-11-23 14:01:57 +01005201 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005202 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005203 }
5204
John Marriott5e6ea922024-11-23 14:01:57 +01005205 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005206
5207 return OK;
5208}
5209
5210/*
5211 * Get the pattern, column and length for command-line completion.
5212 * Sets the global variables: compl_col, compl_length and compl_pattern.
5213 */
5214 static int
5215get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5216{
John Marriott5e6ea922024-11-23 14:01:57 +01005217 compl_pattern.string = vim_strnsave(line, curs_col);
5218 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005219 {
John Marriott5e6ea922024-11-23 14:01:57 +01005220 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005221 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005222 }
John Marriott5e6ea922024-11-23 14:01:57 +01005223 compl_pattern.length = curs_col;
5224 set_cmd_context(&compl_xp, compl_pattern.string,
5225 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005226 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5227 || compl_xp.xp_context == EXPAND_NOTHING)
5228 // No completion possible, use an empty pattern to get a
5229 // "pattern not found" message.
5230 compl_col = curs_col;
5231 else
John Marriott5e6ea922024-11-23 14:01:57 +01005232 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005233 compl_length = curs_col - compl_col;
5234
5235 return OK;
5236}
5237
5238/*
5239 * Get the pattern, column and length for user defined completion ('omnifunc',
5240 * 'completefunc' and 'thesaurusfunc')
5241 * Sets the global variables: compl_col, compl_length and compl_pattern.
5242 * Uses the global variable: spell_bad_len
5243 */
5244 static int
5245get_userdefined_compl_info(colnr_T curs_col UNUSED)
5246{
5247 int ret = FAIL;
5248
5249#ifdef FEAT_COMPL_FUNC
5250 // Call user defined function 'completefunc' with "a:findstart"
5251 // set to 1 to obtain the length of text to use for completion.
5252 char_u *line;
5253 typval_T args[3];
5254 int col;
5255 char_u *funcname;
5256 pos_T pos;
5257 int save_State = State;
5258 callback_T *cb;
5259
5260 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5261 // length as a string
5262 funcname = get_complete_funcname(ctrl_x_mode);
5263 if (*funcname == NUL)
5264 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005265 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005266 ? "completefunc" : "omnifunc");
5267 return FAIL;
5268 }
5269
5270 args[0].v_type = VAR_NUMBER;
5271 args[0].vval.v_number = 1;
5272 args[1].v_type = VAR_STRING;
5273 args[1].vval.v_string = (char_u *)"";
5274 args[2].v_type = VAR_UNKNOWN;
5275 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005276 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005277 cb = get_insert_callback(ctrl_x_mode);
5278 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005279 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005280
5281 State = save_State;
5282 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005283 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005284 validate_cursor();
5285 if (!EQUAL_POS(curwin->w_cursor, pos))
5286 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005287 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005288 return FAIL;
5289 }
5290
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005291 // Return value -2 means the user complete function wants to cancel the
5292 // complete without an error, do the same if the function did not execute
5293 // successfully.
5294 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005295 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005296 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005297 if (col == -3)
5298 {
5299 ctrl_x_mode = CTRL_X_NORMAL;
5300 edit_submode = NULL;
5301 if (!shortmess(SHM_COMPLETIONMENU))
5302 msg_clr_cmdline();
5303 return FAIL;
5304 }
5305
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005306 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005307 // completion.
5308 compl_opt_refresh_always = FALSE;
5309 compl_opt_suppress_empty = FALSE;
5310
5311 if (col < 0)
5312 col = curs_col;
5313 compl_col = col;
5314 if (compl_col > curs_col)
5315 compl_col = curs_col;
5316
5317 // Setup variables for completion. Need to obtain "line" again,
5318 // it may have become invalid.
5319 line = ml_get(curwin->w_cursor.lnum);
5320 compl_length = curs_col - compl_col;
John Marriott5e6ea922024-11-23 14:01:57 +01005321 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5322 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005323 {
John Marriott5e6ea922024-11-23 14:01:57 +01005324 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005325 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005326 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005327
John Marriott5e6ea922024-11-23 14:01:57 +01005328 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005329 ret = OK;
5330#endif
5331
5332 return ret;
5333}
5334
5335/*
5336 * Get the pattern, column and length for spell completion.
5337 * Sets the global variables: compl_col, compl_length and compl_pattern.
5338 * Uses the global variable: spell_bad_len
5339 */
5340 static int
5341get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5342{
5343 int ret = FAIL;
5344#ifdef FEAT_SPELL
5345 char_u *line;
5346
5347 if (spell_bad_len > 0)
5348 compl_col = curs_col - spell_bad_len;
5349 else
5350 compl_col = spell_word_start(startcol);
5351 if (compl_col >= (colnr_T)startcol)
5352 {
5353 compl_length = 0;
5354 compl_col = curs_col;
5355 }
5356 else
5357 {
5358 spell_expand_check_cap(compl_col);
5359 compl_length = (int)curs_col - compl_col;
5360 }
5361 // Need to obtain "line" again, it may have become invalid.
5362 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005363 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5364 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005365 {
John Marriott5e6ea922024-11-23 14:01:57 +01005366 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005367 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005368 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005369
John Marriott5e6ea922024-11-23 14:01:57 +01005370 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005371 ret = OK;
5372#endif
5373
5374 return ret;
5375}
5376
5377/*
5378 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005379 * "startcol" - start column number of the completion pattern/text
5380 * "cur_col" - current cursor column
5381 * On return, "line_invalid" is set to TRUE, if the current line may have
5382 * become invalid and needs to be fetched again.
5383 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005384 */
5385 static int
5386compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5387{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005388 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005389 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5390 && !thesaurus_func_complete(ctrl_x_mode)))
5391 {
5392 return get_normal_compl_info(line, startcol, curs_col);
5393 }
5394 else if (ctrl_x_mode_line_or_eval())
5395 {
5396 return get_wholeline_compl_info(line, curs_col);
5397 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005398 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005399 {
5400 return get_filename_compl_info(line, startcol, curs_col);
5401 }
5402 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5403 {
5404 return get_cmdline_compl_info(line, curs_col);
5405 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005406 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005407 || thesaurus_func_complete(ctrl_x_mode))
5408 {
5409 if (get_userdefined_compl_info(curs_col) == FAIL)
5410 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005411 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005412 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005413 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005414 {
5415 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5416 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005417 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005418 }
5419 else
5420 {
5421 internal_error("ins_complete()");
5422 return FAIL;
5423 }
5424
5425 return OK;
5426}
5427
5428/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005429 * Continue an interrupted completion mode search in "line".
5430 *
5431 * If this same ctrl_x_mode has been interrupted use the text from
5432 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5433 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5434 * the same line as the cursor then fix it (the line has been split because it
5435 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5436 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005437 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005438 static void
5439ins_compl_continue_search(char_u *line)
5440{
5441 // it is a continued search
5442 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005443 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5444 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005445 {
5446 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5447 {
5448 // line (probably) wrapped, set compl_startpos to the
5449 // first non_blank in the line, if it is not a wordchar
5450 // include it to get a better pattern, but then we don't
5451 // want the "\\<" prefix, check it below
5452 compl_col = (colnr_T)getwhitecols(line);
5453 compl_startpos.col = compl_col;
5454 compl_startpos.lnum = curwin->w_cursor.lnum;
5455 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5456 }
5457 else
5458 {
5459 // S_IPOS was set when we inserted a word that was at the
5460 // beginning of the line, which means that we'll go to SOL
5461 // mode but first we need to redefine compl_startpos
5462 if (compl_cont_status & CONT_S_IPOS)
5463 {
5464 compl_cont_status |= CONT_SOL;
5465 compl_startpos.col = (colnr_T)(skipwhite(
5466 line + compl_length
5467 + compl_startpos.col) - line);
5468 }
5469 compl_col = compl_startpos.col;
5470 }
5471 compl_length = curwin->w_cursor.col - (int)compl_col;
5472 // IObuff is used to add a "word from the next line" would we
5473 // have enough space? just being paranoid
5474#define MIN_SPACE 75
5475 if (compl_length > (IOSIZE - MIN_SPACE))
5476 {
5477 compl_cont_status &= ~CONT_SOL;
5478 compl_length = (IOSIZE - MIN_SPACE);
5479 compl_col = curwin->w_cursor.col - compl_length;
5480 }
5481 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5482 if (compl_length < 1)
5483 compl_cont_status &= CONT_LOCAL;
5484 }
5485 else if (ctrl_x_mode_line_or_eval())
5486 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5487 else
5488 compl_cont_status = 0;
5489}
5490
5491/*
5492 * start insert mode completion
5493 */
5494 static int
5495ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005496{
5497 char_u *line;
5498 int startcol = 0; // column where searched text starts
5499 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005500 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005501 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005502 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005503
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005504 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005505
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005506 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005507 did_si = FALSE;
5508 can_si = FALSE;
5509 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005510 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005511 return FAIL;
5512
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005513 line = ml_get(curwin->w_cursor.lnum);
5514 curs_col = curwin->w_cursor.col;
5515 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005516 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005517
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005518 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5519 && compl_cont_mode == ctrl_x_mode)
5520 // this same ctrl-x_mode was interrupted previously. Continue the
5521 // completion.
5522 ins_compl_continue_search(line);
5523 else
5524 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005525
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005526 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005527 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005528 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005529 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005530 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5531 compl_cont_status = 0;
5532 compl_cont_status |= CONT_N_ADDS;
5533 compl_startpos = curwin->w_cursor;
5534 startcol = (int)curs_col;
5535 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005536 }
5537
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005538 // Work out completion pattern and original text -- webb
5539 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5540 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005541 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5542 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005543 // restore did_ai, so that adding comment leader works
5544 did_ai = save_did_ai;
5545 return FAIL;
5546 }
5547 // If "line" was changed while getting completion info get it again.
5548 if (line_invalid)
5549 line = ml_get(curwin->w_cursor.lnum);
5550
glepnir7cfe6932024-09-15 20:06:28 +02005551 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005552 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005553 {
5554 edit_submode_pre = (char_u *)_(" Adding");
5555 if (ctrl_x_mode_line_or_eval())
5556 {
5557 // Insert a new line, keep indentation but ignore 'comments'.
5558 char_u *old = curbuf->b_p_com;
5559
5560 curbuf->b_p_com = (char_u *)"";
5561 compl_startpos.lnum = curwin->w_cursor.lnum;
5562 compl_startpos.col = compl_col;
5563 ins_eol('\r');
5564 curbuf->b_p_com = old;
5565 compl_length = 0;
5566 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01005567 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005568 }
glepnir7cfe6932024-09-15 20:06:28 +02005569 else if (ctrl_x_mode_normal() && in_fuzzy)
5570 {
5571 compl_startpos = curwin->w_cursor;
5572 compl_cont_status &= CONT_S_IPOS;
5573 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005574 }
5575 else
5576 {
5577 edit_submode_pre = NULL;
5578 compl_startpos.col = compl_col;
5579 }
5580
5581 if (compl_cont_status & CONT_LOCAL)
5582 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5583 else
5584 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5585
5586 // If any of the original typed text has been changed we need to fix
5587 // the redo buffer.
5588 ins_compl_fixRedoBufForLeader(NULL);
5589
5590 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005591 VIM_CLEAR_STRING(compl_orig_text);
5592 compl_orig_text.length = (size_t)compl_length;
5593 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005594 if (p_ic)
5595 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01005596 if (compl_orig_text.string == NULL || ins_compl_add(compl_orig_text.string,
5597 (int)compl_orig_text.length, NULL, NULL, NULL, 0, flags, FALSE, NULL) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005598 {
John Marriott5e6ea922024-11-23 14:01:57 +01005599 VIM_CLEAR_STRING(compl_pattern);
5600 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005601 return FAIL;
5602 }
5603
5604 // showmode might reset the internal line pointers, so it must
5605 // be called before line = ml_get(), or when this address is no
5606 // longer needed. -- Acevedo.
5607 edit_submode_extra = (char_u *)_("-- Searching...");
5608 edit_submode_highl = HLF_COUNT;
5609 showmode();
5610 edit_submode_extra = NULL;
5611 out_flush();
5612
5613 return OK;
5614}
5615
5616/*
5617 * display the completion status message
5618 */
5619 static void
5620ins_compl_show_statusmsg(void)
5621{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005622 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005623 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005624 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005625 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005626 ? (char_u *)_("Hit end of paragraph")
5627 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005628 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005629 }
5630
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005631 if (edit_submode_extra == NULL)
5632 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005633 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005634 {
5635 edit_submode_extra = (char_u *)_("Back at original");
5636 edit_submode_highl = HLF_W;
5637 }
5638 else if (compl_cont_status & CONT_S_IPOS)
5639 {
5640 edit_submode_extra = (char_u *)_("Word from other line");
5641 edit_submode_highl = HLF_COUNT;
5642 }
5643 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5644 {
5645 edit_submode_extra = (char_u *)_("The only match");
5646 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005647 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005648 }
5649 else
5650 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005651#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005652 // Update completion sequence number when needed.
5653 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005654 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005655#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005656 // The match should always have a sequence number now, this is
5657 // just a safety check.
5658 if (compl_curr_match->cp_number != -1)
5659 {
5660 // Space for 10 text chars. + 2x10-digit no.s = 31.
5661 // Translations may need more than twice that.
5662 static char_u match_ref[81];
5663
5664 if (compl_matches > 0)
5665 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005666 _("match %d of %d"),
5667 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005668 else
5669 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005670 _("match %d"),
5671 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005672 edit_submode_extra = match_ref;
5673 edit_submode_highl = HLF_R;
5674 if (dollar_vcol >= 0)
5675 curs_columns(FALSE);
5676 }
5677 }
5678 }
5679
5680 // Show a message about what (completion) mode we're in.
5681 if (!compl_opt_suppress_empty)
5682 {
5683 showmode();
5684 if (!shortmess(SHM_COMPLETIONMENU))
5685 {
5686 if (edit_submode_extra != NULL)
5687 {
5688 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005689 {
5690 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005691 msg_attr((char *)edit_submode_extra,
5692 edit_submode_highl < HLF_COUNT
5693 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005694 msg_hist_off = FALSE;
5695 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005696 }
5697 else
5698 msg_clr_cmdline(); // necessary for "noshowmode"
5699 }
5700 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005701}
5702
5703/*
5704 * Do Insert mode completion.
5705 * Called when character "c" was typed, which has a meaning for completion.
5706 * Returns OK if completion was done, FAIL if something failed (out of mem).
5707 */
5708 int
5709ins_complete(int c, int enable_pum)
5710{
5711 int n;
5712 int save_w_wrow;
5713 int save_w_leftcol;
5714 int insert_match;
5715
5716 compl_direction = ins_compl_key2dir(c);
5717 insert_match = ins_compl_use_match(c);
5718
5719 if (!compl_started)
5720 {
5721 if (ins_compl_start() == FAIL)
5722 return FAIL;
5723 }
5724 else if (insert_match && stop_arrow() == FAIL)
5725 return FAIL;
5726
5727 compl_shown_match = compl_curr_match;
5728 compl_shows_dir = compl_direction;
5729
5730 // Find next match (and following matches).
5731 save_w_wrow = curwin->w_wrow;
5732 save_w_leftcol = curwin->w_leftcol;
5733 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5734
5735 // may undisplay the popup menu
5736 ins_compl_upd_pum();
5737
5738 if (n > 1) // all matches have been found
5739 compl_matches = n;
5740 compl_curr_match = compl_shown_match;
5741 compl_direction = compl_shows_dir;
5742
5743 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5744 // mode.
5745 if (got_int && !global_busy)
5746 {
5747 (void)vgetc();
5748 got_int = FALSE;
5749 }
5750
5751 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005752 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005753 {
5754 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5755 // because we couldn't expand anything at first place, but if we used
5756 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5757 // (such as M in M'exico) if not tried already. -- Acevedo
5758 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005759 || compl_status_adding()
5760 || (ctrl_x_mode_not_default()
5761 && !ctrl_x_mode_path_patterns()
5762 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005763 compl_cont_status &= ~CONT_N_ADDS;
5764 }
5765
5766 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5767 compl_cont_status |= CONT_S_IPOS;
5768 else
5769 compl_cont_status &= ~CONT_S_IPOS;
5770
5771 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005772
5773 // Show the popup menu, unless we got interrupted.
5774 if (enable_pum && !compl_interrupted)
5775 show_pum(save_w_wrow, save_w_leftcol);
5776
5777 compl_was_interrupted = compl_interrupted;
5778 compl_interrupted = FALSE;
5779
5780 return OK;
5781}
5782
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005783/*
5784 * Remove (if needed) and show the popup menu
5785 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005786 static void
5787show_pum(int prev_w_wrow, int prev_w_leftcol)
5788{
5789 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005790 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005791 RedrawingDisabled = 0;
5792
5793 // If the cursor moved or the display scrolled we need to remove the pum
5794 // first.
5795 setcursor();
5796 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5797 ins_compl_del_pum();
5798
5799 ins_compl_show_pum();
5800 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005801
5802 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005803}
5804
5805/*
5806 * Looks in the first "len" chars. of "src" for search-metachars.
5807 * If dest is not NULL the chars. are copied there quoting (with
5808 * a backslash) the metachars, and dest would be NUL terminated.
5809 * Returns the length (needed) of dest
5810 */
5811 static unsigned
5812quote_meta(char_u *dest, char_u *src, int len)
5813{
5814 unsigned m = (unsigned)len + 1; // one extra for the NUL
5815
5816 for ( ; --len >= 0; src++)
5817 {
5818 switch (*src)
5819 {
5820 case '.':
5821 case '*':
5822 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005823 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005824 break;
5825 // FALLTHROUGH
5826 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005827 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005828 break;
5829 // FALLTHROUGH
5830 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005831 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005832 break;
5833 // FALLTHROUGH
5834 case '^': // currently it's not needed.
5835 case '$':
5836 m++;
5837 if (dest != NULL)
5838 *dest++ = '\\';
5839 break;
5840 }
5841 if (dest != NULL)
5842 *dest++ = *src;
5843 // Copy remaining bytes of a multibyte character.
5844 if (has_mbyte)
5845 {
5846 int i, mb_len;
5847
5848 mb_len = (*mb_ptr2len)(src) - 1;
5849 if (mb_len > 0 && len >= mb_len)
5850 for (i = 0; i < mb_len; ++i)
5851 {
5852 --len;
5853 ++src;
5854 if (dest != NULL)
5855 *dest++ = *src;
5856 }
5857 }
5858 }
5859 if (dest != NULL)
5860 *dest = NUL;
5861
5862 return m;
5863}
5864
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005865#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005866 void
5867free_insexpand_stuff(void)
5868{
John Marriott5e6ea922024-11-23 14:01:57 +01005869 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005870# ifdef FEAT_EVAL
5871 free_callback(&cfu_cb);
5872 free_callback(&ofu_cb);
5873 free_callback(&tsrfu_cb);
5874# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005875}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005876#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005877
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005878#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005879/*
5880 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5881 * spelled word, if there is one.
5882 */
5883 static void
5884spell_back_to_badword(void)
5885{
5886 pos_T tpos = curwin->w_cursor;
5887
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005888 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005889 if (curwin->w_cursor.col != tpos.col)
5890 start_arrow(&tpos);
5891}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005892#endif