blob: 7b9a5116d00cdadf54005eb97e102f0edf70bf5b [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)"),
61 N_(" Spelling suggestion (s^N^P)"),
62 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/*
91 * Array indexes used for cp_text[].
92 */
93#define CPT_ABBR 0 // "abbr"
94#define CPT_MENU 1 // "menu"
95#define CPT_KIND 2 // "kind"
96#define CPT_INFO 3 // "info"
Bram Moolenaar08928322020-01-04 14:32:48 +010097#define CPT_COUNT 4 // Number of entries
Bram Moolenaar7591bb32019-03-30 13:53:47 +010098
99/*
100 * Structure used to store one match for insert completion.
101 */
102typedef struct compl_S compl_T;
103struct compl_S
104{
105 compl_T *cp_next;
106 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200107 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200108 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100109#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100110 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100111#endif
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200112 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113 // cp_flags has CP_FREE_FNAME
114 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200115 int cp_number; // sequence number
glepnira218cc62024-06-03 19:32:39 +0200116 int cp_score; // fuzzy match score
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100117};
118
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200119// values for cp_flags
120# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
121# define CP_FREE_FNAME 2 // cp_fname is allocated
122# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
123# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
124# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200125# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100127/*
128 * All the current matches are stored in a list.
129 * "compl_first_match" points to the start of the list.
130 * "compl_curr_match" points to the currently selected entry.
131 * "compl_shown_match" is different from compl_curr_match during
132 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000133 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100134 */
135static compl_T *compl_first_match = NULL;
136static compl_T *compl_curr_match = NULL;
137static compl_T *compl_shown_match = NULL;
138static compl_T *compl_old_match = NULL;
139
140// After using a cursor key <Enter> selects a match in the popup menu,
141// otherwise it inserts a line break.
142static int compl_enter_selects = FALSE;
143
144// When "compl_leader" is not NULL only matches that start with this string
145// are used.
146static char_u *compl_leader = NULL;
147
148static int compl_get_longest = FALSE; // put longest common string
149 // in compl_leader
150
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100151// Selected one of the matches. When FALSE the match was edited or using the
152// longest common string.
153static int compl_used_match;
154
155// didn't finish finding completions.
156static int compl_was_interrupted = FALSE;
157
158// Set when character typed while looking for matches and it means we should
159// stop looking for matches.
160static int compl_interrupted = FALSE;
161
162static int compl_restarting = FALSE; // don't insert match
163
164// When the first completion is done "compl_started" is set. When it's
165// FALSE the word to be completed must be located.
166static int compl_started = FALSE;
167
168// Which Ctrl-X mode are we in?
169static int ctrl_x_mode = CTRL_X_NORMAL;
170
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000171static int compl_matches = 0; // number of completion matches
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100172static char_u *compl_pattern = NULL;
John Marriott8c85a2a2024-05-20 19:18:26 +0200173static size_t compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100174static int compl_direction = FORWARD;
175static int compl_shows_dir = FORWARD;
176static int compl_pending = 0; // > 1 for postponed CTRL-N
177static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000178// Length in bytes of the text being completed (this is deleted to be replaced
179// by the match.)
180static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100181static colnr_T compl_col = 0; // column where the text starts
182 // that is being completed
183static char_u *compl_orig_text = NULL; // text as it was before
184 // completion started
185static int compl_cont_mode = 0;
186static expand_T compl_xp;
187
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000188// List of flags for method of completion.
189static int compl_cont_status = 0;
190# define CONT_ADDING 1 // "normal" or "adding" expansion
191# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
192 // it's set only iff N_ADDS is set
193# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
194# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
195 // if so, word-wise-expansion will set SOL
196# define CONT_SOL 16 // pattern includes start of line, just for
197 // word-wise expansion, not set for ^X^L
198# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
199 // expansion, (eg use complete=.)
200
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100201static int compl_opt_refresh_always = FALSE;
202static int compl_opt_suppress_empty = FALSE;
203
glepnira218cc62024-06-03 19:32:39 +0200204static int compl_selected_item = -1;
205
Bram Moolenaar08928322020-01-04 14:32:48 +0100206static 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);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100207static void ins_compl_longest_match(compl_T *match);
208static void ins_compl_del_pum(void);
209static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
210static char_u *find_line_end(char_u *ptr);
211static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100212static int ins_compl_need_restart(void);
213static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000214static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100215static void ins_compl_restart(void);
216static void ins_compl_set_original_text(char_u *str);
217static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
218# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
219static void ins_compl_add_list(list_T *list);
220static void ins_compl_add_dict(dict_T *dict);
221# endif
222static int ins_compl_key2dir(int c);
223static int ins_compl_pum_key(int c);
224static int ins_compl_key2count(int c);
225static void show_pum(int prev_w_wrow, int prev_w_leftcol);
226static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100227
228#ifdef FEAT_SPELL
229static void spell_back_to_badword(void);
230static int spell_bad_len = 0; // length of located bad word
231#endif
232
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100233/*
234 * CTRL-X pressed in Insert mode.
235 */
236 void
237ins_ctrl_x(void)
238{
zeertzjqdca29d92021-08-31 19:12:51 +0200239 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100240 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000241 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242 if (compl_cont_status & CONT_N_ADDS)
243 compl_cont_status |= CONT_INTRPT;
244 else
245 compl_cont_status = 0;
246 // We're not sure which CTRL-X mode it will be yet
247 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
248 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
249 edit_submode_pre = NULL;
250 showmode();
251 }
zeertzjqdca29d92021-08-31 19:12:51 +0200252 else
253 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
254 // CTRL-V look like CTRL-N
255 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100256
LemonBoy2bf52dd2022-04-09 18:17:34 +0100257 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100258}
259
260/*
261 * Functions to check the current CTRL-X mode.
262 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000263int ctrl_x_mode_none(void)
264 { return ctrl_x_mode == 0; }
265int ctrl_x_mode_normal(void)
266 { return ctrl_x_mode == CTRL_X_NORMAL; }
267int ctrl_x_mode_scroll(void)
268 { return ctrl_x_mode == CTRL_X_SCROLL; }
269int ctrl_x_mode_whole_line(void)
270 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
271int ctrl_x_mode_files(void)
272 { return ctrl_x_mode == CTRL_X_FILES; }
273int ctrl_x_mode_tags(void)
274 { return ctrl_x_mode == CTRL_X_TAGS; }
275int ctrl_x_mode_path_patterns(void)
276 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
277int ctrl_x_mode_path_defines(void)
278 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
279int ctrl_x_mode_dictionary(void)
280 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
281int ctrl_x_mode_thesaurus(void)
282 { return ctrl_x_mode == CTRL_X_THESAURUS; }
283int ctrl_x_mode_cmdline(void)
284 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200285 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000286int ctrl_x_mode_function(void)
287 { return ctrl_x_mode == CTRL_X_FUNCTION; }
288int ctrl_x_mode_omni(void)
289 { return ctrl_x_mode == CTRL_X_OMNI; }
290int ctrl_x_mode_spell(void)
291 { return ctrl_x_mode == CTRL_X_SPELL; }
292static int ctrl_x_mode_eval(void)
293 { return ctrl_x_mode == CTRL_X_EVAL; }
294int ctrl_x_mode_line_or_eval(void)
295 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100296
297/*
298 * Whether other than default completion has been selected.
299 */
300 int
301ctrl_x_mode_not_default(void)
302{
303 return ctrl_x_mode != CTRL_X_NORMAL;
304}
305
306/*
zeertzjqdca29d92021-08-31 19:12:51 +0200307 * Whether CTRL-X was typed without a following character,
308 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100309 */
310 int
311ctrl_x_mode_not_defined_yet(void)
312{
313 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
314}
315
316/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000317 * Return TRUE if currently in "normal" or "adding" insert completion matches
318 * state
319 */
320 int
321compl_status_adding(void)
322{
323 return compl_cont_status & CONT_ADDING;
324}
325
326/*
327 * Return TRUE if the completion pattern includes start of line, just for
328 * word-wise expansion.
329 */
330 int
331compl_status_sol(void)
332{
333 return compl_cont_status & CONT_SOL;
334}
335
336/*
337 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
338 */
339 int
340compl_status_local(void)
341{
342 return compl_cont_status & CONT_LOCAL;
343}
344
345/*
346 * Clear the completion status flags
347 */
348 void
349compl_status_clear(void)
350{
351 compl_cont_status = 0;
352}
353
354/*
355 * Return TRUE if completion is using the forward direction matches
356 */
357 static int
358compl_dir_forward(void)
359{
360 return compl_direction == FORWARD;
361}
362
363/*
364 * Return TRUE if currently showing forward completion matches
365 */
366 static int
367compl_shows_dir_forward(void)
368{
369 return compl_shows_dir == FORWARD;
370}
371
372/*
373 * Return TRUE if currently showing backward completion matches
374 */
375 static int
376compl_shows_dir_backward(void)
377{
378 return compl_shows_dir == BACKWARD;
379}
380
381/*
382 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100383 */
384 int
385has_compl_option(int dict_opt)
386{
387 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200388#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100389 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200390#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100391 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100392 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
393#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100394 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100395#endif
396 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100397 {
398 ctrl_x_mode = CTRL_X_NORMAL;
399 edit_submode = NULL;
400 msg_attr(dict_opt ? _("'dictionary' option is empty")
401 : _("'thesaurus' option is empty"),
402 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100403 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100404 {
405 vim_beep(BO_COMPL);
406 setcursor();
407 out_flush();
408#ifdef FEAT_EVAL
409 if (!get_vim_var_nr(VV_TESTING))
410#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100411 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100412 }
413 return FALSE;
414 }
415 return TRUE;
416}
417
418/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000419 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100420 * This depends on the current mode.
421 */
422 int
423vim_is_ctrl_x_key(int c)
424{
425 // Always allow ^R - let its results then be checked
426 if (c == Ctrl_R)
427 return TRUE;
428
429 // Accept <PageUp> and <PageDown> if the popup menu is visible.
430 if (ins_compl_pum_key(c))
431 return TRUE;
432
433 switch (ctrl_x_mode)
434 {
435 case 0: // Not in any CTRL-X mode
436 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
437 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200438 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100439 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
440 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
441 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
442 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
443 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200444 || c == Ctrl_S || c == Ctrl_K || c == 's'
445 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100446 case CTRL_X_SCROLL:
447 return (c == Ctrl_Y || c == Ctrl_E);
448 case CTRL_X_WHOLE_LINE:
449 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
450 case CTRL_X_FILES:
451 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
452 case CTRL_X_DICTIONARY:
453 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
454 case CTRL_X_THESAURUS:
455 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
456 case CTRL_X_TAGS:
457 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
458#ifdef FEAT_FIND_ID
459 case CTRL_X_PATH_PATTERNS:
460 return (c == Ctrl_P || c == Ctrl_N);
461 case CTRL_X_PATH_DEFINES:
462 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
463#endif
464 case CTRL_X_CMDLINE:
465 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
466 || c == Ctrl_X);
467#ifdef FEAT_COMPL_FUNC
468 case CTRL_X_FUNCTION:
469 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
470 case CTRL_X_OMNI:
471 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
472#endif
473 case CTRL_X_SPELL:
474 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
475 case CTRL_X_EVAL:
476 return (c == Ctrl_P || c == Ctrl_N);
477 }
478 internal_error("vim_is_ctrl_x_key()");
479 return FALSE;
480}
481
482/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000483 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000484 */
485 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000486match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000487{
488 return match->cp_flags & CP_ORIGINAL_TEXT;
489}
490
491/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000492 * Returns TRUE if "match" is the first match in the completion list.
493 */
494 static int
495is_first_match(compl_T *match)
496{
497 return match == compl_first_match;
498}
499
500/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100501 * Return TRUE when character "c" is part of the item currently being
502 * completed. Used to decide whether to abandon complete mode when the menu
503 * is visible.
504 */
505 int
506ins_compl_accept_char(int c)
507{
508 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
509 // When expanding an identifier only accept identifier chars.
510 return vim_isIDc(c);
511
512 switch (ctrl_x_mode)
513 {
514 case CTRL_X_FILES:
515 // When expanding file name only accept file name chars. But not
516 // path separators, so that "proto/<Tab>" expands files in
517 // "proto", not "proto/" as a whole
518 return vim_isfilec(c) && !vim_ispathsep(c);
519
520 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200521 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100522 case CTRL_X_OMNI:
523 // Command line and Omni completion can work with just about any
524 // printable character, but do stop at white space.
525 return vim_isprintc(c) && !VIM_ISWHITE(c);
526
527 case CTRL_X_WHOLE_LINE:
528 // For while line completion a space can be part of the line.
529 return vim_isprintc(c);
530 }
531 return vim_iswordc(c);
532}
533
534/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000535 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100536 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000537 */
538 static char_u *
539ins_compl_infercase_gettext(
540 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100541 int char_len,
542 int compl_char_len,
543 int min_len,
544 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000545{
546 int *wca; // Wide character array.
547 char_u *p;
548 int i, c;
549 int has_lower = FALSE;
550 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100551 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000552
553 IObuff[0] = NUL;
554
555 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100556 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000557 if (wca == NULL)
558 return IObuff;
559
560 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100561 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000562 if (has_mbyte)
563 wca[i] = mb_ptr2char_adv(&p);
564 else
565 wca[i] = *(p++);
566
567 // Rule 1: Were any chars converted to lower?
568 p = compl_orig_text;
569 for (i = 0; i < min_len; ++i)
570 {
571 if (has_mbyte)
572 c = mb_ptr2char_adv(&p);
573 else
574 c = *(p++);
575 if (MB_ISLOWER(c))
576 {
577 has_lower = TRUE;
578 if (MB_ISUPPER(wca[i]))
579 {
580 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100581 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 wca[i] = MB_TOLOWER(wca[i]);
583 break;
584 }
585 }
586 }
587
588 // Rule 2: No lower case, 2nd consecutive letter converted to
589 // upper case.
590 if (!has_lower)
591 {
592 p = compl_orig_text;
593 for (i = 0; i < min_len; ++i)
594 {
595 if (has_mbyte)
596 c = mb_ptr2char_adv(&p);
597 else
598 c = *(p++);
599 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
600 {
601 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100602 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000603 wca[i] = MB_TOUPPER(wca[i]);
604 break;
605 }
606 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
607 }
608 }
609
610 // Copy the original case of the part we typed.
611 p = compl_orig_text;
612 for (i = 0; i < min_len; ++i)
613 {
614 if (has_mbyte)
615 c = mb_ptr2char_adv(&p);
616 else
617 c = *(p++);
618 if (MB_ISLOWER(c))
619 wca[i] = MB_TOLOWER(wca[i]);
620 else if (MB_ISUPPER(c))
621 wca[i] = MB_TOUPPER(wca[i]);
622 }
623
624 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000625 p = IObuff;
626 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100627 ga_init2(&gap, 1, 500);
628 while (i < char_len)
629 {
630 if (gap.ga_data != NULL)
631 {
632 if (ga_grow(&gap, 10) == FAIL)
633 {
634 ga_clear(&gap);
635 return (char_u *)"[failed]";
636 }
637 p = (char_u *)gap.ga_data + gap.ga_len;
638 if (has_mbyte)
639 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
640 else
641 {
642 *p = wca[i++];
643 ++gap.ga_len;
644 }
645 }
646 else if ((p - IObuff) + 6 >= IOSIZE)
647 {
648 // Multi-byte characters can occupy up to five bytes more than
649 // ASCII characters, and we also need one byte for NUL, so when
650 // getting to six bytes from the edge of IObuff switch to using a
651 // growarray. Add the character in the next round.
652 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100653 {
654 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100655 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100656 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100657 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100658 STRCPY(gap.ga_data, IObuff);
Bram Moolenaarc7bd2f02022-07-15 20:45:20 +0100659 gap.ga_len = (int)STRLEN(IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100660 }
661 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000662 p += (*mb_char2bytes)(wca[i++], p);
663 else
664 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100665 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000666 vim_free(wca);
667
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100668 if (gap.ga_data != NULL)
669 {
670 *tofree = gap.ga_data;
671 return gap.ga_data;
672 }
673
674 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000675 return IObuff;
676}
677
678/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100679 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
680 * case of the originally typed text is used, and the case of the completed
681 * text is inferred, ie this tries to work out what case you probably wanted
682 * the rest of the word to be in -- webb
683 */
684 int
685ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200686 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100687 int len,
688 int icase,
689 char_u *fname,
690 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200691 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200693 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100694 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 int char_len; // count multi-byte characters
696 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100697 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200698 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100699 int res;
700 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100701
702 if (p_ic && curbuf->b_p_inf && len > 0)
703 {
704 // Infer case of completed part.
705
706 // Find actual length of completion.
707 if (has_mbyte)
708 {
709 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100710 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100711 while (*p != NUL)
712 {
713 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100714 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100715 }
716 }
717 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100718 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719
720 // Find actual length of original text.
721 if (has_mbyte)
722 {
723 p = compl_orig_text;
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
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100732 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100734 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100737
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 str = ins_compl_infercase_gettext(str, char_len,
739 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100740 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200741 if (cont_s_ipos)
742 flags |= CP_CONT_S_IPOS;
743 if (icase)
744 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200745
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100746 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);
747 vim_free(tofree);
748 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100749}
750
751/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000752 * Add a match to the list of matches. The arguments are:
753 * str - text of the match to add
754 * len - length of "str". If -1, then the length of "str" is
755 * computed.
756 * fname - file name to associate with this match.
757 * cptext - list of strings to use with this match (for abbr, menu, info
758 * and kind)
759 * user_data - user supplied data (any vim type) for this match
760 * cdir - match direction. If 0, use "compl_direction".
761 * flags_arg - match flags (cp_flags)
762 * adup - accept this match even if it is already present.
763 * If "cdir" is FORWARD, then the match is added after the current match.
764 * Otherwise, it is added before the current match.
765 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 * If the given string is already in the list of completions, then return
767 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
768 * maybe because alloc() returns NULL, then FAIL is returned.
769 */
770 static int
771ins_compl_add(
772 char_u *str,
773 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100774 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100775 char_u **cptext, // extra text for popup menu or NULL
776 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200778 int flags_arg,
Bram Moolenaar08928322020-01-04 14:32:48 +0100779 int adup) // accept duplicate match
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780{
781 compl_T *match;
782 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200783 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784
Bram Moolenaarceb06192021-04-04 15:05:22 +0200785 if (flags & CP_FAST)
786 fast_breakcheck();
787 else
788 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100789 if (got_int)
790 return FAIL;
791 if (len < 0)
792 len = (int)STRLEN(str);
793
794 // If the same match is already present, don't add it.
795 if (compl_first_match != NULL && !adup)
796 {
797 match = compl_first_match;
798 do
799 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000800 if (!match_at_original_text(match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100801 && STRNCMP(match->cp_str, str, len) == 0
Bram Moolenaarbaefde12022-07-07 19:59:49 +0100802 && ((int)STRLEN(match->cp_str) <= len
803 || match->cp_str[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100804 return NOTDONE;
805 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000806 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100807 }
808
809 // Remove any popup menu before changing the list of matches.
810 ins_compl_del_pum();
811
812 // Allocate a new match structure.
813 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200814 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100815 if (match == NULL)
816 return FAIL;
817 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200818 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 match->cp_number = 0;
820 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
821 {
822 vim_free(match);
823 return FAIL;
824 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100825
826 // match-fname is:
827 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200828 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829 // - NULL otherwise. --Acevedo
830 if (fname != NULL
831 && compl_curr_match != NULL
832 && compl_curr_match->cp_fname != NULL
833 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
834 match->cp_fname = compl_curr_match->cp_fname;
835 else if (fname != NULL)
836 {
837 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200838 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100839 }
840 else
841 match->cp_fname = NULL;
842 match->cp_flags = flags;
843
844 if (cptext != NULL)
845 {
846 int i;
847
848 for (i = 0; i < CPT_COUNT; ++i)
849 if (cptext[i] != NULL && *cptext[i] != NUL)
850 match->cp_text[i] = vim_strsave(cptext[i]);
851 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100852#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100853 if (user_data != NULL)
854 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100855#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000857 // Link the new match structure after (FORWARD) or before (BACKWARD) the
858 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859 if (compl_first_match == NULL)
860 match->cp_next = match->cp_prev = NULL;
861 else if (dir == FORWARD)
862 {
863 match->cp_next = compl_curr_match->cp_next;
864 match->cp_prev = compl_curr_match;
865 }
866 else // BACKWARD
867 {
868 match->cp_next = compl_curr_match;
869 match->cp_prev = compl_curr_match->cp_prev;
870 }
871 if (match->cp_next)
872 match->cp_next->cp_prev = match;
873 if (match->cp_prev)
874 match->cp_prev->cp_next = match;
875 else // if there's nothing before, it is the first match
876 compl_first_match = match;
877 compl_curr_match = match;
878
879 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200880 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881 ins_compl_longest_match(match);
882
883 return OK;
884}
885
886/*
887 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 */
890 static int
891ins_compl_equal(compl_T *match, char_u *str, int len)
892{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200893 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200894 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200895 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100896 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
897 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
898}
899
900/*
901 * Reduce the longest common string for match "match".
902 */
903 static void
904ins_compl_longest_match(compl_T *match)
905{
906 char_u *p, *s;
907 int c1, c2;
908 int had_match;
909
910 if (compl_leader == NULL)
911 {
912 // First match, use it as a whole.
913 compl_leader = vim_strsave(match->cp_str);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000914 if (compl_leader == NULL)
915 return;
916
917 had_match = (curwin->w_cursor.col > compl_col);
918 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000919 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000920 ins_redraw(FALSE);
921
922 // When the match isn't there (to avoid matching itself) remove it
923 // again after redrawing.
924 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100925 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000927
928 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100929 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000930
931 // Reduce the text if this match differs from compl_leader.
932 p = compl_leader;
933 s = match->cp_str;
934 while (*p != NUL)
935 {
936 if (has_mbyte)
937 {
938 c1 = mb_ptr2char(p);
939 c2 = mb_ptr2char(s);
940 }
941 else
942 {
943 c1 = *p;
944 c2 = *s;
945 }
946 if ((match->cp_flags & CP_ICASE)
947 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
948 break;
949 if (has_mbyte)
950 {
951 MB_PTR_ADV(p);
952 MB_PTR_ADV(s);
953 }
954 else
955 {
956 ++p;
957 ++s;
958 }
959 }
960
961 if (*p != NUL)
962 {
963 // Leader was shortened, need to change the inserted text.
964 *p = NUL;
965 had_match = (curwin->w_cursor.col > compl_col);
966 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000967 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000968 ins_redraw(FALSE);
969
970 // When the match isn't there (to avoid matching itself) remove it
971 // again after redrawing.
972 if (!had_match)
973 ins_compl_delete();
974 }
975
976 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100977}
978
979/*
980 * Add an array of matches to the list of matches.
981 * Frees matches[].
982 */
983 static void
984ins_compl_add_matches(
985 int num_matches,
986 char_u **matches,
987 int icase)
988{
989 int i;
990 int add_r = OK;
991 int dir = compl_direction;
992
993 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100994 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
Bram Moolenaar440cf092021-04-03 20:13:30 +0200995 CP_FAST | (icase ? CP_ICASE : 0), FALSE)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100996 // if dir was BACKWARD then honor it just once
997 dir = FORWARD;
998 FreeWild(num_matches, matches);
999}
1000
1001/*
1002 * Make the completion list cyclic.
1003 * Return the number of matches (excluding the original).
1004 */
1005 static int
1006ins_compl_make_cyclic(void)
1007{
1008 compl_T *match;
1009 int count = 0;
1010
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001011 if (compl_first_match == NULL)
1012 return 0;
1013
1014 // Find the end of the list.
1015 match = compl_first_match;
1016 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001017 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001018 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001019 match = match->cp_next;
1020 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001021 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001022 match->cp_next = compl_first_match;
1023 compl_first_match->cp_prev = match;
1024
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001025 return count;
1026}
1027
1028/*
1029 * Return whether there currently is a shown match.
1030 */
1031 int
1032ins_compl_has_shown_match(void)
1033{
1034 return compl_shown_match == NULL
1035 || compl_shown_match != compl_shown_match->cp_next;
1036}
1037
1038/*
1039 * Return whether the shown match is long enough.
1040 */
1041 int
1042ins_compl_long_shown_match(void)
1043{
1044 return (int)STRLEN(compl_shown_match->cp_str)
1045 > curwin->w_cursor.col - compl_col;
1046}
1047
1048/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001049 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001050 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001051 unsigned int
1052get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001053{
zeertzjq529b9ad2024-06-05 20:27:06 +02001054 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001055}
1056
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001057
1058// "compl_match_array" points the currently displayed list of entries in the
1059// popup menu. It is NULL when there is no popup menu.
1060static pumitem_T *compl_match_array = NULL;
1061static int compl_match_arraysize;
1062
1063/*
1064 * Update the screen and when there is any scrolling remove the popup menu.
1065 */
1066 static void
1067ins_compl_upd_pum(void)
1068{
1069 int h;
1070
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001071 if (compl_match_array == NULL)
1072 return;
1073
1074 h = curwin->w_cline_height;
1075 // Update the screen later, before drawing the popup menu over it.
1076 pum_call_update_screen();
1077 if (h != curwin->w_cline_height)
1078 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001079}
1080
1081/*
1082 * Remove any popup menu.
1083 */
1084 static void
1085ins_compl_del_pum(void)
1086{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001087 if (compl_match_array == NULL)
1088 return;
1089
1090 pum_undisplay();
1091 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001092}
1093
1094/*
1095 * Return TRUE if the popup menu should be displayed.
1096 */
1097 int
1098pum_wanted(void)
1099{
1100 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001101 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001102 return FALSE;
1103
1104 // The display looks bad on a B&W display.
1105 if (t_colors < 8
1106#ifdef FEAT_GUI
1107 && !gui.in_use
1108#endif
1109 )
1110 return FALSE;
1111 return TRUE;
1112}
1113
1114/*
1115 * Return TRUE if there are two or more matches to be shown in the popup menu.
1116 * One if 'completopt' contains "menuone".
1117 */
1118 static int
1119pum_enough_matches(void)
1120{
1121 compl_T *compl;
1122 int i;
1123
1124 // Don't display the popup menu if there are no matches or there is only
1125 // one (ignoring the original text).
1126 compl = compl_first_match;
1127 i = 0;
1128 do
1129 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001130 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001131 break;
1132 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001133 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134
zeertzjq529b9ad2024-06-05 20:27:06 +02001135 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001136 return (i >= 1);
1137 return (i >= 2);
1138}
1139
Bram Moolenaar3075a452021-11-17 15:51:52 +00001140#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001141/*
1142 * Allocate Dict for the completed item.
1143 * { word, abbr, menu, kind, info }
1144 */
1145 static dict_T *
1146ins_compl_dict_alloc(compl_T *match)
1147{
1148 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1149
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001150 if (dict == NULL)
1151 return NULL;
1152
1153 dict_add_string(dict, "word", match->cp_str);
1154 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1155 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1156 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1157 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1158 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1159 dict_add_string(dict, "user_data", (char_u *)"");
1160 else
1161 dict_add_tv(dict, "user_data", &match->cp_user_data);
1162
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001163 return dict;
1164}
1165
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001166/*
1167 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1168 * completion menu is changed.
1169 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001170 static void
1171trigger_complete_changed_event(int cur)
1172{
1173 dict_T *v_event;
1174 dict_T *item;
1175 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001176 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001177
1178 if (recursive)
1179 return;
1180
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001181 if (cur < 0)
1182 item = dict_alloc();
1183 else
1184 item = ins_compl_dict_alloc(compl_curr_match);
1185 if (item == NULL)
1186 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001187 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001188 dict_add_dict(v_event, "completed_item", item);
1189 pum_set_event_info(v_event);
1190 dict_set_items_ro(v_event);
1191
1192 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001193 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001194 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001195 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001196 recursive = FALSE;
1197
Bram Moolenaar3075a452021-11-17 15:51:52 +00001198 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001199}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001200#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001201
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001202/*
glepnira218cc62024-06-03 19:32:39 +02001203 * pumitem qsort compare func
1204 */
1205 static int
zeertzjq8e567472024-06-14 20:04:42 +02001206ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001207{
1208 const int sa = (*(pumitem_T *)a).pum_score;
1209 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001210 const int ia = (*(pumitem_T *)a).pum_idx;
1211 const int ib = (*(pumitem_T *)b).pum_idx;
1212 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001213}
1214
1215/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001216 * Build a popup menu to show the completion matches.
1217 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1218 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001219 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001220 static int
1221ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001222{
1223 compl_T *compl;
1224 compl_T *shown_compl = NULL;
glepnirf94c9c42024-06-14 21:11:56 +02001225 compl_T *after_first_compl = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001226 int did_find_shown_match = FALSE;
1227 int shown_match_ok = FALSE;
1228 int i;
1229 int cur = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001230 int lead_len = 0;
glepnira218cc62024-06-03 19:32:39 +02001231 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001232 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001233 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1234 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001235
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001236 // Need to build the popup menu list.
1237 compl_match_arraysize = 0;
1238 compl = compl_first_match;
1239 if (compl_leader != NULL)
1240 lead_len = (int)STRLEN(compl_leader);
1241
1242 do
1243 {
zeertzjq551d8c32024-06-05 19:53:32 +02001244 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1245 // set the cp_score for later comparisons.
glepnira218cc62024-06-03 19:32:39 +02001246 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1247 compl->cp_score = fuzzy_match_str(compl->cp_str, compl_leader);
1248
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001249 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001250 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001251 || ins_compl_equal(compl, compl_leader, lead_len)
1252 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001253 ++compl_match_arraysize;
1254 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001255 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001256
1257 if (compl_match_arraysize == 0)
1258 return -1;
1259
1260 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1261 if (compl_match_array == NULL)
1262 return -1;
1263
1264 // If the current match is the original text don't find the first
1265 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001266 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001267 shown_match_ok = TRUE;
1268
glepnir53387c52024-05-27 15:11:01 +02001269 if (compl_leader != NULL
1270 && STRCMP(compl_leader, compl_orig_text) == 0
1271 && shown_match_ok == FALSE)
1272 compl_shown_match = compl_no_select ? compl_first_match
1273 : compl_first_match->cp_next;
1274
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001275 i = 0;
1276 compl = compl_first_match;
1277 do
1278 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001279 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001280 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001281 || ins_compl_equal(compl, compl_leader, lead_len)
1282 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001283 {
glepnira218cc62024-06-03 19:32:39 +02001284 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001285 {
1286 if (compl == compl_shown_match || did_find_shown_match)
1287 {
1288 // This item is the shown match or this is the
1289 // first displayed item after the shown match.
1290 compl_shown_match = compl;
1291 did_find_shown_match = TRUE;
1292 shown_match_ok = TRUE;
1293 }
1294 else
1295 // Remember this displayed match for when the
1296 // shown match is just below it.
1297 shown_compl = compl;
1298 cur = i;
1299 }
glepnira218cc62024-06-03 19:32:39 +02001300 else if (compl_fuzzy_match)
1301 {
glepnirf94c9c42024-06-14 21:11:56 +02001302 if (i == 0)
1303 after_first_compl = compl;
glepnirdca57fb2024-06-04 22:01:21 +02001304 // Update the maximum fuzzy score and the shown match
1305 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001306 if (compl->cp_score > max_fuzzy_score)
1307 {
1308 did_find_shown_match = TRUE;
1309 max_fuzzy_score = compl->cp_score;
1310 compl_shown_match = compl;
1311 shown_match_ok = TRUE;
1312 }
1313
glepnirdca57fb2024-06-04 22:01:21 +02001314 // If there is no "no select" condition and the max fuzzy
1315 // score is positive, or there is no completion leader or the
1316 // leader length is zero, mark the shown match as valid and
1317 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001318 if (!compl_no_select
1319 && (max_fuzzy_score > 0
1320 || (compl_leader == NULL || lead_len == 0)))
1321 {
1322 shown_match_ok = TRUE;
1323 cur = 0;
glepnirf94c9c42024-06-14 21:11:56 +02001324 if (match_at_original_text(compl_shown_match))
1325 compl_shown_match = after_first_compl;
glepnira218cc62024-06-03 19:32:39 +02001326 }
1327 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001328
1329 if (compl->cp_text[CPT_ABBR] != NULL)
1330 compl_match_array[i].pum_text =
1331 compl->cp_text[CPT_ABBR];
1332 else
1333 compl_match_array[i].pum_text = compl->cp_str;
1334 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1335 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001336 compl_match_array[i].pum_score = compl->cp_score;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001337 if (compl->cp_text[CPT_MENU] != NULL)
1338 compl_match_array[i++].pum_extra =
1339 compl->cp_text[CPT_MENU];
1340 else
1341 compl_match_array[i++].pum_extra = compl->cp_fname;
1342 }
1343
glepnira218cc62024-06-03 19:32:39 +02001344 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001345 {
1346 did_find_shown_match = TRUE;
1347
1348 // When the original text is the shown match don't set
1349 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001350 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001351 shown_match_ok = TRUE;
1352
1353 if (!shown_match_ok && shown_compl != NULL)
1354 {
1355 // The shown match isn't displayed, set it to the
1356 // previously displayed match.
1357 compl_shown_match = shown_compl;
1358 shown_match_ok = TRUE;
1359 }
1360 }
1361 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001362 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001363
glepnira218cc62024-06-03 19:32:39 +02001364 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001365 {
1366 for (i = 0; i < compl_match_arraysize; i++)
1367 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001368 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001369 qsort(compl_match_array, (size_t)compl_match_arraysize,
1370 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
1371 }
glepnira218cc62024-06-03 19:32:39 +02001372
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001373 if (!shown_match_ok) // no displayed match at all
1374 cur = -1;
1375
1376 return cur;
1377}
1378
1379/*
1380 * Show the popup menu for the list of matches.
1381 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1382 */
1383 void
1384ins_compl_show_pum(void)
1385{
1386 int i;
1387 int cur = -1;
1388 colnr_T col;
1389
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001390 if (!pum_wanted() || !pum_enough_matches())
1391 return;
1392
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001393 // Update the screen later, before drawing the popup menu over it.
1394 pum_call_update_screen();
1395
1396 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001397 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001398 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001399 else
1400 {
1401 // popup menu already exists, only need to find the current item.
1402 for (i = 0; i < compl_match_arraysize; ++i)
1403 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1404 || compl_match_array[i].pum_text
1405 == compl_shown_match->cp_text[CPT_ABBR])
1406 {
1407 cur = i;
1408 break;
1409 }
1410 }
1411
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001412 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001413 {
1414#ifdef FEAT_EVAL
1415 if (compl_started && has_completechanged())
1416 trigger_complete_changed_event(cur);
1417#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001418 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001419 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001420
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001421 // In Replace mode when a $ is displayed at the end of the line only
1422 // part of the screen would be updated. We do need to redraw here.
1423 dollar_vcol = -1;
1424
1425 // Compute the screen column of the start of the completed text.
1426 // Use the cursor to get all wrapping and other settings right.
1427 col = curwin->w_cursor.col;
1428 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001429 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001430 pum_display(compl_match_array, compl_match_arraysize, cur);
1431 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001432
glepnircbb46b42024-02-03 18:11:13 +01001433 // After adding leader, set the current match to shown match.
1434 if (compl_started && compl_curr_match != compl_shown_match)
1435 compl_curr_match = compl_shown_match;
1436
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001437#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001438 if (has_completechanged())
1439 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001440#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001441}
1442
1443#define DICT_FIRST (1) // use just first element in "dict"
1444#define DICT_EXACT (2) // "dict" is the exact name of a file
1445
1446/*
glepnir40c1c332024-06-11 19:37:04 +02001447 * Get current completion leader
1448 */
1449 char_u *
1450ins_compl_leader(void)
1451{
1452 return compl_leader;
1453}
1454
1455/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001456 * Add any identifiers that match the given pattern "pat" in the list of
1457 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001458 */
1459 static void
1460ins_compl_dictionaries(
1461 char_u *dict_start,
1462 char_u *pat,
1463 int flags, // DICT_FIRST and/or DICT_EXACT
1464 int thesaurus) // Thesaurus completion
1465{
1466 char_u *dict = dict_start;
1467 char_u *ptr;
1468 char_u *buf;
1469 regmatch_T regmatch;
1470 char_u **files;
1471 int count;
1472 int save_p_scs;
1473 int dir = compl_direction;
1474
1475 if (*dict == NUL)
1476 {
1477#ifdef FEAT_SPELL
1478 // When 'dictionary' is empty and spell checking is enabled use
1479 // "spell".
1480 if (!thesaurus && curwin->w_p_spell)
1481 dict = (char_u *)"spell";
1482 else
1483#endif
1484 return;
1485 }
1486
1487 buf = alloc(LSIZE);
1488 if (buf == NULL)
1489 return;
1490 regmatch.regprog = NULL; // so that we can goto theend
1491
1492 // If 'infercase' is set, don't use 'smartcase' here
1493 save_p_scs = p_scs;
1494 if (curbuf->b_p_inf)
1495 p_scs = FALSE;
1496
1497 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1498 // to only match at the start of a line. Otherwise just match the
1499 // pattern. Also need to double backslashes.
1500 if (ctrl_x_mode_line_or_eval())
1501 {
1502 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1503 size_t len;
1504
1505 if (pat_esc == NULL)
1506 goto theend;
1507 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001508 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001509 if (ptr == NULL)
1510 {
1511 vim_free(pat_esc);
1512 goto theend;
1513 }
1514 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1515 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1516 vim_free(pat_esc);
1517 vim_free(ptr);
1518 }
1519 else
1520 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001521 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001522 if (regmatch.regprog == NULL)
1523 goto theend;
1524 }
1525
1526 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1527 regmatch.rm_ic = ignorecase(pat);
1528 while (*dict != NUL && !got_int && !compl_interrupted)
1529 {
1530 // copy one dictionary file name into buf
1531 if (flags == DICT_EXACT)
1532 {
1533 count = 1;
1534 files = &dict;
1535 }
1536 else
1537 {
1538 // Expand wildcards in the dictionary name, but do not allow
1539 // backticks (for security, the 'dict' option may have been set in
1540 // a modeline).
1541 copy_option_part(&dict, buf, LSIZE, ",");
1542# ifdef FEAT_SPELL
1543 if (!thesaurus && STRCMP(buf, "spell") == 0)
1544 count = -1;
1545 else
1546# endif
1547 if (vim_strchr(buf, '`') != NULL
1548 || expand_wildcards(1, &buf, &count, &files,
1549 EW_FILE|EW_SILENT) != OK)
1550 count = 0;
1551 }
1552
1553# ifdef FEAT_SPELL
1554 if (count == -1)
1555 {
1556 // Complete from active spelling. Skip "\<" in the pattern, we
1557 // don't use it as a RE.
1558 if (pat[0] == '\\' && pat[1] == '<')
1559 ptr = pat + 2;
1560 else
1561 ptr = pat;
1562 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1563 }
1564 else
1565# endif
1566 if (count > 0) // avoid warning for using "files" uninit
1567 {
1568 ins_compl_files(count, files, thesaurus, flags,
1569 &regmatch, buf, &dir);
1570 if (flags != DICT_EXACT)
1571 FreeWild(count, files);
1572 }
1573 if (flags != 0)
1574 break;
1575 }
1576
1577theend:
1578 p_scs = save_p_scs;
1579 vim_regfree(regmatch.regprog);
1580 vim_free(buf);
1581}
1582
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001583/*
1584 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1585 * skipping the word at 'skip_word'. Returns OK on success.
1586 */
1587 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001588thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001589 char_u *fname,
1590 char_u **buf_arg,
1591 int dir,
1592 char_u *skip_word)
1593{
1594 int status = OK;
1595 char_u *ptr;
1596 char_u *wstart;
1597
1598 // Add the other matches on the line
1599 ptr = *buf_arg;
1600 while (!got_int)
1601 {
1602 // Find start of the next word. Skip white
1603 // space and punctuation.
1604 ptr = find_word_start(ptr);
1605 if (*ptr == NUL || *ptr == NL)
1606 break;
1607 wstart = ptr;
1608
1609 // Find end of the word.
1610 if (has_mbyte)
1611 // Japanese words may have characters in
1612 // different classes, only separate words
1613 // with single-byte non-word characters.
1614 while (*ptr != NUL)
1615 {
1616 int l = (*mb_ptr2len)(ptr);
1617
1618 if (l < 2 && !vim_iswordc(*ptr))
1619 break;
1620 ptr += l;
1621 }
1622 else
1623 ptr = find_word_end(ptr);
1624
1625 // Add the word. Skip the regexp match.
1626 if (wstart != skip_word)
1627 {
1628 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1629 fname, dir, FALSE);
1630 if (status == FAIL)
1631 break;
1632 }
1633 }
1634
1635 *buf_arg = ptr;
1636 return status;
1637}
1638
1639/*
1640 * Process "count" dictionary/thesaurus "files" and add the text matching
1641 * "regmatch".
1642 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001643 static void
1644ins_compl_files(
1645 int count,
1646 char_u **files,
1647 int thesaurus,
1648 int flags,
1649 regmatch_T *regmatch,
1650 char_u *buf,
1651 int *dir)
1652{
1653 char_u *ptr;
1654 int i;
1655 FILE *fp;
1656 int add_r;
1657
1658 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1659 {
1660 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001661 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001662 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001663 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001664 vim_snprintf((char *)IObuff, IOSIZE,
1665 _("Scanning dictionary: %s"), (char *)files[i]);
1666 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1667 }
1668
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001669 if (fp == NULL)
1670 continue;
1671
1672 // Read dictionary file line by line.
1673 // Check each line for a match.
1674 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001675 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001676 ptr = buf;
1677 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001678 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001679 ptr = regmatch->startp[0];
1680 if (ctrl_x_mode_line_or_eval())
1681 ptr = find_line_end(ptr);
1682 else
1683 ptr = find_word_end(ptr);
1684 add_r = ins_compl_add_infercase(regmatch->startp[0],
1685 (int)(ptr - regmatch->startp[0]),
1686 p_ic, files[i], *dir, FALSE);
1687 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001688 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001689 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001690 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001691 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001692 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001693 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001694 if (add_r == OK)
1695 // if dir was BACKWARD then honor it just once
1696 *dir = FORWARD;
1697 else if (add_r == FAIL)
1698 break;
1699 // avoid expensive call to vim_regexec() when at end
1700 // of line
1701 if (*ptr == '\n' || got_int)
1702 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001703 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001704 line_breakcheck();
1705 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001706 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001707 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001708 }
1709}
1710
1711/*
1712 * Find the start of the next word.
1713 * Returns a pointer to the first char of the word. Also stops at a NUL.
1714 */
1715 char_u *
1716find_word_start(char_u *ptr)
1717{
1718 if (has_mbyte)
1719 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1720 ptr += (*mb_ptr2len)(ptr);
1721 else
1722 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1723 ++ptr;
1724 return ptr;
1725}
1726
1727/*
1728 * Find the end of the word. Assumes it starts inside a word.
1729 * Returns a pointer to just after the word.
1730 */
1731 char_u *
1732find_word_end(char_u *ptr)
1733{
1734 int start_class;
1735
1736 if (has_mbyte)
1737 {
1738 start_class = mb_get_class(ptr);
1739 if (start_class > 1)
1740 while (*ptr != NUL)
1741 {
1742 ptr += (*mb_ptr2len)(ptr);
1743 if (mb_get_class(ptr) != start_class)
1744 break;
1745 }
1746 }
1747 else
1748 while (vim_iswordc(*ptr))
1749 ++ptr;
1750 return ptr;
1751}
1752
1753/*
1754 * Find the end of the line, omitting CR and NL at the end.
1755 * Returns a pointer to just after the line.
1756 */
1757 static char_u *
1758find_line_end(char_u *ptr)
1759{
1760 char_u *s;
1761
1762 s = ptr + STRLEN(ptr);
1763 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1764 --s;
1765 return s;
1766}
1767
1768/*
1769 * Free the list of completions
1770 */
1771 static void
1772ins_compl_free(void)
1773{
1774 compl_T *match;
1775 int i;
1776
1777 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001778 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001779 VIM_CLEAR(compl_leader);
1780
1781 if (compl_first_match == NULL)
1782 return;
1783
1784 ins_compl_del_pum();
1785 pum_clear();
1786
1787 compl_curr_match = compl_first_match;
1788 do
1789 {
1790 match = compl_curr_match;
1791 compl_curr_match = compl_curr_match->cp_next;
1792 vim_free(match->cp_str);
1793 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001794 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001795 vim_free(match->cp_fname);
1796 for (i = 0; i < CPT_COUNT; ++i)
1797 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001798#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001799 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001800#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001801 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001802 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001803 compl_first_match = compl_curr_match = NULL;
1804 compl_shown_match = NULL;
1805 compl_old_match = NULL;
1806}
1807
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001808/*
1809 * Reset/clear the completion state.
1810 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001811 void
1812ins_compl_clear(void)
1813{
1814 compl_cont_status = 0;
1815 compl_started = FALSE;
1816 compl_matches = 0;
1817 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001818 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001819 VIM_CLEAR(compl_leader);
1820 edit_submode_extra = NULL;
1821 VIM_CLEAR(compl_orig_text);
1822 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001823#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001824 // clear v:completed_item
1825 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001826#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001827}
1828
1829/*
1830 * Return TRUE when Insert completion is active.
1831 */
1832 int
1833ins_compl_active(void)
1834{
1835 return compl_started;
1836}
1837
1838/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001839 * Selected one of the matches. When FALSE the match was edited or using the
1840 * longest common string.
1841 */
1842 int
1843ins_compl_used_match(void)
1844{
1845 return compl_used_match;
1846}
1847
1848/*
1849 * Initialize get longest common string.
1850 */
1851 void
1852ins_compl_init_get_longest(void)
1853{
1854 compl_get_longest = FALSE;
1855}
1856
1857/*
1858 * Returns TRUE when insert completion is interrupted.
1859 */
1860 int
1861ins_compl_interrupted(void)
1862{
1863 return compl_interrupted;
1864}
1865
1866/*
1867 * Returns TRUE if the <Enter> key selects a match in the completion popup
1868 * menu.
1869 */
1870 int
1871ins_compl_enter_selects(void)
1872{
1873 return compl_enter_selects;
1874}
1875
1876/*
1877 * Return the column where the text starts that is being completed
1878 */
1879 colnr_T
1880ins_compl_col(void)
1881{
1882 return compl_col;
1883}
1884
1885/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001886 * Return the length in bytes of the text being completed
1887 */
1888 int
1889ins_compl_len(void)
1890{
1891 return compl_length;
1892}
1893
1894/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001895 * Delete one character before the cursor and show the subset of the matches
1896 * that match the word that is now before the cursor.
1897 * Returns the character to be used, NUL if the work is done and another char
1898 * to be got from the user.
1899 */
1900 int
1901ins_compl_bs(void)
1902{
1903 char_u *line;
1904 char_u *p;
1905
1906 line = ml_get_curline();
1907 p = line + curwin->w_cursor.col;
1908 MB_PTR_BACK(line, p);
1909
1910 // Stop completion when the whole word was deleted. For Omni completion
1911 // allow the word to be deleted, we won't match everything.
1912 // Respect the 'backspace' option.
1913 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001914 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1915 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001916 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1917 - compl_length < 0))
1918 return K_BS;
1919
1920 // Deleted more than what was used to find matches or didn't finish
1921 // finding all matches: need to look for matches all over again.
1922 if (curwin->w_cursor.col <= compl_col + compl_length
1923 || ins_compl_need_restart())
1924 ins_compl_restart();
1925
1926 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001927 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001928 if (compl_leader == NULL)
1929 return K_BS;
1930
1931 ins_compl_new_leader();
1932 if (compl_shown_match != NULL)
1933 // Make sure current match is not a hidden item.
1934 compl_curr_match = compl_shown_match;
1935 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001936}
1937
1938/*
1939 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1940 * be called.
1941 */
1942 static int
1943ins_compl_need_restart(void)
1944{
1945 // Return TRUE if we didn't complete finding matches or when the
1946 // 'completefunc' returned "always" in the "refresh" dictionary item.
1947 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001948 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001949 && compl_opt_refresh_always);
1950}
1951
1952/*
1953 * Called after changing "compl_leader".
1954 * Show the popup menu with a different set of matches.
1955 * May also search for matches again if the previous search was interrupted.
1956 */
1957 static void
1958ins_compl_new_leader(void)
1959{
1960 ins_compl_del_pum();
1961 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001962 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001963 compl_used_match = FALSE;
1964
1965 if (compl_started)
1966 ins_compl_set_original_text(compl_leader);
1967 else
1968 {
1969#ifdef FEAT_SPELL
1970 spell_bad_len = 0; // need to redetect bad word
1971#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001972 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001973 // the popup menu display the changed text before the cursor. Set
1974 // "compl_restarting" to avoid that the first match is inserted.
1975 pum_call_update_screen();
1976#ifdef FEAT_GUI
1977 if (gui.in_use)
1978 {
1979 // Show the cursor after the match, not after the redrawn text.
1980 setcursor();
1981 out_flush_cursor(FALSE, FALSE);
1982 }
1983#endif
1984 compl_restarting = TRUE;
1985 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1986 compl_cont_status = 0;
1987 compl_restarting = FALSE;
1988 }
1989
1990 compl_enter_selects = !compl_used_match;
1991
1992 // Show the popup menu with a different set of matches.
1993 ins_compl_show_pum();
1994
1995 // Don't let Enter select the original text when there is no popup menu.
1996 if (compl_match_array == NULL)
1997 compl_enter_selects = FALSE;
1998}
1999
2000/*
2001 * Return the length of the completion, from the completion start column to
2002 * the cursor column. Making sure it never goes below zero.
2003 */
2004 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002005get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002006{
2007 int off = (int)curwin->w_cursor.col - (int)compl_col;
2008
2009 if (off < 0)
2010 return 0;
2011 return off;
2012}
2013
2014/*
2015 * Append one character to the match leader. May reduce the number of
2016 * matches.
2017 */
2018 void
2019ins_compl_addleader(int c)
2020{
2021 int cc;
2022
2023 if (stop_arrow() == FAIL)
2024 return;
2025 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2026 {
2027 char_u buf[MB_MAXBYTES + 1];
2028
2029 (*mb_char2bytes)(c, buf);
2030 buf[cc] = NUL;
2031 ins_char_bytes(buf, cc);
2032 if (compl_opt_refresh_always)
2033 AppendToRedobuff(buf);
2034 }
2035 else
2036 {
2037 ins_char(c);
2038 if (compl_opt_refresh_always)
2039 AppendCharToRedobuff(c);
2040 }
2041
2042 // If we didn't complete finding matches we must search again.
2043 if (ins_compl_need_restart())
2044 ins_compl_restart();
2045
2046 // When 'always' is set, don't reset compl_leader. While completing,
2047 // cursor doesn't point original position, changing compl_leader would
2048 // break redo.
2049 if (!compl_opt_refresh_always)
2050 {
2051 vim_free(compl_leader);
2052 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002053 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002054 if (compl_leader != NULL)
2055 ins_compl_new_leader();
2056 }
2057}
2058
2059/*
2060 * Setup for finding completions again without leaving CTRL-X mode. Used when
2061 * BS or a key was typed while still searching for matches.
2062 */
2063 static void
2064ins_compl_restart(void)
2065{
2066 ins_compl_free();
2067 compl_started = FALSE;
2068 compl_matches = 0;
2069 compl_cont_status = 0;
2070 compl_cont_mode = 0;
2071}
2072
2073/*
2074 * Set the first match, the original text.
2075 */
2076 static void
2077ins_compl_set_original_text(char_u *str)
2078{
2079 char_u *p;
2080
2081 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002082 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2083 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002084 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002085 {
2086 p = vim_strsave(str);
2087 if (p != NULL)
2088 {
2089 vim_free(compl_first_match->cp_str);
2090 compl_first_match->cp_str = p;
2091 }
2092 }
2093 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002094 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002095 {
2096 p = vim_strsave(str);
2097 if (p != NULL)
2098 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002099 vim_free(compl_first_match->cp_prev->cp_str);
2100 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002101 }
2102 }
2103}
2104
2105/*
2106 * Append one character to the match leader. May reduce the number of
2107 * matches.
2108 */
2109 void
2110ins_compl_addfrommatch(void)
2111{
2112 char_u *p;
2113 int len = (int)curwin->w_cursor.col - (int)compl_col;
2114 int c;
2115 compl_T *cp;
2116
2117 p = compl_shown_match->cp_str;
2118 if ((int)STRLEN(p) <= len) // the match is too short
2119 {
2120 // When still at the original match use the first entry that matches
2121 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002122 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002123 return;
2124
2125 p = NULL;
2126 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002127 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002128 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002129 if (compl_leader == NULL
2130 || ins_compl_equal(cp, compl_leader,
2131 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002132 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002133 p = cp->cp_str;
2134 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002135 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002136 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002137 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002138 return;
2139 }
2140 p += len;
2141 c = PTR2CHAR(p);
2142 ins_compl_addleader(c);
2143}
2144
2145/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002146 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002147 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2148 * compl_cont_mode and compl_cont_status.
2149 * Returns TRUE when the character is not to be inserted.
2150 */
2151 static int
2152set_ctrl_x_mode(int c)
2153{
2154 int retval = FALSE;
2155
2156 switch (c)
2157 {
2158 case Ctrl_E:
2159 case Ctrl_Y:
2160 // scroll the window one line up or down
2161 ctrl_x_mode = CTRL_X_SCROLL;
2162 if (!(State & REPLACE_FLAG))
2163 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2164 else
2165 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2166 edit_submode_pre = NULL;
2167 showmode();
2168 break;
2169 case Ctrl_L:
2170 // complete whole line
2171 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2172 break;
2173 case Ctrl_F:
2174 // complete filenames
2175 ctrl_x_mode = CTRL_X_FILES;
2176 break;
2177 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002178 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002179 ctrl_x_mode = CTRL_X_DICTIONARY;
2180 break;
2181 case Ctrl_R:
2182 // Register insertion without exiting CTRL-X mode
2183 // Simply allow ^R to happen without affecting ^X mode
2184 break;
2185 case Ctrl_T:
2186 // complete words from a thesaurus
2187 ctrl_x_mode = CTRL_X_THESAURUS;
2188 break;
2189#ifdef FEAT_COMPL_FUNC
2190 case Ctrl_U:
2191 // user defined completion
2192 ctrl_x_mode = CTRL_X_FUNCTION;
2193 break;
2194 case Ctrl_O:
2195 // omni completion
2196 ctrl_x_mode = CTRL_X_OMNI;
2197 break;
2198#endif
2199 case 's':
2200 case Ctrl_S:
2201 // complete spelling suggestions
2202 ctrl_x_mode = CTRL_X_SPELL;
2203#ifdef FEAT_SPELL
2204 ++emsg_off; // Avoid getting the E756 error twice.
2205 spell_back_to_badword();
2206 --emsg_off;
2207#endif
2208 break;
2209 case Ctrl_RSB:
2210 // complete tag names
2211 ctrl_x_mode = CTRL_X_TAGS;
2212 break;
2213#ifdef FEAT_FIND_ID
2214 case Ctrl_I:
2215 case K_S_TAB:
2216 // complete keywords from included files
2217 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2218 break;
2219 case Ctrl_D:
2220 // complete definitions from included files
2221 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2222 break;
2223#endif
2224 case Ctrl_V:
2225 case Ctrl_Q:
2226 // complete vim commands
2227 ctrl_x_mode = CTRL_X_CMDLINE;
2228 break;
2229 case Ctrl_Z:
2230 // stop completion
2231 ctrl_x_mode = CTRL_X_NORMAL;
2232 edit_submode = NULL;
2233 showmode();
2234 retval = TRUE;
2235 break;
2236 case Ctrl_P:
2237 case Ctrl_N:
2238 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2239 // just started ^X mode, or there were enough ^X's to cancel
2240 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2241 // do normal expansion when interrupting a different mode (say
2242 // ^X^F^X^P or ^P^X^X^P, see below)
2243 // nothing changes if interrupting mode 0, (eg, the flag
2244 // doesn't change when going to ADDING mode -- Acevedo
2245 if (!(compl_cont_status & CONT_INTRPT))
2246 compl_cont_status |= CONT_LOCAL;
2247 else if (compl_cont_mode != 0)
2248 compl_cont_status &= ~CONT_LOCAL;
2249 // FALLTHROUGH
2250 default:
2251 // If we have typed at least 2 ^X's... for modes != 0, we set
2252 // compl_cont_status = 0 (eg, as if we had just started ^X
2253 // mode).
2254 // For mode 0, we set "compl_cont_mode" to an impossible
2255 // value, in both cases ^X^X can be used to restart the same
2256 // mode (avoiding ADDING mode).
2257 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2258 // 'complete' and local ^P expansions respectively.
2259 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2260 // mode -- Acevedo
2261 if (c == Ctrl_X)
2262 {
2263 if (compl_cont_mode != 0)
2264 compl_cont_status = 0;
2265 else
2266 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2267 }
2268 ctrl_x_mode = CTRL_X_NORMAL;
2269 edit_submode = NULL;
2270 showmode();
2271 break;
2272 }
2273
2274 return retval;
2275}
2276
2277/*
2278 * Stop insert completion mode
2279 */
2280 static int
2281ins_compl_stop(int c, int prev_mode, int retval)
2282{
2283 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002284 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002285
2286 // Get here when we have finished typing a sequence of ^N and
2287 // ^P or other completion characters in CTRL-X mode. Free up
2288 // memory that was used, and make sure we can redo the insert.
2289 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2290 {
2291 // If any of the original typed text has been changed, eg when
2292 // ignorecase is set, we must add back-spaces to the redo
2293 // buffer. We add as few as necessary to delete just the part
2294 // of the original text that has changed.
2295 // When using the longest match, edited the match or used
2296 // CTRL-E then don't use the current match.
2297 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2298 ptr = compl_curr_match->cp_str;
2299 else
2300 ptr = NULL;
2301 ins_compl_fixRedoBufForLeader(ptr);
2302 }
2303
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002304 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002305
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002306 // When completing whole lines: fix indent for 'cindent'.
2307 // Otherwise, break line if it's too long.
2308 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2309 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002310 // re-indent the current line
2311 if (want_cindent)
2312 {
2313 do_c_expr_indent();
2314 want_cindent = FALSE; // don't do it again
2315 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002316 }
2317 else
2318 {
2319 int prev_col = curwin->w_cursor.col;
2320
2321 // put the cursor on the last char, for 'tw' formatting
2322 if (prev_col > 0)
2323 dec_cursor();
2324 // only format when something was inserted
2325 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2326 insertchar(NUL, 0, -1);
2327 if (prev_col > 0
2328 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2329 inc_cursor();
2330 }
2331
2332 // If the popup menu is displayed pressing CTRL-Y means accepting
2333 // the selection without inserting anything. When
2334 // compl_enter_selects is set the Enter key does the same.
2335 if ((c == Ctrl_Y || (compl_enter_selects
2336 && (c == CAR || c == K_KENTER || c == NL)))
2337 && pum_visible())
2338 retval = TRUE;
2339
2340 // CTRL-E means completion is Ended, go back to the typed text.
2341 // but only do this, if the Popup is still visible
2342 if (c == Ctrl_E)
2343 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002344 char_u *p = NULL;
2345
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002346 ins_compl_delete();
2347 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002348 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002349 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002350 p = compl_orig_text;
2351 if (p != NULL)
2352 {
2353 int compl_len = get_compl_len();
2354 int len = (int)STRLEN(p);
2355
2356 if (len > compl_len)
2357 ins_bytes_len(p + compl_len, len - compl_len);
2358 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002359 retval = TRUE;
2360 }
2361
2362 auto_format(FALSE, TRUE);
2363
2364 // Trigger the CompleteDonePre event to give scripts a chance to
2365 // act upon the completion before clearing the info, and restore
2366 // ctrl_x_mode, so that complete_info() can be used.
2367 ctrl_x_mode = prev_mode;
2368 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2369
2370 ins_compl_free();
2371 compl_started = FALSE;
2372 compl_matches = 0;
2373 if (!shortmess(SHM_COMPLETIONMENU))
2374 msg_clr_cmdline(); // necessary for "noshowmode"
2375 ctrl_x_mode = CTRL_X_NORMAL;
2376 compl_enter_selects = FALSE;
2377 if (edit_submode != NULL)
2378 {
2379 edit_submode = NULL;
2380 showmode();
2381 }
2382
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002383 if (c == Ctrl_C && cmdwin_type != 0)
2384 // Avoid the popup menu remains displayed when leaving the
2385 // command line window.
2386 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002387 // Indent now if a key was typed that is in 'cinkeys'.
2388 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2389 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002390 // Trigger the CompleteDone event to give scripts a chance to act
2391 // upon the end of completion.
2392 ins_apply_autocmds(EVENT_COMPLETEDONE);
2393
2394 return retval;
2395}
2396
2397/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002398 * Prepare for Insert mode completion, or stop it.
2399 * Called just after typing a character in Insert mode.
2400 * Returns TRUE when the character is not to be inserted;
2401 */
2402 int
2403ins_compl_prep(int c)
2404{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002405 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002406 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002407
2408 // Forget any previous 'special' messages if this is actually
2409 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2410 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2411 edit_submode_extra = NULL;
2412
zeertzjq440d4cb2023-03-02 17:51:32 +00002413 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002414 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002415 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002416 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002417 return retval;
2418
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002419#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002420 // Ignore mouse events in a popup window
2421 if (is_mouse_key(c))
2422 {
2423 // Ignore drag and release events, the position does not need to be in
2424 // the popup and it may have just closed.
2425 if (c == K_LEFTRELEASE
2426 || c == K_LEFTRELEASE_NM
2427 || c == K_MIDDLERELEASE
2428 || c == K_RIGHTRELEASE
2429 || c == K_X1RELEASE
2430 || c == K_X2RELEASE
2431 || c == K_LEFTDRAG
2432 || c == K_MIDDLEDRAG
2433 || c == K_RIGHTDRAG
2434 || c == K_X1DRAG
2435 || c == K_X2DRAG)
2436 return retval;
2437 if (popup_visible)
2438 {
2439 int row = mouse_row;
2440 int col = mouse_col;
2441 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2442
2443 if (wp != NULL && WIN_IS_POPUP(wp))
2444 return retval;
2445 }
2446 }
2447#endif
2448
zeertzjqdca29d92021-08-31 19:12:51 +02002449 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2450 {
2451 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2452 || !vim_is_ctrl_x_key(c))
2453 {
2454 // Not starting another completion mode.
2455 ctrl_x_mode = CTRL_X_CMDLINE;
2456
2457 // CTRL-X CTRL-Z should stop completion without inserting anything
2458 if (c == Ctrl_Z)
2459 retval = TRUE;
2460 }
2461 else
2462 {
2463 ctrl_x_mode = CTRL_X_CMDLINE;
2464
2465 // Other CTRL-X keys first stop completion, then start another
2466 // completion mode.
2467 ins_compl_prep(' ');
2468 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2469 }
2470 }
2471
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002472 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002473 if (ctrl_x_mode_not_defined_yet()
2474 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002475 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002476 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002477 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002478 }
2479
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002480 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002481 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2482 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002483 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002484 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002485 {
2486 // We're already in CTRL-X mode, do we stay in it?
2487 if (!vim_is_ctrl_x_key(c))
2488 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002489 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002490 ctrl_x_mode = CTRL_X_NORMAL;
2491 else
2492 ctrl_x_mode = CTRL_X_FINISHED;
2493 edit_submode = NULL;
2494 }
2495 showmode();
2496 }
2497
2498 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2499 {
2500 // Show error message from attempted keyword completion (probably
2501 // 'Pattern not found') until another key is hit, then go back to
2502 // showing what mode we are in.
2503 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002504 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002505 && c != Ctrl_R && !ins_compl_pum_key(c))
2506 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002507 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002508 }
2509 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2510 // Trigger the CompleteDone event to give scripts a chance to act
2511 // upon the (possibly failed) completion.
2512 ins_apply_autocmds(EVENT_COMPLETEDONE);
2513
LemonBoy2bf52dd2022-04-09 18:17:34 +01002514 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002515
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002516 // reset continue_* if we left expansion-mode, if we stay they'll be
2517 // (re)set properly in ins_complete()
2518 if (!vim_is_ctrl_x_key(c))
2519 {
2520 compl_cont_status = 0;
2521 compl_cont_mode = 0;
2522 }
2523
2524 return retval;
2525}
2526
2527/*
2528 * Fix the redo buffer for the completion leader replacing some of the typed
2529 * text. This inserts backspaces and appends the changed text.
2530 * "ptr" is the known leader text or NUL.
2531 */
2532 static void
2533ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2534{
2535 int len;
2536 char_u *p;
2537 char_u *ptr = ptr_arg;
2538
2539 if (ptr == NULL)
2540 {
2541 if (compl_leader != NULL)
2542 ptr = compl_leader;
2543 else
2544 return; // nothing to do
2545 }
2546 if (compl_orig_text != NULL)
2547 {
2548 p = compl_orig_text;
2549 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2550 ;
2551 if (len > 0)
2552 len -= (*mb_head_off)(p, p + len);
2553 for (p += len; *p != NUL; MB_PTR_ADV(p))
2554 AppendCharToRedobuff(K_BS);
2555 }
2556 else
2557 len = 0;
2558 if (ptr != NULL)
2559 AppendToRedobuffLit(ptr + len, -1);
2560}
2561
2562/*
2563 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2564 * (depending on flag) starting from buf and looking for a non-scanned
2565 * buffer (other than curbuf). curbuf is special, if it is called with
2566 * buf=curbuf then it has to be the first call for a given flag/expansion.
2567 *
2568 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2569 */
2570 static buf_T *
2571ins_compl_next_buf(buf_T *buf, int flag)
2572{
2573 static win_T *wp = NULL;
2574
2575 if (flag == 'w') // just windows
2576 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002577 if (buf == curbuf || !win_valid(wp))
2578 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002579 wp = curwin;
2580 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2581 && wp->w_buffer->b_scanned)
2582 ;
2583 buf = wp->w_buffer;
2584 }
2585 else
2586 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2587 // (unlisted buffers)
2588 // When completing whole lines skip unloaded buffers.
2589 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2590 && ((flag == 'U'
2591 ? buf->b_p_bl
2592 : (!buf->b_p_bl
2593 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2594 || buf->b_scanned))
2595 ;
2596 return buf;
2597}
2598
2599#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002600
2601# ifdef FEAT_EVAL
2602static callback_T cfu_cb; // 'completefunc' callback function
2603static callback_T ofu_cb; // 'omnifunc' callback function
2604static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2605# endif
2606
2607/*
2608 * Copy a global callback function to a buffer local callback.
2609 */
2610 static void
2611copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2612{
2613 free_callback(bufcb);
2614 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2615 copy_callback(bufcb, globcb);
2616}
2617
2618/*
2619 * Parse the 'completefunc' option value and set the callback function.
2620 * Invoked when the 'completefunc' option is set. The option value can be a
2621 * name of a function (string), or function(<name>) or funcref(<name>) or a
2622 * lambda expression.
2623 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002624 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002625did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002626{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002627 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2628 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002629
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002630 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002631
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002632 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002633}
2634
2635/*
2636 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002637 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002638 */
2639 void
2640set_buflocal_cfu_callback(buf_T *buf UNUSED)
2641{
2642# ifdef FEAT_EVAL
2643 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2644# endif
2645}
2646
2647/*
2648 * Parse the 'omnifunc' option value and set the callback function.
2649 * Invoked when the 'omnifunc' option is set. The option value can be a
2650 * name of a function (string), or function(<name>) or funcref(<name>) or a
2651 * lambda expression.
2652 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002653 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002654did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002655{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002656 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2657 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002658
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002659 set_buflocal_ofu_callback(curbuf);
2660 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002661}
2662
2663/*
2664 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002665 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002666 */
2667 void
2668set_buflocal_ofu_callback(buf_T *buf UNUSED)
2669{
2670# ifdef FEAT_EVAL
2671 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2672# endif
2673}
2674
2675/*
2676 * Parse the 'thesaurusfunc' option value and set the callback function.
2677 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2678 * name of a function (string), or function(<name>) or funcref(<name>) or a
2679 * lambda expression.
2680 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002681 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002682did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002683{
2684 int retval;
2685
2686 if (*curbuf->b_p_tsrfu != NUL)
2687 {
2688 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002689 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2690 &curbuf->b_tsrfu_cb);
2691 }
2692 else
2693 {
2694 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002695 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2696 }
2697
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002698 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002699}
2700
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002701/*
2702 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002703 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002704 */
2705 int
2706set_ref_in_insexpand_funcs(int copyID)
2707{
2708 int abort = FALSE;
2709
2710 abort = set_ref_in_callback(&cfu_cb, copyID);
2711 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2712 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2713
2714 return abort;
2715}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002716
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002717/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002718 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002719 */
2720 static char_u *
2721get_complete_funcname(int type)
2722{
2723 switch (type)
2724 {
2725 case CTRL_X_FUNCTION:
2726 return curbuf->b_p_cfu;
2727 case CTRL_X_OMNI:
2728 return curbuf->b_p_ofu;
2729 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002730 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002731 default:
2732 return (char_u *)"";
2733 }
2734}
2735
2736/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002737 * Get the callback to use for insert mode completion.
2738 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002739 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002740get_insert_callback(int type)
2741{
2742 if (type == CTRL_X_FUNCTION)
2743 return &curbuf->b_cfu_cb;
2744 if (type == CTRL_X_OMNI)
2745 return &curbuf->b_ofu_cb;
2746 // CTRL_X_THESAURUS
2747 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2748}
2749
2750/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002751 * Execute user defined complete function 'completefunc', 'omnifunc' or
2752 * 'thesaurusfunc', and get matches in "matches".
2753 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002754 */
2755 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002756expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002757{
2758 list_T *matchlist = NULL;
2759 dict_T *matchdict = NULL;
2760 typval_T args[3];
2761 char_u *funcname;
2762 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002763 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002764 typval_T rettv;
2765 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002766 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002767
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002768 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002769 if (*funcname == NUL)
2770 return;
2771
2772 // Call 'completefunc' to obtain the list of matches.
2773 args[0].v_type = VAR_NUMBER;
2774 args[0].vval.v_number = 0;
2775 args[1].v_type = VAR_STRING;
2776 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2777 args[2].v_type = VAR_UNKNOWN;
2778
2779 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002780 // Lock the text to avoid weird things from happening. Also disallow
2781 // switching to another window, it should not be needed and may end up in
2782 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002783 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002784
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002785 cb = get_insert_callback(type);
2786 retval = call_callback(cb, 0, &rettv, 2, args);
2787
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002788 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002789 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002790 {
2791 switch (rettv.v_type)
2792 {
2793 case VAR_LIST:
2794 matchlist = rettv.vval.v_list;
2795 break;
2796 case VAR_DICT:
2797 matchdict = rettv.vval.v_dict;
2798 break;
2799 case VAR_SPECIAL:
2800 if (rettv.vval.v_number == VVAL_NONE)
2801 compl_opt_suppress_empty = TRUE;
2802 // FALLTHROUGH
2803 default:
2804 // TODO: Give error message?
2805 clear_tv(&rettv);
2806 break;
2807 }
2808 }
zeertzjqcfe45652022-05-27 17:26:55 +01002809 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002810
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002811 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002812 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002813 validate_cursor();
2814 if (!EQUAL_POS(curwin->w_cursor, pos))
2815 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002816 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002817 goto theend;
2818 }
2819
2820 if (matchlist != NULL)
2821 ins_compl_add_list(matchlist);
2822 else if (matchdict != NULL)
2823 ins_compl_add_dict(matchdict);
2824
2825theend:
2826 // Restore State, it might have been changed.
2827 State = save_State;
2828
2829 if (matchdict != NULL)
2830 dict_unref(matchdict);
2831 if (matchlist != NULL)
2832 list_unref(matchlist);
2833}
2834#endif // FEAT_COMPL_FUNC
2835
2836#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2837/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002838 * Add a match to the list of matches from a typeval_T.
2839 * If the given string is already in the list of completions, then return
2840 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2841 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002842 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002843 */
2844 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002845ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002846{
2847 char_u *word;
2848 int dup = FALSE;
2849 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002850 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002851 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002852 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002853 int status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002854
Bram Moolenaar08928322020-01-04 14:32:48 +01002855 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002856 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2857 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002858 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2859 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2860 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2861 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2862 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
2863 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2864 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2865 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002866 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002867 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2868 dup = dict_get_number(tv->vval.v_dict, "dup");
2869 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2870 empty = dict_get_number(tv->vval.v_dict, "empty");
2871 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2872 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002873 flags |= CP_EQUAL;
2874 }
2875 else
2876 {
2877 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002878 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002879 }
2880 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002881 {
2882 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002883 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002884 }
2885 status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
2886 if (status != OK)
2887 clear_tv(&user_data);
2888 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002889}
2890
2891/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002892 * Add completions from a list.
2893 */
2894 static void
2895ins_compl_add_list(list_T *list)
2896{
2897 listitem_T *li;
2898 int dir = compl_direction;
2899
2900 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002901 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002902 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002903 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002904 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002905 // if dir was BACKWARD then honor it just once
2906 dir = FORWARD;
2907 else if (did_emsg)
2908 break;
2909 }
2910}
2911
2912/*
2913 * Add completions from a dict.
2914 */
2915 static void
2916ins_compl_add_dict(dict_T *dict)
2917{
2918 dictitem_T *di_refresh;
2919 dictitem_T *di_words;
2920
2921 // Check for optional "refresh" item.
2922 compl_opt_refresh_always = FALSE;
2923 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2924 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2925 {
2926 char_u *v = di_refresh->di_tv.vval.v_string;
2927
2928 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2929 compl_opt_refresh_always = TRUE;
2930 }
2931
2932 // Add completions from a "words" list.
2933 di_words = dict_find(dict, (char_u *)"words", 5);
2934 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2935 ins_compl_add_list(di_words->di_tv.vval.v_list);
2936}
2937
2938/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002939 * Start completion for the complete() function.
2940 * "startcol" is where the matched text starts (1 is first column).
2941 * "list" is the list of matches.
2942 */
2943 static void
2944set_completion(colnr_T startcol, list_T *list)
2945{
2946 int save_w_wrow = curwin->w_wrow;
2947 int save_w_leftcol = curwin->w_leftcol;
2948 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002949 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002950 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2951 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2952 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002953
2954 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002955 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002956 ins_compl_prep(' ');
2957 ins_compl_clear();
2958 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002959 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002960
2961 compl_direction = FORWARD;
2962 if (startcol > curwin->w_cursor.col)
2963 startcol = curwin->w_cursor.col;
2964 compl_col = startcol;
2965 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2966 // compl_pattern doesn't need to be set
2967 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2968 if (p_ic)
2969 flags |= CP_ICASE;
2970 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002971 -1, NULL, NULL, NULL, 0,
2972 flags | CP_FAST, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002973 return;
2974
2975 ctrl_x_mode = CTRL_X_EVAL;
2976
2977 ins_compl_add_list(list);
2978 compl_matches = ins_compl_make_cyclic();
2979 compl_started = TRUE;
2980 compl_used_match = TRUE;
2981 compl_cont_status = 0;
2982
2983 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01002984 int no_select = compl_no_select || compl_longest;
2985 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002986 {
2987 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01002988 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002989 // Down/Up has no real effect.
2990 ins_complete(K_UP, FALSE);
2991 }
2992 else
2993 ins_complete(Ctrl_N, FALSE);
2994 compl_enter_selects = compl_no_insert;
2995
2996 // Lazily show the popup menu, unless we got interrupted.
2997 if (!compl_interrupted)
2998 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01002999 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003000 out_flush();
3001}
3002
3003/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003004 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003005 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003006 void
3007f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003008{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003009 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003010
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003011 if (in_vim9script()
3012 && (check_for_number_arg(argvars, 0) == FAIL
3013 || check_for_list_arg(argvars, 1) == FAIL))
3014 return;
3015
Bram Moolenaar24959102022-05-07 20:01:16 +01003016 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003017 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003018 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003019 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003020 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003021
3022 // Check for undo allowed here, because if something was already inserted
3023 // the line was already saved for undo and this check isn't done.
3024 if (!undo_allowed())
3025 return;
3026
Bram Moolenaard83392a2022-09-01 12:22:46 +01003027 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003028 {
3029 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3030 if (startcol > 0)
3031 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003032 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003033}
3034
3035/*
3036 * "complete_add()" function
3037 */
3038 void
3039f_complete_add(typval_T *argvars, typval_T *rettv)
3040{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003041 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003042 return;
3043
Bram Moolenaar440cf092021-04-03 20:13:30 +02003044 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003045}
3046
3047/*
3048 * "complete_check()" function
3049 */
3050 void
3051f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3052{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003053 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003054 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003055
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003056 ins_compl_check_keys(0, TRUE);
3057 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003058
3059 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003060}
3061
3062/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003063 * Return Insert completion mode name string
3064 */
3065 static char_u *
3066ins_compl_mode(void)
3067{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003068 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003069 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3070
3071 return (char_u *)"";
3072}
3073
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003074/*
3075 * Assign the sequence number to all the completion matches which don't have
3076 * one assigned yet.
3077 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003078 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003079ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003080{
3081 int number = 0;
3082 compl_T *match;
3083
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003084 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003085 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003086 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003087 // This should normally succeed already at the first loop
3088 // cycle, so it's fast!
3089 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003090 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003091 if (match->cp_number != -1)
3092 {
3093 number = match->cp_number;
3094 break;
3095 }
3096 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003097 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003098 for (match = match->cp_next;
3099 match != NULL && match->cp_number == -1;
3100 match = match->cp_next)
3101 match->cp_number = ++number;
3102 }
3103 else // BACKWARD
3104 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003105 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003106 // number. This should normally succeed already at the
3107 // first loop cycle, so it's fast!
3108 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003109 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003110 if (match->cp_number != -1)
3111 {
3112 number = match->cp_number;
3113 break;
3114 }
3115 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003116 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003117 for (match = match->cp_prev; match
3118 && match->cp_number == -1;
3119 match = match->cp_prev)
3120 match->cp_number = ++number;
3121 }
3122}
3123
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003124/*
3125 * Get complete information
3126 */
3127 static void
3128get_complete_info(list_T *what_list, dict_T *retdict)
3129{
3130 int ret = OK;
3131 listitem_T *item;
3132#define CI_WHAT_MODE 0x01
3133#define CI_WHAT_PUM_VISIBLE 0x02
3134#define CI_WHAT_ITEMS 0x04
3135#define CI_WHAT_SELECTED 0x08
3136#define CI_WHAT_INSERTED 0x10
3137#define CI_WHAT_ALL 0xff
3138 int what_flag;
3139
3140 if (what_list == NULL)
3141 what_flag = CI_WHAT_ALL;
3142 else
3143 {
3144 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003145 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003146 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003147 {
3148 char_u *what = tv_get_string(&item->li_tv);
3149
3150 if (STRCMP(what, "mode") == 0)
3151 what_flag |= CI_WHAT_MODE;
3152 else if (STRCMP(what, "pum_visible") == 0)
3153 what_flag |= CI_WHAT_PUM_VISIBLE;
3154 else if (STRCMP(what, "items") == 0)
3155 what_flag |= CI_WHAT_ITEMS;
3156 else if (STRCMP(what, "selected") == 0)
3157 what_flag |= CI_WHAT_SELECTED;
3158 else if (STRCMP(what, "inserted") == 0)
3159 what_flag |= CI_WHAT_INSERTED;
3160 }
3161 }
3162
3163 if (ret == OK && (what_flag & CI_WHAT_MODE))
3164 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3165
3166 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3167 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3168
Girish Palya8950bf72024-03-20 20:07:29 +01003169 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003170 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003171 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003172 dict_T *di;
3173 compl_T *match;
3174 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003175
Girish Palya8950bf72024-03-20 20:07:29 +01003176 if (what_flag & CI_WHAT_ITEMS)
3177 {
3178 li = list_alloc();
3179 if (li == NULL)
3180 return;
3181 ret = dict_add_list(retdict, "items", li);
3182 }
3183 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3184 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3185 ins_compl_update_sequence_numbers();
3186 if (ret == OK && compl_first_match != NULL)
3187 {
3188 int list_idx = 0;
3189 match = compl_first_match;
3190 do
3191 {
3192 if (!match_at_original_text(match))
3193 {
3194 if (what_flag & CI_WHAT_ITEMS)
3195 {
3196 di = dict_alloc();
3197 if (di == NULL)
3198 return;
3199 ret = list_append_dict(li, di);
3200 if (ret != OK)
3201 return;
3202 dict_add_string(di, "word", match->cp_str);
3203 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3204 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3205 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3206 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3207 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3208 // Add an empty string for backwards compatibility
3209 dict_add_string(di, "user_data", (char_u *)"");
3210 else
3211 dict_add_tv(di, "user_data", &match->cp_user_data);
3212 }
3213 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3214 selected_idx = list_idx;
3215 list_idx += 1;
3216 }
3217 match = match->cp_next;
3218 }
3219 while (match != NULL && !is_first_match(match));
3220 }
3221 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3222 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003223 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003224
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003225 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3226 {
3227 // TODO
3228 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003229}
3230
3231/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003232 * "complete_info()" function
3233 */
3234 void
3235f_complete_info(typval_T *argvars, typval_T *rettv)
3236{
3237 list_T *what_list = NULL;
3238
Bram Moolenaar93a10962022-06-16 11:42:09 +01003239 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003240 return;
3241
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003242 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3243 return;
3244
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003245 if (argvars[0].v_type != VAR_UNKNOWN)
3246 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003247 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003248 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003249 what_list = argvars[0].vval.v_list;
3250 }
3251 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003252}
3253#endif
3254
3255/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003256 * Returns TRUE when using a user-defined function for thesaurus completion.
3257 */
3258 static int
3259thesaurus_func_complete(int type UNUSED)
3260{
3261#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003262 return type == CTRL_X_THESAURUS
3263 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003264#else
3265 return FALSE;
3266#endif
3267}
3268
3269/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003270 * Return value of process_next_cpt_value()
3271 */
3272enum
3273{
3274 INS_COMPL_CPT_OK = 1,
3275 INS_COMPL_CPT_CONT,
3276 INS_COMPL_CPT_END
3277};
3278
3279/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003280 * state information used for getting the next set of insert completion
3281 * matches.
3282 */
3283typedef struct
3284{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003285 char_u *e_cpt_copy; // copy of 'complete'
3286 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003287 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003288 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003289 pos_T prev_match_pos; // previous match position
3290 int set_match_pos; // save first_match_pos/last_match_pos
3291 pos_T first_match_pos; // first match position
3292 pos_T last_match_pos; // last match position
3293 int found_all; // found all matches of a certain type.
3294 char_u *dict; // dictionary file to search
3295 int dict_f; // "dict" is an exact file name or not
3296} ins_compl_next_state_T;
3297
3298/*
3299 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003300 *
3301 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003302 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003303 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003304 * st->found_all - all matches of this type are found
3305 * st->ins_buf - search for completions in this buffer
3306 * st->first_match_pos - position of the first completion match
3307 * st->last_match_pos - position of the last completion match
3308 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003309 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003310 * st->dict - name of the dictionary or thesaurus file to search
3311 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003312 *
3313 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003314 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3315 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003316 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003317 */
3318 static int
3319process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003320 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003321 int *compl_type_arg,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003322 pos_T *start_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003323{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003324 int compl_type = -1;
3325 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003326
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003327 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003328
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003329 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3330 st->e_cpt++;
3331
3332 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003333 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003334 st->ins_buf = curbuf;
3335 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003336 // Move the cursor back one character so that ^N can match the
3337 // word immediately after the cursor.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003338 if (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003339 {
3340 // Move the cursor to after the last character in the
3341 // buffer, so that word at start of buffer is found
3342 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003343 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003344 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003345 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003346 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003347 compl_type = 0;
3348
3349 // Remember the first match so that the loop stops when we
3350 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003351 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003352 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003353 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003354 && (st->ins_buf = ins_compl_next_buf(
3355 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003356 {
3357 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003358 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003359 {
3360 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003361 st->first_match_pos.col = st->last_match_pos.col = 0;
3362 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3363 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003364 compl_type = 0;
3365 }
3366 else // unloaded buffer, scan like dictionary
3367 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003368 st->found_all = TRUE;
3369 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003370 {
3371 status = INS_COMPL_CPT_CONT;
3372 goto done;
3373 }
3374 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003375 st->dict = st->ins_buf->b_fname;
3376 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003377 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003378 if (!shortmess(SHM_COMPLETIONSCAN))
3379 {
3380 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3381 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3382 st->ins_buf->b_fname == NULL
3383 ? buf_spname(st->ins_buf)
3384 : st->ins_buf->b_sfname == NULL
3385 ? st->ins_buf->b_fname
3386 : st->ins_buf->b_sfname);
3387 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3388 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003389 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003390 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003391 status = INS_COMPL_CPT_END;
3392 else
3393 {
3394 if (ctrl_x_mode_line_or_eval())
3395 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003396 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003397 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003398 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003399 compl_type = CTRL_X_DICTIONARY;
3400 else
3401 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003402 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003403 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003404 st->dict = st->e_cpt;
3405 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003406 }
3407 }
3408#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003409 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003410 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003411 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003412 compl_type = CTRL_X_PATH_DEFINES;
3413#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003414 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003415 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003416 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003417 if (!shortmess(SHM_COMPLETIONSCAN))
3418 {
3419 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3420 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3421 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3422 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003423 }
3424 else
3425 compl_type = -1;
3426
3427 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003428 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003429
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003430 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003431 if (compl_type == -1)
3432 status = INS_COMPL_CPT_CONT;
3433 }
3434
3435done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003436 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003437 return status;
3438}
3439
3440#ifdef FEAT_FIND_ID
3441/*
3442 * Get the next set of identifiers or defines matching "compl_pattern" in
3443 * included files.
3444 */
3445 static void
3446get_next_include_file_completion(int compl_type)
3447{
3448 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003449 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003450 (compl_type == CTRL_X_PATH_DEFINES
3451 && !(compl_cont_status & CONT_SOL))
3452 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003453 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003454}
3455#endif
3456
3457/*
3458 * Get the next set of words matching "compl_pattern" in dictionary or
3459 * thesaurus files.
3460 */
3461 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003462get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003463{
3464#ifdef FEAT_COMPL_FUNC
3465 if (thesaurus_func_complete(compl_type))
3466 expand_by_function(compl_type, compl_pattern);
3467 else
3468#endif
3469 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003470 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003471 : (compl_type == CTRL_X_THESAURUS
3472 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3473 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3474 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003475 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003476 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003477}
3478
3479/*
3480 * Get the next set of tag names matching "compl_pattern".
3481 */
3482 static void
3483get_next_tag_completion(void)
3484{
3485 int save_p_ic;
3486 char_u **matches;
3487 int num_matches;
3488
3489 // set p_ic according to p_ic, p_scs and pat for find_tags().
3490 save_p_ic = p_ic;
3491 p_ic = ignorecase(compl_pattern);
3492
3493 // Find up to TAG_MANY matches. Avoids that an enormous number
3494 // of matches is found when compl_pattern is empty
3495 g_tag_at_cursor = TRUE;
3496 if (find_tags(compl_pattern, &num_matches, &matches,
3497 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003498 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003499 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3500 ins_compl_add_matches(num_matches, matches, p_ic);
3501 g_tag_at_cursor = FALSE;
3502 p_ic = save_p_ic;
3503}
3504
3505/*
3506 * Get the next set of filename matching "compl_pattern".
3507 */
3508 static void
3509get_next_filename_completion(void)
3510{
3511 char_u **matches;
3512 int num_matches;
3513
3514 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3515 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3516 return;
3517
3518 // May change home directory back to "~".
3519 tilde_replace(compl_pattern, num_matches, matches);
3520#ifdef BACKSLASH_IN_FILENAME
3521 if (curbuf->b_p_csl[0] != NUL)
3522 {
3523 int i;
3524
3525 for (i = 0; i < num_matches; ++i)
3526 {
3527 char_u *ptr = matches[i];
3528
3529 while (*ptr != NUL)
3530 {
3531 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3532 *ptr = '/';
3533 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3534 *ptr = '\\';
3535 ptr += (*mb_ptr2len)(ptr);
3536 }
3537 }
3538 }
3539#endif
3540 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
3541}
3542
3543/*
3544 * Get the next set of command-line completions matching "compl_pattern".
3545 */
3546 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003547get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003548{
3549 char_u **matches;
3550 int num_matches;
3551
3552 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003553 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003554 ins_compl_add_matches(num_matches, matches, FALSE);
3555}
3556
3557/*
3558 * Get the next set of spell suggestions matching "compl_pattern".
3559 */
3560 static void
3561get_next_spell_completion(linenr_T lnum UNUSED)
3562{
3563#ifdef FEAT_SPELL
3564 char_u **matches;
3565 int num_matches;
3566
3567 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3568 if (num_matches > 0)
3569 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003570 else
3571 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003572#endif
3573}
3574
3575/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003576 * Return the next word or line from buffer "ins_buf" at position
3577 * "cur_match_pos" for completion. The length of the match is set in "len".
3578 */
3579 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003580ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003581 buf_T *ins_buf, // buffer being scanned
3582 pos_T *cur_match_pos, // current match position
3583 int *match_len,
3584 int *cont_s_ipos) // next ^X<> will set initial_pos
3585{
3586 char_u *ptr;
3587 int len;
3588
3589 *match_len = 0;
3590 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3591 cur_match_pos->col;
3592 if (ctrl_x_mode_line_or_eval())
3593 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003594 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003595 {
3596 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3597 return NULL;
3598 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3599 if (!p_paste)
3600 ptr = skipwhite(ptr);
3601 }
3602 len = (int)STRLEN(ptr);
3603 }
3604 else
3605 {
3606 char_u *tmp_ptr = ptr;
3607
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003608 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003609 {
3610 tmp_ptr += compl_length;
3611 // Skip if already inside a word.
3612 if (vim_iswordp(tmp_ptr))
3613 return NULL;
3614 // Find start of next word.
3615 tmp_ptr = find_word_start(tmp_ptr);
3616 }
3617 // Find end of this word.
3618 tmp_ptr = find_word_end(tmp_ptr);
3619 len = (int)(tmp_ptr - ptr);
3620
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003621 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003622 {
3623 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3624 {
3625 // Try next line, if any. the new word will be
3626 // "join" as if the normal command "J" was used.
3627 // IOSIZE is always greater than
3628 // compl_length, so the next STRNCPY always
3629 // works -- Acevedo
3630 STRNCPY(IObuff, ptr, len);
3631 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3632 tmp_ptr = ptr = skipwhite(ptr);
3633 // Find start of next word.
3634 tmp_ptr = find_word_start(tmp_ptr);
3635 // Find end of next word.
3636 tmp_ptr = find_word_end(tmp_ptr);
3637 if (tmp_ptr > ptr)
3638 {
3639 if (*ptr != ')' && IObuff[len - 1] != TAB)
3640 {
3641 if (IObuff[len - 1] != ' ')
3642 IObuff[len++] = ' ';
3643 // IObuf =~ "\k.* ", thus len >= 2
3644 if (p_js
3645 && (IObuff[len - 2] == '.'
3646 || (vim_strchr(p_cpo, CPO_JOINSP)
3647 == NULL
3648 && (IObuff[len - 2] == '?'
3649 || IObuff[len - 2] == '!'))))
3650 IObuff[len++] = ' ';
3651 }
3652 // copy as much as possible of the new word
3653 if (tmp_ptr - ptr >= IOSIZE - len)
3654 tmp_ptr = ptr + IOSIZE - len - 1;
3655 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3656 len += (int)(tmp_ptr - ptr);
3657 *cont_s_ipos = TRUE;
3658 }
3659 IObuff[len] = NUL;
3660 ptr = IObuff;
3661 }
3662 if (len == compl_length)
3663 return NULL;
3664 }
3665 }
3666
3667 *match_len = len;
3668 return ptr;
3669}
3670
3671/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003672 * Get the next set of words matching "compl_pattern" for default completion(s)
3673 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003674 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3675 * position "st->start_pos" in the "compl_direction" direction. If
3676 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3677 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003678 * Returns OK if a new next match is found, otherwise returns FAIL.
3679 */
3680 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003681get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003682{
3683 int found_new_match = FAIL;
3684 int save_p_scs;
3685 int save_p_ws;
3686 int looped_around = FALSE;
3687 char_u *ptr;
3688 int len;
3689
3690 // If 'infercase' is set, don't use 'smartcase' here
3691 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003692 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003693 p_scs = FALSE;
3694
3695 // Buffers other than curbuf are scanned from the beginning or the
3696 // end but never from the middle, thus setting nowrapscan in this
3697 // buffer is a good idea, on the other hand, we always set
3698 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3699 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003700 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003701 p_ws = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003702 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003703 p_ws = TRUE;
3704 looped_around = FALSE;
3705 for (;;)
3706 {
3707 int cont_s_ipos = FALSE;
3708
3709 ++msg_silent; // Don't want messages for wrapscan.
3710
3711 // ctrl_x_mode_line_or_eval() || word-wise search that
3712 // has added a word that was at the beginning of the line
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003713 if (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003714 found_new_match = search_for_exact_line(st->ins_buf,
3715 st->cur_match_pos, compl_direction, compl_pattern);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003716 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003717 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003718 NULL, compl_direction, compl_pattern, compl_patternlen,
3719 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003720 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003721 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003722 {
3723 // set "compl_started" even on fail
3724 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003725 st->first_match_pos = *st->cur_match_pos;
3726 st->last_match_pos = *st->cur_match_pos;
3727 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003728 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003729 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3730 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003731 {
3732 found_new_match = FAIL;
3733 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003734 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003735 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3736 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3737 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003738 {
3739 if (looped_around)
3740 found_new_match = FAIL;
3741 else
3742 looped_around = TRUE;
3743 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003744 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003745 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3746 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3747 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003748 {
3749 if (looped_around)
3750 found_new_match = FAIL;
3751 else
3752 looped_around = TRUE;
3753 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003754 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003755 if (found_new_match == FAIL)
3756 break;
3757
3758 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003759 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003760 && start_pos->lnum == st->cur_match_pos->lnum
3761 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003762 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003763
zeertzjq440d4cb2023-03-02 17:51:32 +00003764 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3765 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003766 if (ptr == NULL)
3767 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003768
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003769 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003770 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003771 0, cont_s_ipos) != NOTDONE)
3772 {
3773 found_new_match = OK;
3774 break;
3775 }
3776 }
3777 p_scs = save_p_scs;
3778 p_ws = save_p_ws;
3779
3780 return found_new_match;
3781}
3782
3783/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003784 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003785 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003786 */
3787 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003788get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003789{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003790 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003791
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003792 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003793 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003794 case -1:
3795 break;
3796#ifdef FEAT_FIND_ID
3797 case CTRL_X_PATH_PATTERNS:
3798 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003799 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003800 break;
3801#endif
3802
3803 case CTRL_X_DICTIONARY:
3804 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003805 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3806 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003807 break;
3808
3809 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003810 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003811 break;
3812
3813 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003814 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003815 break;
3816
3817 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003818 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003819 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003820 break;
3821
3822#ifdef FEAT_COMPL_FUNC
3823 case CTRL_X_FUNCTION:
3824 case CTRL_X_OMNI:
3825 expand_by_function(type, compl_pattern);
3826 break;
3827#endif
3828
3829 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003830 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003831 break;
3832
3833 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003834 found_new_match = get_next_default_completion(st, ini);
3835 if (found_new_match == FAIL && st->ins_buf == curbuf)
3836 st->found_all = TRUE;
3837 }
3838
3839 // check if compl_curr_match has changed, (e.g. other type of
3840 // expansion added something)
3841 if (type != 0 && compl_curr_match != compl_old_match)
3842 found_new_match = OK;
3843
3844 return found_new_match;
3845}
3846
3847/*
3848 * Get the next expansion(s), using "compl_pattern".
3849 * The search starts at position "ini" in curbuf and in the direction
3850 * compl_direction.
3851 * When "compl_started" is FALSE start at that position, otherwise continue
3852 * where we stopped searching before.
3853 * This may return before finding all the matches.
3854 * Return the total number of matches or -1 if still unknown -- Acevedo
3855 */
3856 static int
3857ins_compl_get_exp(pos_T *ini)
3858{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003859 static ins_compl_next_state_T st;
3860 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003861 int i;
3862 int found_new_match;
3863 int type = ctrl_x_mode;
3864
3865 if (!compl_started)
3866 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003867 buf_T *buf;
3868
3869 FOR_ALL_BUFFERS(buf)
3870 buf->b_scanned = 0;
3871 if (!st_cleared)
3872 {
3873 CLEAR_FIELD(st);
3874 st_cleared = TRUE;
3875 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003876 st.found_all = FALSE;
3877 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003878 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003879 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003880 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
3881 ? (char_u *)"." : curbuf->b_p_cpt);
3882 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003883 st.last_match_pos = st.first_match_pos = *ini;
3884 }
3885 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
3886 st.ins_buf = curbuf; // In case the buffer was wiped out.
3887
3888 compl_old_match = compl_curr_match; // remember the last current match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003889 st.cur_match_pos = (compl_dir_forward())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003890 ? &st.last_match_pos : &st.first_match_pos;
3891
3892 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
3893 for (;;)
3894 {
3895 found_new_match = FAIL;
3896 st.set_match_pos = FALSE;
3897
3898 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
3899 // or if found_all says this entry is done. For ^X^L only use the
3900 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003901 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003902 && (!compl_started || st.found_all))
3903 {
3904 int status = process_next_cpt_value(&st, &type, ini);
3905
3906 if (status == INS_COMPL_CPT_END)
3907 break;
3908 if (status == INS_COMPL_CPT_CONT)
3909 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003910 }
3911
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003912 // If complete() was called then compl_pattern has been reset. The
3913 // following won't work then, bail out.
3914 if (compl_pattern == NULL)
3915 break;
3916
3917 // get the next set of completion matches
3918 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003919
3920 // break the loop for specialized modes (use 'complete' just for the
3921 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3922 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003923 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
3924 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003925 {
3926 if (got_int)
3927 break;
3928 // Fill the popup menu as soon as possible.
3929 if (type != -1)
3930 ins_compl_check_keys(0, FALSE);
3931
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003932 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003933 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3934 break;
3935 compl_started = TRUE;
3936 }
3937 else
3938 {
3939 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02003940 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003941 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003942
3943 compl_started = FALSE;
3944 }
3945 }
3946 compl_started = TRUE;
3947
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003948 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003949 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003950 found_new_match = FAIL;
3951
3952 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003953 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003954 && !ctrl_x_mode_line_or_eval()))
3955 i = ins_compl_make_cyclic();
3956
3957 if (compl_old_match != NULL)
3958 {
3959 // If several matches were added (FORWARD) or the search failed and has
3960 // just been made cyclic then we have to move compl_curr_match to the
3961 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003962 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003963 : compl_old_match->cp_prev;
3964 if (compl_curr_match == NULL)
3965 compl_curr_match = compl_old_match;
3966 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01003967 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003968
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003969 return i;
3970}
3971
3972/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003973 * Update "compl_shown_match" to the actually shown match, it may differ when
3974 * "compl_leader" is used to omit some of the matches.
3975 */
3976 static void
3977ins_compl_update_shown_match(void)
3978{
3979 while (!ins_compl_equal(compl_shown_match,
3980 compl_leader, (int)STRLEN(compl_leader))
3981 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003982 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003983 compl_shown_match = compl_shown_match->cp_next;
3984
3985 // If we didn't find it searching forward, and compl_shows_dir is
3986 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003987 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003988 && !ins_compl_equal(compl_shown_match,
3989 compl_leader, (int)STRLEN(compl_leader))
3990 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003991 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003992 {
3993 while (!ins_compl_equal(compl_shown_match,
3994 compl_leader, (int)STRLEN(compl_leader))
3995 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003996 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003997 compl_shown_match = compl_shown_match->cp_prev;
3998 }
3999}
4000
4001/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004002 * Delete the old text being completed.
4003 */
4004 void
4005ins_compl_delete(void)
4006{
4007 int col;
4008
4009 // In insert mode: Delete the typed part.
4010 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004011 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004012 if ((int)curwin->w_cursor.col > col)
4013 {
4014 if (stop_arrow() == FAIL)
4015 return;
4016 backspace_until_column(col);
4017 }
4018
4019 // TODO: is this sufficient for redrawing? Redrawing everything causes
4020 // flicker, thus we can't do that.
4021 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004022#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004023 // clear v:completed_item
4024 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004025#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004026}
4027
4028/*
4029 * Insert the new text being completed.
4030 * "in_compl_func" is TRUE when called from complete_check().
4031 */
4032 void
4033ins_compl_insert(int in_compl_func)
4034{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004035 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004036
4037 // Make sure we don't go over the end of the string, this can happen with
4038 // illegal bytes.
4039 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4040 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004041 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004042 compl_used_match = FALSE;
4043 else
4044 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004045#ifdef FEAT_EVAL
4046 {
4047 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4048
4049 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4050 }
4051#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004052 if (!in_compl_func)
4053 compl_curr_match = compl_shown_match;
4054}
4055
4056/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004057 * show the file name for the completion match (if any). Truncate the file
4058 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004059 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004060 static void
4061ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004062{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004063 char *lead = _("match in file");
4064 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4065 char_u *s;
4066 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004067
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004068 if (space <= 0)
4069 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004070
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004071 // We need the tail that fits. With double-byte encoding going
4072 // back from the end is very slow, thus go from the start and keep
4073 // the text that fits in "space" between "s" and "e".
4074 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004075 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004076 space -= ptr2cells(e);
4077 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004078 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004079 space += ptr2cells(s);
4080 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004081 }
4082 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004083 msg_hist_off = TRUE;
4084 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4085 s > compl_shown_match->cp_fname ? "<" : "", s);
4086 msg((char *)IObuff);
4087 msg_hist_off = FALSE;
4088 redraw_cmdline = FALSE; // don't overwrite!
4089}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004090
glepnirdca57fb2024-06-04 22:01:21 +02004091/*
zeertzjq551d8c32024-06-05 19:53:32 +02004092 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004093 */
glepnira218cc62024-06-03 19:32:39 +02004094 static compl_T *
4095find_comp_when_fuzzy(void)
4096{
4097 int score;
4098 char_u* str;
4099 int target_idx = -1;
4100 int is_forward = compl_shows_dir_forward();
4101 int is_backward = compl_shows_dir_backward();
4102 compl_T *comp = NULL;
4103
4104 if (compl_match_array == NULL ||
4105 (is_forward && compl_selected_item == compl_match_arraysize - 1)
4106 || (is_backward && compl_selected_item == 0))
4107 return compl_first_match;
4108
4109 if (is_forward)
4110 target_idx = compl_selected_item + 1;
4111 else if (is_backward)
4112 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004113 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004114
4115 score = compl_match_array[target_idx].pum_score;
4116 str = compl_match_array[target_idx].pum_text;
4117
4118 comp = compl_first_match;
4119 do {
4120 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4121 return comp;
4122 comp = comp->cp_next;
4123 } while (comp != NULL && !is_first_match(comp));
4124
4125 return NULL;
4126}
4127
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004128/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004129 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004130 * times. The number of matches found is returned in 'num_matches'.
4131 *
4132 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4133 * get more completions. If it is FALSE, then do nothing when there are no more
4134 * completions in the given direction.
4135 *
4136 * If "advance" is TRUE, then completion will move to the first match.
4137 * Otherwise, the original text will be shown.
4138 *
4139 * Returns OK on success and -1 if the number of matches are unknown.
4140 */
4141 static int
4142find_next_completion_match(
4143 int allow_get_expansion,
4144 int todo, // repeat completion this many times
4145 int advance,
4146 int *num_matches)
4147{
4148 int found_end = FALSE;
4149 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004150 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004151 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4152 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004153
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004154 while (--todo >= 0)
4155 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004156 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004157 {
glepnira218cc62024-06-03 19:32:39 +02004158 compl_shown_match = !compl_fuzzy_match ? compl_shown_match->cp_next
4159 : find_comp_when_fuzzy();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004160 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004161 && (is_first_match(compl_shown_match->cp_next)
4162 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004163 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004164 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004165 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004166 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004167 found_end = is_first_match(compl_shown_match);
glepnira218cc62024-06-03 19:32:39 +02004168 compl_shown_match = !compl_fuzzy_match ? compl_shown_match->cp_prev
4169 : find_comp_when_fuzzy();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004170 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004171 }
4172 else
4173 {
4174 if (!allow_get_expansion)
4175 {
4176 if (advance)
4177 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004178 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004179 compl_pending -= todo + 1;
4180 else
4181 compl_pending += todo + 1;
4182 }
4183 return -1;
4184 }
4185
4186 if (!compl_no_select && advance)
4187 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004188 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004189 --compl_pending;
4190 else
4191 ++compl_pending;
4192 }
4193
4194 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004195 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004196
4197 // handle any pending completions
4198 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004199 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004200 {
4201 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4202 {
4203 compl_shown_match = compl_shown_match->cp_next;
4204 --compl_pending;
4205 }
4206 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4207 {
4208 compl_shown_match = compl_shown_match->cp_prev;
4209 ++compl_pending;
4210 }
4211 else
4212 break;
4213 }
4214 found_end = FALSE;
4215 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004216 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004217 && compl_leader != NULL
4218 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004219 compl_leader, (int)STRLEN(compl_leader))
4220 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004221 ++todo;
4222 else
4223 // Remember a matching item.
4224 found_compl = compl_shown_match;
4225
4226 // Stop at the end of the list when we found a usable match.
4227 if (found_end)
4228 {
4229 if (found_compl != NULL)
4230 {
4231 compl_shown_match = found_compl;
4232 break;
4233 }
4234 todo = 1; // use first usable match after wrapping around
4235 }
4236 }
4237
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004238 return OK;
4239}
4240
4241/*
4242 * Fill in the next completion in the current direction.
4243 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4244 * get more completions. If it is FALSE, then we just do nothing when there
4245 * are no more completions in a given direction. The latter case is used when
4246 * we are still in the middle of finding completions, to allow browsing
4247 * through the ones found so far.
4248 * Return the total number of matches, or -1 if still unknown -- webb.
4249 *
4250 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4251 * compl_shown_match here.
4252 *
4253 * Note that this function may be called recursively once only. First with
4254 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4255 * calls this function with "allow_get_expansion" FALSE.
4256 */
4257 static int
4258ins_compl_next(
4259 int allow_get_expansion,
4260 int count, // repeat completion this many times; should
4261 // be at least 1
4262 int insert_match, // Insert the newly selected match
4263 int in_compl_func) // called from complete_check()
4264{
4265 int num_matches = -1;
4266 int todo = count;
4267 int advance;
4268 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004269 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004270 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004271 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4272 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004273
4274 // When user complete function return -1 for findstart which is next
4275 // time of 'always', compl_shown_match become NULL.
4276 if (compl_shown_match == NULL)
4277 return -1;
4278
glepnira218cc62024-06-03 19:32:39 +02004279 if (compl_leader != NULL
4280 && !match_at_original_text(compl_shown_match)
4281 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004282 // Update "compl_shown_match" to the actually shown match
4283 ins_compl_update_shown_match();
4284
4285 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004286 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004287 // Delete old text to be replaced
4288 ins_compl_delete();
4289
4290 // When finding the longest common text we stick at the original text,
4291 // don't let CTRL-N or CTRL-P move to the first match.
4292 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4293
4294 // When restarting the search don't insert the first match either.
4295 if (compl_restarting)
4296 {
4297 advance = FALSE;
4298 compl_restarting = FALSE;
4299 }
4300
4301 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4302 // around.
4303 if (find_next_completion_match(allow_get_expansion, todo, advance,
4304 &num_matches) == -1)
4305 return -1;
4306
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004307 if (curbuf != orig_curbuf)
4308 {
4309 // In case some completion function switched buffer, don't want to
4310 // insert the completion elsewhere.
4311 return -1;
4312 }
4313
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004314 // Insert the text of the new completion, or the compl_leader.
4315 if (compl_no_insert && !started)
4316 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004317 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004318 compl_used_match = FALSE;
4319 }
4320 else if (insert_match)
4321 {
4322 if (!compl_get_longest || compl_used_match)
4323 ins_compl_insert(in_compl_func);
4324 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004325 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004326 }
4327 else
4328 compl_used_match = FALSE;
4329
4330 if (!allow_get_expansion)
4331 {
4332 // may undisplay the popup menu first
4333 ins_compl_upd_pum();
4334
4335 if (pum_enough_matches())
4336 // Will display the popup menu, don't redraw yet to avoid flicker.
4337 pum_call_update_screen();
4338 else
4339 // Not showing the popup menu yet, redraw to show the user what was
4340 // inserted.
4341 update_screen(0);
4342
4343 // display the updated popup menu
4344 ins_compl_show_pum();
4345#ifdef FEAT_GUI
4346 if (gui.in_use)
4347 {
4348 // Show the cursor after the match, not after the redrawn text.
4349 setcursor();
4350 out_flush_cursor(FALSE, FALSE);
4351 }
4352#endif
4353
4354 // Delete old text to be replaced, since we're still searching and
4355 // don't want to match ourselves!
4356 ins_compl_delete();
4357 }
4358
4359 // Enter will select a match when the match wasn't inserted and the popup
4360 // menu is visible.
4361 if (compl_no_insert && !started)
4362 compl_enter_selects = TRUE;
4363 else
4364 compl_enter_selects = !insert_match && compl_match_array != NULL;
4365
4366 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004367 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004368 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004369
4370 return num_matches;
4371}
4372
4373/*
4374 * Call this while finding completions, to check whether the user has hit a key
4375 * that should change the currently displayed completion, or exit completion
4376 * mode. Also, when compl_pending is not zero, show a completion as soon as
4377 * possible. -- webb
4378 * "frequency" specifies out of how many calls we actually check.
4379 * "in_compl_func" is TRUE when called from complete_check(), don't set
4380 * compl_curr_match.
4381 */
4382 void
4383ins_compl_check_keys(int frequency, int in_compl_func)
4384{
4385 static int count = 0;
4386 int c;
4387
4388 // Don't check when reading keys from a script, :normal or feedkeys().
4389 // That would break the test scripts. But do check for keys when called
4390 // from complete_check().
4391 if (!in_compl_func && (using_script() || ex_normal_busy))
4392 return;
4393
4394 // Only do this at regular intervals
4395 if (++count < frequency)
4396 return;
4397 count = 0;
4398
4399 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4400 // can't do its work correctly.
4401 c = vpeekc_any();
4402 if (c != NUL)
4403 {
4404 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4405 {
4406 c = safe_vgetc(); // Eat the character
4407 compl_shows_dir = ins_compl_key2dir(c);
4408 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4409 c != K_UP && c != K_DOWN, in_compl_func);
4410 }
4411 else
4412 {
4413 // Need to get the character to have KeyTyped set. We'll put it
4414 // back with vungetc() below. But skip K_IGNORE.
4415 c = safe_vgetc();
4416 if (c != K_IGNORE)
4417 {
4418 // Don't interrupt completion when the character wasn't typed,
4419 // e.g., when doing @q to replay keys.
4420 if (c != Ctrl_R && KeyTyped)
4421 compl_interrupted = TRUE;
4422
4423 vungetc(c);
4424 }
4425 }
4426 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004427 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004428 {
4429 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4430
4431 compl_pending = 0;
4432 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4433 }
4434}
4435
4436/*
4437 * Decide the direction of Insert mode complete from the key typed.
4438 * Returns BACKWARD or FORWARD.
4439 */
4440 static int
4441ins_compl_key2dir(int c)
4442{
4443 if (c == Ctrl_P || c == Ctrl_L
4444 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4445 return BACKWARD;
4446 return FORWARD;
4447}
4448
4449/*
4450 * Return TRUE for keys that are used for completion only when the popup menu
4451 * is visible.
4452 */
4453 static int
4454ins_compl_pum_key(int c)
4455{
4456 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4457 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4458 || c == K_UP || c == K_DOWN);
4459}
4460
4461/*
4462 * Decide the number of completions to move forward.
4463 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4464 */
4465 static int
4466ins_compl_key2count(int c)
4467{
4468 int h;
4469
4470 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4471 {
4472 h = pum_get_height();
4473 if (h > 3)
4474 h -= 2; // keep some context
4475 return h;
4476 }
4477 return 1;
4478}
4479
4480/*
4481 * Return TRUE if completion with "c" should insert the match, FALSE if only
4482 * to change the currently selected completion.
4483 */
4484 static int
4485ins_compl_use_match(int c)
4486{
4487 switch (c)
4488 {
4489 case K_UP:
4490 case K_DOWN:
4491 case K_PAGEDOWN:
4492 case K_KPAGEDOWN:
4493 case K_S_DOWN:
4494 case K_PAGEUP:
4495 case K_KPAGEUP:
4496 case K_S_UP:
4497 return FALSE;
4498 }
4499 return TRUE;
4500}
4501
4502/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004503 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4504 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004505 * Sets the global variables: compl_col, compl_length, compl_pattern and
4506 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004507 * Uses the global variables: compl_cont_status and ctrl_x_mode
4508 */
4509 static int
4510get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4511{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004512 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004513 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004514 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004515 {
4516 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4517 ;
4518 compl_col += ++startcol;
4519 compl_length = curs_col - startcol;
4520 }
4521 if (p_ic)
4522 compl_pattern = str_foldcase(line + compl_col,
4523 compl_length, NULL, 0);
4524 else
4525 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4526 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004527 {
4528 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004529 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004530 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004531 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004532 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004533 {
4534 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004535 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004536
4537 // we need up to 2 extra chars for the prefix
4538 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004539 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004540 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004541 {
4542 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004543 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004544 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004545 if (!vim_iswordp(line + compl_col)
4546 || (compl_col > 0
4547 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004548 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004549 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004550 prefixlen = 0;
4551 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004552 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004553 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004554 line + compl_col, compl_length);
4555 }
4556 else if (--startcol < 0
4557 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4558 {
4559 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004560 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004561 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004562 {
4563 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004564 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004565 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004566 compl_col += curs_col;
4567 compl_length = 0;
4568 }
4569 else
4570 {
4571 // Search the point of change class of multibyte character
4572 // or not a word single byte character backward.
4573 if (has_mbyte)
4574 {
4575 int base_class;
4576 int head_off;
4577
4578 startcol -= (*mb_head_off)(line, line + startcol);
4579 base_class = mb_get_class(line + startcol);
4580 while (--startcol >= 0)
4581 {
4582 head_off = (*mb_head_off)(line, line + startcol);
4583 if (base_class != mb_get_class(line + startcol
4584 - head_off))
4585 break;
4586 startcol -= head_off;
4587 }
4588 }
4589 else
4590 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4591 ;
4592 compl_col += ++startcol;
4593 compl_length = (int)curs_col - startcol;
4594 if (compl_length == 1)
4595 {
4596 // Only match word with at least two chars -- webb
4597 // there's no need to call quote_meta,
4598 // alloc(7) is enough -- Acevedo
4599 compl_pattern = alloc(7);
4600 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004601 {
4602 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004603 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004604 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004605 STRCPY((char *)compl_pattern, "\\<");
4606 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4607 STRCAT((char *)compl_pattern, "\\k");
4608 }
4609 else
4610 {
4611 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4612 compl_length) + 2);
4613 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004614 {
4615 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004616 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004617 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004618 STRCPY((char *)compl_pattern, "\\<");
4619 (void)quote_meta(compl_pattern + 2, line + compl_col,
4620 compl_length);
4621 }
4622 }
4623
John Marriott8c85a2a2024-05-20 19:18:26 +02004624 compl_patternlen = STRLEN(compl_pattern);
4625
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004626 return OK;
4627}
4628
4629/*
4630 * Get the pattern, column and length for whole line completion or for the
4631 * complete() function.
4632 * Sets the global variables: compl_col, compl_length and compl_pattern.
4633 */
4634 static int
4635get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4636{
4637 compl_col = (colnr_T)getwhitecols(line);
4638 compl_length = (int)curs_col - (int)compl_col;
4639 if (compl_length < 0) // cursor in indent: empty pattern
4640 compl_length = 0;
4641 if (p_ic)
4642 compl_pattern = str_foldcase(line + compl_col, compl_length,
4643 NULL, 0);
4644 else
4645 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4646 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004647 {
4648 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004649 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004650 }
4651
4652 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004653
4654 return OK;
4655}
4656
4657/*
4658 * Get the pattern, column and length for filename completion.
4659 * Sets the global variables: compl_col, compl_length and compl_pattern.
4660 */
4661 static int
4662get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4663{
4664 // Go back to just before the first filename character.
4665 if (startcol > 0)
4666 {
4667 char_u *p = line + startcol;
4668
4669 MB_PTR_BACK(line, p);
4670 while (p > line && vim_isfilec(PTR2CHAR(p)))
4671 MB_PTR_BACK(line, p);
4672 if (p == line && vim_isfilec(PTR2CHAR(p)))
4673 startcol = 0;
4674 else
4675 startcol = (int)(p - line) + 1;
4676 }
4677
4678 compl_col += startcol;
4679 compl_length = (int)curs_col - startcol;
4680 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4681 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004682 {
4683 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004684 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004685 }
4686
4687 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004688
4689 return OK;
4690}
4691
4692/*
4693 * Get the pattern, column and length for command-line completion.
4694 * Sets the global variables: compl_col, compl_length and compl_pattern.
4695 */
4696 static int
4697get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4698{
4699 compl_pattern = vim_strnsave(line, curs_col);
4700 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004701 {
4702 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004703 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004704 }
4705 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004706 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004707 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004708 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4709 || compl_xp.xp_context == EXPAND_NOTHING)
4710 // No completion possible, use an empty pattern to get a
4711 // "pattern not found" message.
4712 compl_col = curs_col;
4713 else
4714 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4715 compl_length = curs_col - compl_col;
4716
4717 return OK;
4718}
4719
4720/*
4721 * Get the pattern, column and length for user defined completion ('omnifunc',
4722 * 'completefunc' and 'thesaurusfunc')
4723 * Sets the global variables: compl_col, compl_length and compl_pattern.
4724 * Uses the global variable: spell_bad_len
4725 */
4726 static int
4727get_userdefined_compl_info(colnr_T curs_col UNUSED)
4728{
4729 int ret = FAIL;
4730
4731#ifdef FEAT_COMPL_FUNC
4732 // Call user defined function 'completefunc' with "a:findstart"
4733 // set to 1 to obtain the length of text to use for completion.
4734 char_u *line;
4735 typval_T args[3];
4736 int col;
4737 char_u *funcname;
4738 pos_T pos;
4739 int save_State = State;
4740 callback_T *cb;
4741
4742 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4743 // length as a string
4744 funcname = get_complete_funcname(ctrl_x_mode);
4745 if (*funcname == NUL)
4746 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004747 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004748 ? "completefunc" : "omnifunc");
4749 return FAIL;
4750 }
4751
4752 args[0].v_type = VAR_NUMBER;
4753 args[0].vval.v_number = 1;
4754 args[1].v_type = VAR_STRING;
4755 args[1].vval.v_string = (char_u *)"";
4756 args[2].v_type = VAR_UNKNOWN;
4757 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004758 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004759 cb = get_insert_callback(ctrl_x_mode);
4760 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004761 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004762
4763 State = save_State;
4764 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004765 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004766 validate_cursor();
4767 if (!EQUAL_POS(curwin->w_cursor, pos))
4768 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004769 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004770 return FAIL;
4771 }
4772
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004773 // Return value -2 means the user complete function wants to cancel the
4774 // complete without an error, do the same if the function did not execute
4775 // successfully.
4776 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004777 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004778 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004779 if (col == -3)
4780 {
4781 ctrl_x_mode = CTRL_X_NORMAL;
4782 edit_submode = NULL;
4783 if (!shortmess(SHM_COMPLETIONMENU))
4784 msg_clr_cmdline();
4785 return FAIL;
4786 }
4787
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004788 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004789 // completion.
4790 compl_opt_refresh_always = FALSE;
4791 compl_opt_suppress_empty = FALSE;
4792
4793 if (col < 0)
4794 col = curs_col;
4795 compl_col = col;
4796 if (compl_col > curs_col)
4797 compl_col = curs_col;
4798
4799 // Setup variables for completion. Need to obtain "line" again,
4800 // it may have become invalid.
4801 line = ml_get(curwin->w_cursor.lnum);
4802 compl_length = curs_col - compl_col;
4803 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4804 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004805 {
4806 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004807 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004808 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004809
John Marriott8c85a2a2024-05-20 19:18:26 +02004810 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004811 ret = OK;
4812#endif
4813
4814 return ret;
4815}
4816
4817/*
4818 * Get the pattern, column and length for spell completion.
4819 * Sets the global variables: compl_col, compl_length and compl_pattern.
4820 * Uses the global variable: spell_bad_len
4821 */
4822 static int
4823get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4824{
4825 int ret = FAIL;
4826#ifdef FEAT_SPELL
4827 char_u *line;
4828
4829 if (spell_bad_len > 0)
4830 compl_col = curs_col - spell_bad_len;
4831 else
4832 compl_col = spell_word_start(startcol);
4833 if (compl_col >= (colnr_T)startcol)
4834 {
4835 compl_length = 0;
4836 compl_col = curs_col;
4837 }
4838 else
4839 {
4840 spell_expand_check_cap(compl_col);
4841 compl_length = (int)curs_col - compl_col;
4842 }
4843 // Need to obtain "line" again, it may have become invalid.
4844 line = ml_get(curwin->w_cursor.lnum);
4845 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4846 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004847 {
4848 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004849 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004850 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004851
John Marriott8c85a2a2024-05-20 19:18:26 +02004852 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004853 ret = OK;
4854#endif
4855
4856 return ret;
4857}
4858
4859/*
4860 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004861 * "startcol" - start column number of the completion pattern/text
4862 * "cur_col" - current cursor column
4863 * On return, "line_invalid" is set to TRUE, if the current line may have
4864 * become invalid and needs to be fetched again.
4865 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004866 */
4867 static int
4868compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
4869{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004870 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004871 || (ctrl_x_mode & CTRL_X_WANT_IDENT
4872 && !thesaurus_func_complete(ctrl_x_mode)))
4873 {
4874 return get_normal_compl_info(line, startcol, curs_col);
4875 }
4876 else if (ctrl_x_mode_line_or_eval())
4877 {
4878 return get_wholeline_compl_info(line, curs_col);
4879 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004880 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004881 {
4882 return get_filename_compl_info(line, startcol, curs_col);
4883 }
4884 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4885 {
4886 return get_cmdline_compl_info(line, curs_col);
4887 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004888 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004889 || thesaurus_func_complete(ctrl_x_mode))
4890 {
4891 if (get_userdefined_compl_info(curs_col) == FAIL)
4892 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004893 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004894 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004895 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004896 {
4897 if (get_spell_compl_info(startcol, curs_col) == FAIL)
4898 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004899 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004900 }
4901 else
4902 {
4903 internal_error("ins_complete()");
4904 return FAIL;
4905 }
4906
4907 return OK;
4908}
4909
4910/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004911 * Continue an interrupted completion mode search in "line".
4912 *
4913 * If this same ctrl_x_mode has been interrupted use the text from
4914 * "compl_startpos" to the cursor as a pattern to add a new word instead of
4915 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
4916 * the same line as the cursor then fix it (the line has been split because it
4917 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
4918 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004919 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004920 static void
4921ins_compl_continue_search(char_u *line)
4922{
4923 // it is a continued search
4924 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004925 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
4926 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004927 {
4928 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4929 {
4930 // line (probably) wrapped, set compl_startpos to the
4931 // first non_blank in the line, if it is not a wordchar
4932 // include it to get a better pattern, but then we don't
4933 // want the "\\<" prefix, check it below
4934 compl_col = (colnr_T)getwhitecols(line);
4935 compl_startpos.col = compl_col;
4936 compl_startpos.lnum = curwin->w_cursor.lnum;
4937 compl_cont_status &= ~CONT_SOL; // clear SOL if present
4938 }
4939 else
4940 {
4941 // S_IPOS was set when we inserted a word that was at the
4942 // beginning of the line, which means that we'll go to SOL
4943 // mode but first we need to redefine compl_startpos
4944 if (compl_cont_status & CONT_S_IPOS)
4945 {
4946 compl_cont_status |= CONT_SOL;
4947 compl_startpos.col = (colnr_T)(skipwhite(
4948 line + compl_length
4949 + compl_startpos.col) - line);
4950 }
4951 compl_col = compl_startpos.col;
4952 }
4953 compl_length = curwin->w_cursor.col - (int)compl_col;
4954 // IObuff is used to add a "word from the next line" would we
4955 // have enough space? just being paranoid
4956#define MIN_SPACE 75
4957 if (compl_length > (IOSIZE - MIN_SPACE))
4958 {
4959 compl_cont_status &= ~CONT_SOL;
4960 compl_length = (IOSIZE - MIN_SPACE);
4961 compl_col = curwin->w_cursor.col - compl_length;
4962 }
4963 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4964 if (compl_length < 1)
4965 compl_cont_status &= CONT_LOCAL;
4966 }
4967 else if (ctrl_x_mode_line_or_eval())
4968 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4969 else
4970 compl_cont_status = 0;
4971}
4972
4973/*
4974 * start insert mode completion
4975 */
4976 static int
4977ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004978{
4979 char_u *line;
4980 int startcol = 0; // column where searched text starts
4981 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004982 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004983 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004984 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004985
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004986 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004988 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004989 did_si = FALSE;
4990 can_si = FALSE;
4991 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004992 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004993 return FAIL;
4994
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004995 line = ml_get(curwin->w_cursor.lnum);
4996 curs_col = curwin->w_cursor.col;
4997 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004998
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004999 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5000 && compl_cont_mode == ctrl_x_mode)
5001 // this same ctrl-x_mode was interrupted previously. Continue the
5002 // completion.
5003 ins_compl_continue_search(line);
5004 else
5005 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005006
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005007 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005008 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005009 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005010 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005011 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5012 compl_cont_status = 0;
5013 compl_cont_status |= CONT_N_ADDS;
5014 compl_startpos = curwin->w_cursor;
5015 startcol = (int)curs_col;
5016 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005017 }
5018
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005019 // Work out completion pattern and original text -- webb
5020 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5021 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005022 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5023 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005024 // restore did_ai, so that adding comment leader works
5025 did_ai = save_did_ai;
5026 return FAIL;
5027 }
5028 // If "line" was changed while getting completion info get it again.
5029 if (line_invalid)
5030 line = ml_get(curwin->w_cursor.lnum);
5031
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005032 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005033 {
5034 edit_submode_pre = (char_u *)_(" Adding");
5035 if (ctrl_x_mode_line_or_eval())
5036 {
5037 // Insert a new line, keep indentation but ignore 'comments'.
5038 char_u *old = curbuf->b_p_com;
5039
5040 curbuf->b_p_com = (char_u *)"";
5041 compl_startpos.lnum = curwin->w_cursor.lnum;
5042 compl_startpos.col = compl_col;
5043 ins_eol('\r');
5044 curbuf->b_p_com = old;
5045 compl_length = 0;
5046 compl_col = curwin->w_cursor.col;
5047 }
5048 }
5049 else
5050 {
5051 edit_submode_pre = NULL;
5052 compl_startpos.col = compl_col;
5053 }
5054
5055 if (compl_cont_status & CONT_LOCAL)
5056 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5057 else
5058 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5059
5060 // If any of the original typed text has been changed we need to fix
5061 // the redo buffer.
5062 ins_compl_fixRedoBufForLeader(NULL);
5063
5064 // Always add completion for the original text.
5065 vim_free(compl_orig_text);
5066 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5067 if (p_ic)
5068 flags |= CP_ICASE;
5069 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5070 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
5071 {
5072 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005073 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005074 VIM_CLEAR(compl_orig_text);
5075 return FAIL;
5076 }
5077
5078 // showmode might reset the internal line pointers, so it must
5079 // be called before line = ml_get(), or when this address is no
5080 // longer needed. -- Acevedo.
5081 edit_submode_extra = (char_u *)_("-- Searching...");
5082 edit_submode_highl = HLF_COUNT;
5083 showmode();
5084 edit_submode_extra = NULL;
5085 out_flush();
5086
5087 return OK;
5088}
5089
5090/*
5091 * display the completion status message
5092 */
5093 static void
5094ins_compl_show_statusmsg(void)
5095{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005096 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005097 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005098 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005099 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005100 ? (char_u *)_("Hit end of paragraph")
5101 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005102 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005103 }
5104
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005105 if (edit_submode_extra == NULL)
5106 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005107 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005108 {
5109 edit_submode_extra = (char_u *)_("Back at original");
5110 edit_submode_highl = HLF_W;
5111 }
5112 else if (compl_cont_status & CONT_S_IPOS)
5113 {
5114 edit_submode_extra = (char_u *)_("Word from other line");
5115 edit_submode_highl = HLF_COUNT;
5116 }
5117 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5118 {
5119 edit_submode_extra = (char_u *)_("The only match");
5120 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005121 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005122 }
5123 else
5124 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005125#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005126 // Update completion sequence number when needed.
5127 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005128 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005129#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005130 // The match should always have a sequence number now, this is
5131 // just a safety check.
5132 if (compl_curr_match->cp_number != -1)
5133 {
5134 // Space for 10 text chars. + 2x10-digit no.s = 31.
5135 // Translations may need more than twice that.
5136 static char_u match_ref[81];
5137
5138 if (compl_matches > 0)
5139 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005140 _("match %d of %d"),
5141 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005142 else
5143 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005144 _("match %d"),
5145 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005146 edit_submode_extra = match_ref;
5147 edit_submode_highl = HLF_R;
5148 if (dollar_vcol >= 0)
5149 curs_columns(FALSE);
5150 }
5151 }
5152 }
5153
5154 // Show a message about what (completion) mode we're in.
5155 if (!compl_opt_suppress_empty)
5156 {
5157 showmode();
5158 if (!shortmess(SHM_COMPLETIONMENU))
5159 {
5160 if (edit_submode_extra != NULL)
5161 {
5162 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005163 {
5164 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005165 msg_attr((char *)edit_submode_extra,
5166 edit_submode_highl < HLF_COUNT
5167 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005168 msg_hist_off = FALSE;
5169 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005170 }
5171 else
5172 msg_clr_cmdline(); // necessary for "noshowmode"
5173 }
5174 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005175}
5176
5177/*
5178 * Do Insert mode completion.
5179 * Called when character "c" was typed, which has a meaning for completion.
5180 * Returns OK if completion was done, FAIL if something failed (out of mem).
5181 */
5182 int
5183ins_complete(int c, int enable_pum)
5184{
5185 int n;
5186 int save_w_wrow;
5187 int save_w_leftcol;
5188 int insert_match;
5189
5190 compl_direction = ins_compl_key2dir(c);
5191 insert_match = ins_compl_use_match(c);
5192
5193 if (!compl_started)
5194 {
5195 if (ins_compl_start() == FAIL)
5196 return FAIL;
5197 }
5198 else if (insert_match && stop_arrow() == FAIL)
5199 return FAIL;
5200
5201 compl_shown_match = compl_curr_match;
5202 compl_shows_dir = compl_direction;
5203
5204 // Find next match (and following matches).
5205 save_w_wrow = curwin->w_wrow;
5206 save_w_leftcol = curwin->w_leftcol;
5207 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5208
5209 // may undisplay the popup menu
5210 ins_compl_upd_pum();
5211
5212 if (n > 1) // all matches have been found
5213 compl_matches = n;
5214 compl_curr_match = compl_shown_match;
5215 compl_direction = compl_shows_dir;
5216
5217 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5218 // mode.
5219 if (got_int && !global_busy)
5220 {
5221 (void)vgetc();
5222 got_int = FALSE;
5223 }
5224
5225 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005226 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005227 {
5228 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5229 // because we couldn't expand anything at first place, but if we used
5230 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5231 // (such as M in M'exico) if not tried already. -- Acevedo
5232 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005233 || compl_status_adding()
5234 || (ctrl_x_mode_not_default()
5235 && !ctrl_x_mode_path_patterns()
5236 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005237 compl_cont_status &= ~CONT_N_ADDS;
5238 }
5239
5240 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5241 compl_cont_status |= CONT_S_IPOS;
5242 else
5243 compl_cont_status &= ~CONT_S_IPOS;
5244
5245 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005246
5247 // Show the popup menu, unless we got interrupted.
5248 if (enable_pum && !compl_interrupted)
5249 show_pum(save_w_wrow, save_w_leftcol);
5250
5251 compl_was_interrupted = compl_interrupted;
5252 compl_interrupted = FALSE;
5253
5254 return OK;
5255}
5256
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005257/*
5258 * Remove (if needed) and show the popup menu
5259 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005260 static void
5261show_pum(int prev_w_wrow, int prev_w_leftcol)
5262{
5263 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005264 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005265 RedrawingDisabled = 0;
5266
5267 // If the cursor moved or the display scrolled we need to remove the pum
5268 // first.
5269 setcursor();
5270 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5271 ins_compl_del_pum();
5272
5273 ins_compl_show_pum();
5274 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005275
5276 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005277}
5278
5279/*
5280 * Looks in the first "len" chars. of "src" for search-metachars.
5281 * If dest is not NULL the chars. are copied there quoting (with
5282 * a backslash) the metachars, and dest would be NUL terminated.
5283 * Returns the length (needed) of dest
5284 */
5285 static unsigned
5286quote_meta(char_u *dest, char_u *src, int len)
5287{
5288 unsigned m = (unsigned)len + 1; // one extra for the NUL
5289
5290 for ( ; --len >= 0; src++)
5291 {
5292 switch (*src)
5293 {
5294 case '.':
5295 case '*':
5296 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005297 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005298 break;
5299 // FALLTHROUGH
5300 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005301 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005302 break;
5303 // FALLTHROUGH
5304 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005305 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005306 break;
5307 // FALLTHROUGH
5308 case '^': // currently it's not needed.
5309 case '$':
5310 m++;
5311 if (dest != NULL)
5312 *dest++ = '\\';
5313 break;
5314 }
5315 if (dest != NULL)
5316 *dest++ = *src;
5317 // Copy remaining bytes of a multibyte character.
5318 if (has_mbyte)
5319 {
5320 int i, mb_len;
5321
5322 mb_len = (*mb_ptr2len)(src) - 1;
5323 if (mb_len > 0 && len >= mb_len)
5324 for (i = 0; i < mb_len; ++i)
5325 {
5326 --len;
5327 ++src;
5328 if (dest != NULL)
5329 *dest++ = *src;
5330 }
5331 }
5332 }
5333 if (dest != NULL)
5334 *dest = NUL;
5335
5336 return m;
5337}
5338
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005339#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005340 void
5341free_insexpand_stuff(void)
5342{
5343 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005344# ifdef FEAT_EVAL
5345 free_callback(&cfu_cb);
5346 free_callback(&ofu_cb);
5347 free_callback(&tsrfu_cb);
5348# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005349}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005350#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005351
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005352#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005353/*
5354 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5355 * spelled word, if there is one.
5356 */
5357 static void
5358spell_back_to_badword(void)
5359{
5360 pos_T tpos = curwin->w_cursor;
5361
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005362 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005363 if (curwin->w_cursor.col != tpos.col)
5364 start_arrow(&tpos);
5365}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005366#endif