blob: 7066be8f38b9b000a7428c476ff9c23cdfaa2764 [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
1206ins_compl_fuzzy_sort(const void *a, const void *b)
1207{
1208 const int sa = (*(pumitem_T *)a).pum_score;
1209 const int sb = (*(pumitem_T *)b).pum_score;
1210 return sa == sb ? 0 : sa < sb ? 1 : -1;
1211}
1212
1213/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001214 * Build a popup menu to show the completion matches.
1215 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1216 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001217 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001218 static int
1219ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001220{
1221 compl_T *compl;
1222 compl_T *shown_compl = NULL;
1223 int did_find_shown_match = FALSE;
1224 int shown_match_ok = FALSE;
1225 int i;
1226 int cur = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227 int lead_len = 0;
glepnira218cc62024-06-03 19:32:39 +02001228 int max_fuzzy_score = 0;
zeertzjq529b9ad2024-06-05 20:27:06 +02001229 int cur_cot_flags = get_cot_flags();
1230 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1231 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001232
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001233 // Need to build the popup menu list.
1234 compl_match_arraysize = 0;
1235 compl = compl_first_match;
1236 if (compl_leader != NULL)
1237 lead_len = (int)STRLEN(compl_leader);
1238
1239 do
1240 {
zeertzjq551d8c32024-06-05 19:53:32 +02001241 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1242 // set the cp_score for later comparisons.
glepnira218cc62024-06-03 19:32:39 +02001243 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1244 compl->cp_score = fuzzy_match_str(compl->cp_str, compl_leader);
1245
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001246 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001247 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001248 || ins_compl_equal(compl, compl_leader, lead_len)
1249 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001250 ++compl_match_arraysize;
1251 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001252 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001253
1254 if (compl_match_arraysize == 0)
1255 return -1;
1256
1257 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1258 if (compl_match_array == NULL)
1259 return -1;
1260
1261 // If the current match is the original text don't find the first
1262 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001263 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001264 shown_match_ok = TRUE;
1265
glepnir53387c52024-05-27 15:11:01 +02001266 if (compl_leader != NULL
1267 && STRCMP(compl_leader, compl_orig_text) == 0
1268 && shown_match_ok == FALSE)
1269 compl_shown_match = compl_no_select ? compl_first_match
1270 : compl_first_match->cp_next;
1271
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001272 i = 0;
1273 compl = compl_first_match;
1274 do
1275 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001276 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001277 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001278 || ins_compl_equal(compl, compl_leader, lead_len)
1279 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001280 {
glepnira218cc62024-06-03 19:32:39 +02001281 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001282 {
1283 if (compl == compl_shown_match || did_find_shown_match)
1284 {
1285 // This item is the shown match or this is the
1286 // first displayed item after the shown match.
1287 compl_shown_match = compl;
1288 did_find_shown_match = TRUE;
1289 shown_match_ok = TRUE;
1290 }
1291 else
1292 // Remember this displayed match for when the
1293 // shown match is just below it.
1294 shown_compl = compl;
1295 cur = i;
1296 }
glepnira218cc62024-06-03 19:32:39 +02001297 else if (compl_fuzzy_match)
1298 {
glepnirdca57fb2024-06-04 22:01:21 +02001299 // Update the maximum fuzzy score and the shown match
1300 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001301 if (compl->cp_score > max_fuzzy_score)
1302 {
1303 did_find_shown_match = TRUE;
1304 max_fuzzy_score = compl->cp_score;
1305 compl_shown_match = compl;
1306 shown_match_ok = TRUE;
1307 }
1308
glepnirdca57fb2024-06-04 22:01:21 +02001309 // If there is no "no select" condition and the max fuzzy
1310 // score is positive, or there is no completion leader or the
1311 // leader length is zero, mark the shown match as valid and
1312 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001313 if (!compl_no_select
1314 && (max_fuzzy_score > 0
1315 || (compl_leader == NULL || lead_len == 0)))
1316 {
1317 shown_match_ok = TRUE;
1318 cur = 0;
1319 }
1320 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001321
1322 if (compl->cp_text[CPT_ABBR] != NULL)
1323 compl_match_array[i].pum_text =
1324 compl->cp_text[CPT_ABBR];
1325 else
1326 compl_match_array[i].pum_text = compl->cp_str;
1327 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1328 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001329 compl_match_array[i].pum_score = compl->cp_score;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001330 if (compl->cp_text[CPT_MENU] != NULL)
1331 compl_match_array[i++].pum_extra =
1332 compl->cp_text[CPT_MENU];
1333 else
1334 compl_match_array[i++].pum_extra = compl->cp_fname;
1335 }
1336
glepnira218cc62024-06-03 19:32:39 +02001337 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001338 {
1339 did_find_shown_match = TRUE;
1340
1341 // When the original text is the shown match don't set
1342 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001343 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001344 shown_match_ok = TRUE;
1345
1346 if (!shown_match_ok && shown_compl != NULL)
1347 {
1348 // The shown match isn't displayed, set it to the
1349 // previously displayed match.
1350 compl_shown_match = shown_compl;
1351 shown_match_ok = TRUE;
1352 }
1353 }
1354 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001355 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001356
glepnira218cc62024-06-03 19:32:39 +02001357 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1358 // sort by the largest score of fuzzy match
1359 qsort(compl_match_array, (size_t)compl_match_arraysize, sizeof(pumitem_T), ins_compl_fuzzy_sort);
1360
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001361 if (!shown_match_ok) // no displayed match at all
1362 cur = -1;
1363
1364 return cur;
1365}
1366
1367/*
1368 * Show the popup menu for the list of matches.
1369 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1370 */
1371 void
1372ins_compl_show_pum(void)
1373{
1374 int i;
1375 int cur = -1;
1376 colnr_T col;
1377
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001378 if (!pum_wanted() || !pum_enough_matches())
1379 return;
1380
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001381 // Update the screen later, before drawing the popup menu over it.
1382 pum_call_update_screen();
1383
1384 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001385 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001386 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001387 else
1388 {
1389 // popup menu already exists, only need to find the current item.
1390 for (i = 0; i < compl_match_arraysize; ++i)
1391 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1392 || compl_match_array[i].pum_text
1393 == compl_shown_match->cp_text[CPT_ABBR])
1394 {
1395 cur = i;
1396 break;
1397 }
1398 }
1399
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001400 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001401 {
1402#ifdef FEAT_EVAL
1403 if (compl_started && has_completechanged())
1404 trigger_complete_changed_event(cur);
1405#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001406 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001407 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001408
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001409 // In Replace mode when a $ is displayed at the end of the line only
1410 // part of the screen would be updated. We do need to redraw here.
1411 dollar_vcol = -1;
1412
1413 // Compute the screen column of the start of the completed text.
1414 // Use the cursor to get all wrapping and other settings right.
1415 col = curwin->w_cursor.col;
1416 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001417 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001418 pum_display(compl_match_array, compl_match_arraysize, cur);
1419 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001420
glepnircbb46b42024-02-03 18:11:13 +01001421 // After adding leader, set the current match to shown match.
1422 if (compl_started && compl_curr_match != compl_shown_match)
1423 compl_curr_match = compl_shown_match;
1424
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001425#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001426 if (has_completechanged())
1427 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001428#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001429}
1430
1431#define DICT_FIRST (1) // use just first element in "dict"
1432#define DICT_EXACT (2) // "dict" is the exact name of a file
1433
1434/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001435 * Add any identifiers that match the given pattern "pat" in the list of
1436 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001437 */
1438 static void
1439ins_compl_dictionaries(
1440 char_u *dict_start,
1441 char_u *pat,
1442 int flags, // DICT_FIRST and/or DICT_EXACT
1443 int thesaurus) // Thesaurus completion
1444{
1445 char_u *dict = dict_start;
1446 char_u *ptr;
1447 char_u *buf;
1448 regmatch_T regmatch;
1449 char_u **files;
1450 int count;
1451 int save_p_scs;
1452 int dir = compl_direction;
1453
1454 if (*dict == NUL)
1455 {
1456#ifdef FEAT_SPELL
1457 // When 'dictionary' is empty and spell checking is enabled use
1458 // "spell".
1459 if (!thesaurus && curwin->w_p_spell)
1460 dict = (char_u *)"spell";
1461 else
1462#endif
1463 return;
1464 }
1465
1466 buf = alloc(LSIZE);
1467 if (buf == NULL)
1468 return;
1469 regmatch.regprog = NULL; // so that we can goto theend
1470
1471 // If 'infercase' is set, don't use 'smartcase' here
1472 save_p_scs = p_scs;
1473 if (curbuf->b_p_inf)
1474 p_scs = FALSE;
1475
1476 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1477 // to only match at the start of a line. Otherwise just match the
1478 // pattern. Also need to double backslashes.
1479 if (ctrl_x_mode_line_or_eval())
1480 {
1481 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1482 size_t len;
1483
1484 if (pat_esc == NULL)
1485 goto theend;
1486 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001487 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001488 if (ptr == NULL)
1489 {
1490 vim_free(pat_esc);
1491 goto theend;
1492 }
1493 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1494 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1495 vim_free(pat_esc);
1496 vim_free(ptr);
1497 }
1498 else
1499 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001500 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001501 if (regmatch.regprog == NULL)
1502 goto theend;
1503 }
1504
1505 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1506 regmatch.rm_ic = ignorecase(pat);
1507 while (*dict != NUL && !got_int && !compl_interrupted)
1508 {
1509 // copy one dictionary file name into buf
1510 if (flags == DICT_EXACT)
1511 {
1512 count = 1;
1513 files = &dict;
1514 }
1515 else
1516 {
1517 // Expand wildcards in the dictionary name, but do not allow
1518 // backticks (for security, the 'dict' option may have been set in
1519 // a modeline).
1520 copy_option_part(&dict, buf, LSIZE, ",");
1521# ifdef FEAT_SPELL
1522 if (!thesaurus && STRCMP(buf, "spell") == 0)
1523 count = -1;
1524 else
1525# endif
1526 if (vim_strchr(buf, '`') != NULL
1527 || expand_wildcards(1, &buf, &count, &files,
1528 EW_FILE|EW_SILENT) != OK)
1529 count = 0;
1530 }
1531
1532# ifdef FEAT_SPELL
1533 if (count == -1)
1534 {
1535 // Complete from active spelling. Skip "\<" in the pattern, we
1536 // don't use it as a RE.
1537 if (pat[0] == '\\' && pat[1] == '<')
1538 ptr = pat + 2;
1539 else
1540 ptr = pat;
1541 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1542 }
1543 else
1544# endif
1545 if (count > 0) // avoid warning for using "files" uninit
1546 {
1547 ins_compl_files(count, files, thesaurus, flags,
1548 &regmatch, buf, &dir);
1549 if (flags != DICT_EXACT)
1550 FreeWild(count, files);
1551 }
1552 if (flags != 0)
1553 break;
1554 }
1555
1556theend:
1557 p_scs = save_p_scs;
1558 vim_regfree(regmatch.regprog);
1559 vim_free(buf);
1560}
1561
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001562/*
1563 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1564 * skipping the word at 'skip_word'. Returns OK on success.
1565 */
1566 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001567thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001568 char_u *fname,
1569 char_u **buf_arg,
1570 int dir,
1571 char_u *skip_word)
1572{
1573 int status = OK;
1574 char_u *ptr;
1575 char_u *wstart;
1576
1577 // Add the other matches on the line
1578 ptr = *buf_arg;
1579 while (!got_int)
1580 {
1581 // Find start of the next word. Skip white
1582 // space and punctuation.
1583 ptr = find_word_start(ptr);
1584 if (*ptr == NUL || *ptr == NL)
1585 break;
1586 wstart = ptr;
1587
1588 // Find end of the word.
1589 if (has_mbyte)
1590 // Japanese words may have characters in
1591 // different classes, only separate words
1592 // with single-byte non-word characters.
1593 while (*ptr != NUL)
1594 {
1595 int l = (*mb_ptr2len)(ptr);
1596
1597 if (l < 2 && !vim_iswordc(*ptr))
1598 break;
1599 ptr += l;
1600 }
1601 else
1602 ptr = find_word_end(ptr);
1603
1604 // Add the word. Skip the regexp match.
1605 if (wstart != skip_word)
1606 {
1607 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1608 fname, dir, FALSE);
1609 if (status == FAIL)
1610 break;
1611 }
1612 }
1613
1614 *buf_arg = ptr;
1615 return status;
1616}
1617
1618/*
1619 * Process "count" dictionary/thesaurus "files" and add the text matching
1620 * "regmatch".
1621 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001622 static void
1623ins_compl_files(
1624 int count,
1625 char_u **files,
1626 int thesaurus,
1627 int flags,
1628 regmatch_T *regmatch,
1629 char_u *buf,
1630 int *dir)
1631{
1632 char_u *ptr;
1633 int i;
1634 FILE *fp;
1635 int add_r;
1636
1637 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1638 {
1639 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001640 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001641 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001642 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001643 vim_snprintf((char *)IObuff, IOSIZE,
1644 _("Scanning dictionary: %s"), (char *)files[i]);
1645 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1646 }
1647
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001648 if (fp == NULL)
1649 continue;
1650
1651 // Read dictionary file line by line.
1652 // Check each line for a match.
1653 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001654 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001655 ptr = buf;
1656 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001657 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001658 ptr = regmatch->startp[0];
1659 if (ctrl_x_mode_line_or_eval())
1660 ptr = find_line_end(ptr);
1661 else
1662 ptr = find_word_end(ptr);
1663 add_r = ins_compl_add_infercase(regmatch->startp[0],
1664 (int)(ptr - regmatch->startp[0]),
1665 p_ic, files[i], *dir, FALSE);
1666 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001667 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001668 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001669 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001670 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001671 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001672 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001673 if (add_r == OK)
1674 // if dir was BACKWARD then honor it just once
1675 *dir = FORWARD;
1676 else if (add_r == FAIL)
1677 break;
1678 // avoid expensive call to vim_regexec() when at end
1679 // of line
1680 if (*ptr == '\n' || got_int)
1681 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001682 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001683 line_breakcheck();
1684 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001685 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001686 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001687 }
1688}
1689
1690/*
1691 * Find the start of the next word.
1692 * Returns a pointer to the first char of the word. Also stops at a NUL.
1693 */
1694 char_u *
1695find_word_start(char_u *ptr)
1696{
1697 if (has_mbyte)
1698 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1699 ptr += (*mb_ptr2len)(ptr);
1700 else
1701 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1702 ++ptr;
1703 return ptr;
1704}
1705
1706/*
1707 * Find the end of the word. Assumes it starts inside a word.
1708 * Returns a pointer to just after the word.
1709 */
1710 char_u *
1711find_word_end(char_u *ptr)
1712{
1713 int start_class;
1714
1715 if (has_mbyte)
1716 {
1717 start_class = mb_get_class(ptr);
1718 if (start_class > 1)
1719 while (*ptr != NUL)
1720 {
1721 ptr += (*mb_ptr2len)(ptr);
1722 if (mb_get_class(ptr) != start_class)
1723 break;
1724 }
1725 }
1726 else
1727 while (vim_iswordc(*ptr))
1728 ++ptr;
1729 return ptr;
1730}
1731
1732/*
1733 * Find the end of the line, omitting CR and NL at the end.
1734 * Returns a pointer to just after the line.
1735 */
1736 static char_u *
1737find_line_end(char_u *ptr)
1738{
1739 char_u *s;
1740
1741 s = ptr + STRLEN(ptr);
1742 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1743 --s;
1744 return s;
1745}
1746
1747/*
1748 * Free the list of completions
1749 */
1750 static void
1751ins_compl_free(void)
1752{
1753 compl_T *match;
1754 int i;
1755
1756 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001757 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001758 VIM_CLEAR(compl_leader);
1759
1760 if (compl_first_match == NULL)
1761 return;
1762
1763 ins_compl_del_pum();
1764 pum_clear();
1765
1766 compl_curr_match = compl_first_match;
1767 do
1768 {
1769 match = compl_curr_match;
1770 compl_curr_match = compl_curr_match->cp_next;
1771 vim_free(match->cp_str);
1772 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001773 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001774 vim_free(match->cp_fname);
1775 for (i = 0; i < CPT_COUNT; ++i)
1776 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001777#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001778 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001779#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001780 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001781 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001782 compl_first_match = compl_curr_match = NULL;
1783 compl_shown_match = NULL;
1784 compl_old_match = NULL;
1785}
1786
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001787/*
1788 * Reset/clear the completion state.
1789 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001790 void
1791ins_compl_clear(void)
1792{
1793 compl_cont_status = 0;
1794 compl_started = FALSE;
1795 compl_matches = 0;
1796 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001797 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001798 VIM_CLEAR(compl_leader);
1799 edit_submode_extra = NULL;
1800 VIM_CLEAR(compl_orig_text);
1801 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001802#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001803 // clear v:completed_item
1804 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001805#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001806}
1807
1808/*
1809 * Return TRUE when Insert completion is active.
1810 */
1811 int
1812ins_compl_active(void)
1813{
1814 return compl_started;
1815}
1816
1817/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001818 * Selected one of the matches. When FALSE the match was edited or using the
1819 * longest common string.
1820 */
1821 int
1822ins_compl_used_match(void)
1823{
1824 return compl_used_match;
1825}
1826
1827/*
1828 * Initialize get longest common string.
1829 */
1830 void
1831ins_compl_init_get_longest(void)
1832{
1833 compl_get_longest = FALSE;
1834}
1835
1836/*
1837 * Returns TRUE when insert completion is interrupted.
1838 */
1839 int
1840ins_compl_interrupted(void)
1841{
1842 return compl_interrupted;
1843}
1844
1845/*
1846 * Returns TRUE if the <Enter> key selects a match in the completion popup
1847 * menu.
1848 */
1849 int
1850ins_compl_enter_selects(void)
1851{
1852 return compl_enter_selects;
1853}
1854
1855/*
1856 * Return the column where the text starts that is being completed
1857 */
1858 colnr_T
1859ins_compl_col(void)
1860{
1861 return compl_col;
1862}
1863
1864/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001865 * Return the length in bytes of the text being completed
1866 */
1867 int
1868ins_compl_len(void)
1869{
1870 return compl_length;
1871}
1872
1873/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001874 * Delete one character before the cursor and show the subset of the matches
1875 * that match the word that is now before the cursor.
1876 * Returns the character to be used, NUL if the work is done and another char
1877 * to be got from the user.
1878 */
1879 int
1880ins_compl_bs(void)
1881{
1882 char_u *line;
1883 char_u *p;
1884
1885 line = ml_get_curline();
1886 p = line + curwin->w_cursor.col;
1887 MB_PTR_BACK(line, p);
1888
1889 // Stop completion when the whole word was deleted. For Omni completion
1890 // allow the word to be deleted, we won't match everything.
1891 // Respect the 'backspace' option.
1892 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001893 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1894 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001895 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1896 - compl_length < 0))
1897 return K_BS;
1898
1899 // Deleted more than what was used to find matches or didn't finish
1900 // finding all matches: need to look for matches all over again.
1901 if (curwin->w_cursor.col <= compl_col + compl_length
1902 || ins_compl_need_restart())
1903 ins_compl_restart();
1904
1905 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001906 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001907 if (compl_leader == NULL)
1908 return K_BS;
1909
1910 ins_compl_new_leader();
1911 if (compl_shown_match != NULL)
1912 // Make sure current match is not a hidden item.
1913 compl_curr_match = compl_shown_match;
1914 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001915}
1916
1917/*
1918 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1919 * be called.
1920 */
1921 static int
1922ins_compl_need_restart(void)
1923{
1924 // Return TRUE if we didn't complete finding matches or when the
1925 // 'completefunc' returned "always" in the "refresh" dictionary item.
1926 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001927 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001928 && compl_opt_refresh_always);
1929}
1930
1931/*
1932 * Called after changing "compl_leader".
1933 * Show the popup menu with a different set of matches.
1934 * May also search for matches again if the previous search was interrupted.
1935 */
1936 static void
1937ins_compl_new_leader(void)
1938{
1939 ins_compl_del_pum();
1940 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001941 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001942 compl_used_match = FALSE;
1943
1944 if (compl_started)
1945 ins_compl_set_original_text(compl_leader);
1946 else
1947 {
1948#ifdef FEAT_SPELL
1949 spell_bad_len = 0; // need to redetect bad word
1950#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001951 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001952 // the popup menu display the changed text before the cursor. Set
1953 // "compl_restarting" to avoid that the first match is inserted.
1954 pum_call_update_screen();
1955#ifdef FEAT_GUI
1956 if (gui.in_use)
1957 {
1958 // Show the cursor after the match, not after the redrawn text.
1959 setcursor();
1960 out_flush_cursor(FALSE, FALSE);
1961 }
1962#endif
1963 compl_restarting = TRUE;
1964 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1965 compl_cont_status = 0;
1966 compl_restarting = FALSE;
1967 }
1968
1969 compl_enter_selects = !compl_used_match;
1970
1971 // Show the popup menu with a different set of matches.
1972 ins_compl_show_pum();
1973
1974 // Don't let Enter select the original text when there is no popup menu.
1975 if (compl_match_array == NULL)
1976 compl_enter_selects = FALSE;
1977}
1978
1979/*
1980 * Return the length of the completion, from the completion start column to
1981 * the cursor column. Making sure it never goes below zero.
1982 */
1983 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001984get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001985{
1986 int off = (int)curwin->w_cursor.col - (int)compl_col;
1987
1988 if (off < 0)
1989 return 0;
1990 return off;
1991}
1992
1993/*
1994 * Append one character to the match leader. May reduce the number of
1995 * matches.
1996 */
1997 void
1998ins_compl_addleader(int c)
1999{
2000 int cc;
2001
2002 if (stop_arrow() == FAIL)
2003 return;
2004 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2005 {
2006 char_u buf[MB_MAXBYTES + 1];
2007
2008 (*mb_char2bytes)(c, buf);
2009 buf[cc] = NUL;
2010 ins_char_bytes(buf, cc);
2011 if (compl_opt_refresh_always)
2012 AppendToRedobuff(buf);
2013 }
2014 else
2015 {
2016 ins_char(c);
2017 if (compl_opt_refresh_always)
2018 AppendCharToRedobuff(c);
2019 }
2020
2021 // If we didn't complete finding matches we must search again.
2022 if (ins_compl_need_restart())
2023 ins_compl_restart();
2024
2025 // When 'always' is set, don't reset compl_leader. While completing,
2026 // cursor doesn't point original position, changing compl_leader would
2027 // break redo.
2028 if (!compl_opt_refresh_always)
2029 {
2030 vim_free(compl_leader);
2031 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002032 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002033 if (compl_leader != NULL)
2034 ins_compl_new_leader();
2035 }
2036}
2037
2038/*
2039 * Setup for finding completions again without leaving CTRL-X mode. Used when
2040 * BS or a key was typed while still searching for matches.
2041 */
2042 static void
2043ins_compl_restart(void)
2044{
2045 ins_compl_free();
2046 compl_started = FALSE;
2047 compl_matches = 0;
2048 compl_cont_status = 0;
2049 compl_cont_mode = 0;
2050}
2051
2052/*
2053 * Set the first match, the original text.
2054 */
2055 static void
2056ins_compl_set_original_text(char_u *str)
2057{
2058 char_u *p;
2059
2060 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002061 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2062 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002063 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002064 {
2065 p = vim_strsave(str);
2066 if (p != NULL)
2067 {
2068 vim_free(compl_first_match->cp_str);
2069 compl_first_match->cp_str = p;
2070 }
2071 }
2072 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002073 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002074 {
2075 p = vim_strsave(str);
2076 if (p != NULL)
2077 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002078 vim_free(compl_first_match->cp_prev->cp_str);
2079 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002080 }
2081 }
2082}
2083
2084/*
2085 * Append one character to the match leader. May reduce the number of
2086 * matches.
2087 */
2088 void
2089ins_compl_addfrommatch(void)
2090{
2091 char_u *p;
2092 int len = (int)curwin->w_cursor.col - (int)compl_col;
2093 int c;
2094 compl_T *cp;
2095
2096 p = compl_shown_match->cp_str;
2097 if ((int)STRLEN(p) <= len) // the match is too short
2098 {
2099 // When still at the original match use the first entry that matches
2100 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002101 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002102 return;
2103
2104 p = NULL;
2105 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002106 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002107 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002108 if (compl_leader == NULL
2109 || ins_compl_equal(cp, compl_leader,
2110 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002111 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002112 p = cp->cp_str;
2113 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002114 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002115 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002116 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002117 return;
2118 }
2119 p += len;
2120 c = PTR2CHAR(p);
2121 ins_compl_addleader(c);
2122}
2123
2124/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002125 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002126 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2127 * compl_cont_mode and compl_cont_status.
2128 * Returns TRUE when the character is not to be inserted.
2129 */
2130 static int
2131set_ctrl_x_mode(int c)
2132{
2133 int retval = FALSE;
2134
2135 switch (c)
2136 {
2137 case Ctrl_E:
2138 case Ctrl_Y:
2139 // scroll the window one line up or down
2140 ctrl_x_mode = CTRL_X_SCROLL;
2141 if (!(State & REPLACE_FLAG))
2142 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2143 else
2144 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2145 edit_submode_pre = NULL;
2146 showmode();
2147 break;
2148 case Ctrl_L:
2149 // complete whole line
2150 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2151 break;
2152 case Ctrl_F:
2153 // complete filenames
2154 ctrl_x_mode = CTRL_X_FILES;
2155 break;
2156 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002157 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002158 ctrl_x_mode = CTRL_X_DICTIONARY;
2159 break;
2160 case Ctrl_R:
2161 // Register insertion without exiting CTRL-X mode
2162 // Simply allow ^R to happen without affecting ^X mode
2163 break;
2164 case Ctrl_T:
2165 // complete words from a thesaurus
2166 ctrl_x_mode = CTRL_X_THESAURUS;
2167 break;
2168#ifdef FEAT_COMPL_FUNC
2169 case Ctrl_U:
2170 // user defined completion
2171 ctrl_x_mode = CTRL_X_FUNCTION;
2172 break;
2173 case Ctrl_O:
2174 // omni completion
2175 ctrl_x_mode = CTRL_X_OMNI;
2176 break;
2177#endif
2178 case 's':
2179 case Ctrl_S:
2180 // complete spelling suggestions
2181 ctrl_x_mode = CTRL_X_SPELL;
2182#ifdef FEAT_SPELL
2183 ++emsg_off; // Avoid getting the E756 error twice.
2184 spell_back_to_badword();
2185 --emsg_off;
2186#endif
2187 break;
2188 case Ctrl_RSB:
2189 // complete tag names
2190 ctrl_x_mode = CTRL_X_TAGS;
2191 break;
2192#ifdef FEAT_FIND_ID
2193 case Ctrl_I:
2194 case K_S_TAB:
2195 // complete keywords from included files
2196 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2197 break;
2198 case Ctrl_D:
2199 // complete definitions from included files
2200 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2201 break;
2202#endif
2203 case Ctrl_V:
2204 case Ctrl_Q:
2205 // complete vim commands
2206 ctrl_x_mode = CTRL_X_CMDLINE;
2207 break;
2208 case Ctrl_Z:
2209 // stop completion
2210 ctrl_x_mode = CTRL_X_NORMAL;
2211 edit_submode = NULL;
2212 showmode();
2213 retval = TRUE;
2214 break;
2215 case Ctrl_P:
2216 case Ctrl_N:
2217 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2218 // just started ^X mode, or there were enough ^X's to cancel
2219 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2220 // do normal expansion when interrupting a different mode (say
2221 // ^X^F^X^P or ^P^X^X^P, see below)
2222 // nothing changes if interrupting mode 0, (eg, the flag
2223 // doesn't change when going to ADDING mode -- Acevedo
2224 if (!(compl_cont_status & CONT_INTRPT))
2225 compl_cont_status |= CONT_LOCAL;
2226 else if (compl_cont_mode != 0)
2227 compl_cont_status &= ~CONT_LOCAL;
2228 // FALLTHROUGH
2229 default:
2230 // If we have typed at least 2 ^X's... for modes != 0, we set
2231 // compl_cont_status = 0 (eg, as if we had just started ^X
2232 // mode).
2233 // For mode 0, we set "compl_cont_mode" to an impossible
2234 // value, in both cases ^X^X can be used to restart the same
2235 // mode (avoiding ADDING mode).
2236 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2237 // 'complete' and local ^P expansions respectively.
2238 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2239 // mode -- Acevedo
2240 if (c == Ctrl_X)
2241 {
2242 if (compl_cont_mode != 0)
2243 compl_cont_status = 0;
2244 else
2245 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2246 }
2247 ctrl_x_mode = CTRL_X_NORMAL;
2248 edit_submode = NULL;
2249 showmode();
2250 break;
2251 }
2252
2253 return retval;
2254}
2255
2256/*
2257 * Stop insert completion mode
2258 */
2259 static int
2260ins_compl_stop(int c, int prev_mode, int retval)
2261{
2262 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002263 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002264
2265 // Get here when we have finished typing a sequence of ^N and
2266 // ^P or other completion characters in CTRL-X mode. Free up
2267 // memory that was used, and make sure we can redo the insert.
2268 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2269 {
2270 // If any of the original typed text has been changed, eg when
2271 // ignorecase is set, we must add back-spaces to the redo
2272 // buffer. We add as few as necessary to delete just the part
2273 // of the original text that has changed.
2274 // When using the longest match, edited the match or used
2275 // CTRL-E then don't use the current match.
2276 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2277 ptr = compl_curr_match->cp_str;
2278 else
2279 ptr = NULL;
2280 ins_compl_fixRedoBufForLeader(ptr);
2281 }
2282
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002283 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002284
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002285 // When completing whole lines: fix indent for 'cindent'.
2286 // Otherwise, break line if it's too long.
2287 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2288 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002289 // re-indent the current line
2290 if (want_cindent)
2291 {
2292 do_c_expr_indent();
2293 want_cindent = FALSE; // don't do it again
2294 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002295 }
2296 else
2297 {
2298 int prev_col = curwin->w_cursor.col;
2299
2300 // put the cursor on the last char, for 'tw' formatting
2301 if (prev_col > 0)
2302 dec_cursor();
2303 // only format when something was inserted
2304 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2305 insertchar(NUL, 0, -1);
2306 if (prev_col > 0
2307 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2308 inc_cursor();
2309 }
2310
2311 // If the popup menu is displayed pressing CTRL-Y means accepting
2312 // the selection without inserting anything. When
2313 // compl_enter_selects is set the Enter key does the same.
2314 if ((c == Ctrl_Y || (compl_enter_selects
2315 && (c == CAR || c == K_KENTER || c == NL)))
2316 && pum_visible())
2317 retval = TRUE;
2318
2319 // CTRL-E means completion is Ended, go back to the typed text.
2320 // but only do this, if the Popup is still visible
2321 if (c == Ctrl_E)
2322 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002323 char_u *p = NULL;
2324
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002325 ins_compl_delete();
2326 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002327 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002328 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002329 p = compl_orig_text;
2330 if (p != NULL)
2331 {
2332 int compl_len = get_compl_len();
2333 int len = (int)STRLEN(p);
2334
2335 if (len > compl_len)
2336 ins_bytes_len(p + compl_len, len - compl_len);
2337 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002338 retval = TRUE;
2339 }
2340
2341 auto_format(FALSE, TRUE);
2342
2343 // Trigger the CompleteDonePre event to give scripts a chance to
2344 // act upon the completion before clearing the info, and restore
2345 // ctrl_x_mode, so that complete_info() can be used.
2346 ctrl_x_mode = prev_mode;
2347 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2348
2349 ins_compl_free();
2350 compl_started = FALSE;
2351 compl_matches = 0;
2352 if (!shortmess(SHM_COMPLETIONMENU))
2353 msg_clr_cmdline(); // necessary for "noshowmode"
2354 ctrl_x_mode = CTRL_X_NORMAL;
2355 compl_enter_selects = FALSE;
2356 if (edit_submode != NULL)
2357 {
2358 edit_submode = NULL;
2359 showmode();
2360 }
2361
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002362 if (c == Ctrl_C && cmdwin_type != 0)
2363 // Avoid the popup menu remains displayed when leaving the
2364 // command line window.
2365 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002366 // Indent now if a key was typed that is in 'cinkeys'.
2367 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2368 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002369 // Trigger the CompleteDone event to give scripts a chance to act
2370 // upon the end of completion.
2371 ins_apply_autocmds(EVENT_COMPLETEDONE);
2372
2373 return retval;
2374}
2375
2376/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002377 * Prepare for Insert mode completion, or stop it.
2378 * Called just after typing a character in Insert mode.
2379 * Returns TRUE when the character is not to be inserted;
2380 */
2381 int
2382ins_compl_prep(int c)
2383{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002384 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002385 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002386
2387 // Forget any previous 'special' messages if this is actually
2388 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2389 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2390 edit_submode_extra = NULL;
2391
zeertzjq440d4cb2023-03-02 17:51:32 +00002392 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002393 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002394 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002395 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002396 return retval;
2397
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002398#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002399 // Ignore mouse events in a popup window
2400 if (is_mouse_key(c))
2401 {
2402 // Ignore drag and release events, the position does not need to be in
2403 // the popup and it may have just closed.
2404 if (c == K_LEFTRELEASE
2405 || c == K_LEFTRELEASE_NM
2406 || c == K_MIDDLERELEASE
2407 || c == K_RIGHTRELEASE
2408 || c == K_X1RELEASE
2409 || c == K_X2RELEASE
2410 || c == K_LEFTDRAG
2411 || c == K_MIDDLEDRAG
2412 || c == K_RIGHTDRAG
2413 || c == K_X1DRAG
2414 || c == K_X2DRAG)
2415 return retval;
2416 if (popup_visible)
2417 {
2418 int row = mouse_row;
2419 int col = mouse_col;
2420 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2421
2422 if (wp != NULL && WIN_IS_POPUP(wp))
2423 return retval;
2424 }
2425 }
2426#endif
2427
zeertzjqdca29d92021-08-31 19:12:51 +02002428 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2429 {
2430 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2431 || !vim_is_ctrl_x_key(c))
2432 {
2433 // Not starting another completion mode.
2434 ctrl_x_mode = CTRL_X_CMDLINE;
2435
2436 // CTRL-X CTRL-Z should stop completion without inserting anything
2437 if (c == Ctrl_Z)
2438 retval = TRUE;
2439 }
2440 else
2441 {
2442 ctrl_x_mode = CTRL_X_CMDLINE;
2443
2444 // Other CTRL-X keys first stop completion, then start another
2445 // completion mode.
2446 ins_compl_prep(' ');
2447 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2448 }
2449 }
2450
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002451 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002452 if (ctrl_x_mode_not_defined_yet()
2453 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002454 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002455 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002456 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002457 }
2458
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002459 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002460 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2461 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002462 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002463 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002464 {
2465 // We're already in CTRL-X mode, do we stay in it?
2466 if (!vim_is_ctrl_x_key(c))
2467 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002468 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002469 ctrl_x_mode = CTRL_X_NORMAL;
2470 else
2471 ctrl_x_mode = CTRL_X_FINISHED;
2472 edit_submode = NULL;
2473 }
2474 showmode();
2475 }
2476
2477 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2478 {
2479 // Show error message from attempted keyword completion (probably
2480 // 'Pattern not found') until another key is hit, then go back to
2481 // showing what mode we are in.
2482 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002483 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002484 && c != Ctrl_R && !ins_compl_pum_key(c))
2485 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002486 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002487 }
2488 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2489 // Trigger the CompleteDone event to give scripts a chance to act
2490 // upon the (possibly failed) completion.
2491 ins_apply_autocmds(EVENT_COMPLETEDONE);
2492
LemonBoy2bf52dd2022-04-09 18:17:34 +01002493 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002494
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002495 // reset continue_* if we left expansion-mode, if we stay they'll be
2496 // (re)set properly in ins_complete()
2497 if (!vim_is_ctrl_x_key(c))
2498 {
2499 compl_cont_status = 0;
2500 compl_cont_mode = 0;
2501 }
2502
2503 return retval;
2504}
2505
2506/*
2507 * Fix the redo buffer for the completion leader replacing some of the typed
2508 * text. This inserts backspaces and appends the changed text.
2509 * "ptr" is the known leader text or NUL.
2510 */
2511 static void
2512ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2513{
2514 int len;
2515 char_u *p;
2516 char_u *ptr = ptr_arg;
2517
2518 if (ptr == NULL)
2519 {
2520 if (compl_leader != NULL)
2521 ptr = compl_leader;
2522 else
2523 return; // nothing to do
2524 }
2525 if (compl_orig_text != NULL)
2526 {
2527 p = compl_orig_text;
2528 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2529 ;
2530 if (len > 0)
2531 len -= (*mb_head_off)(p, p + len);
2532 for (p += len; *p != NUL; MB_PTR_ADV(p))
2533 AppendCharToRedobuff(K_BS);
2534 }
2535 else
2536 len = 0;
2537 if (ptr != NULL)
2538 AppendToRedobuffLit(ptr + len, -1);
2539}
2540
2541/*
2542 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2543 * (depending on flag) starting from buf and looking for a non-scanned
2544 * buffer (other than curbuf). curbuf is special, if it is called with
2545 * buf=curbuf then it has to be the first call for a given flag/expansion.
2546 *
2547 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2548 */
2549 static buf_T *
2550ins_compl_next_buf(buf_T *buf, int flag)
2551{
2552 static win_T *wp = NULL;
2553
2554 if (flag == 'w') // just windows
2555 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002556 if (buf == curbuf || !win_valid(wp))
2557 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002558 wp = curwin;
2559 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2560 && wp->w_buffer->b_scanned)
2561 ;
2562 buf = wp->w_buffer;
2563 }
2564 else
2565 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2566 // (unlisted buffers)
2567 // When completing whole lines skip unloaded buffers.
2568 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2569 && ((flag == 'U'
2570 ? buf->b_p_bl
2571 : (!buf->b_p_bl
2572 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2573 || buf->b_scanned))
2574 ;
2575 return buf;
2576}
2577
2578#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002579
2580# ifdef FEAT_EVAL
2581static callback_T cfu_cb; // 'completefunc' callback function
2582static callback_T ofu_cb; // 'omnifunc' callback function
2583static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2584# endif
2585
2586/*
2587 * Copy a global callback function to a buffer local callback.
2588 */
2589 static void
2590copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2591{
2592 free_callback(bufcb);
2593 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2594 copy_callback(bufcb, globcb);
2595}
2596
2597/*
2598 * Parse the 'completefunc' option value and set the callback function.
2599 * Invoked when the 'completefunc' option is set. The option value can be a
2600 * name of a function (string), or function(<name>) or funcref(<name>) or a
2601 * lambda expression.
2602 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002603 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002604did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002605{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002606 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2607 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002608
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002609 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002610
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002611 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002612}
2613
2614/*
2615 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002616 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002617 */
2618 void
2619set_buflocal_cfu_callback(buf_T *buf UNUSED)
2620{
2621# ifdef FEAT_EVAL
2622 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2623# endif
2624}
2625
2626/*
2627 * Parse the 'omnifunc' option value and set the callback function.
2628 * Invoked when the 'omnifunc' option is set. The option value can be a
2629 * name of a function (string), or function(<name>) or funcref(<name>) or a
2630 * lambda expression.
2631 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002632 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002633did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002634{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002635 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2636 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002637
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002638 set_buflocal_ofu_callback(curbuf);
2639 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002640}
2641
2642/*
2643 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002644 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002645 */
2646 void
2647set_buflocal_ofu_callback(buf_T *buf UNUSED)
2648{
2649# ifdef FEAT_EVAL
2650 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2651# endif
2652}
2653
2654/*
2655 * Parse the 'thesaurusfunc' option value and set the callback function.
2656 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2657 * name of a function (string), or function(<name>) or funcref(<name>) or a
2658 * lambda expression.
2659 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002660 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002661did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002662{
2663 int retval;
2664
2665 if (*curbuf->b_p_tsrfu != NUL)
2666 {
2667 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002668 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2669 &curbuf->b_tsrfu_cb);
2670 }
2671 else
2672 {
2673 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002674 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2675 }
2676
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002677 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002678}
2679
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002680/*
2681 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002682 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002683 */
2684 int
2685set_ref_in_insexpand_funcs(int copyID)
2686{
2687 int abort = FALSE;
2688
2689 abort = set_ref_in_callback(&cfu_cb, copyID);
2690 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2691 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2692
2693 return abort;
2694}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002695
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002696/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002697 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002698 */
2699 static char_u *
2700get_complete_funcname(int type)
2701{
2702 switch (type)
2703 {
2704 case CTRL_X_FUNCTION:
2705 return curbuf->b_p_cfu;
2706 case CTRL_X_OMNI:
2707 return curbuf->b_p_ofu;
2708 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002709 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002710 default:
2711 return (char_u *)"";
2712 }
2713}
2714
2715/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002716 * Get the callback to use for insert mode completion.
2717 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002718 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002719get_insert_callback(int type)
2720{
2721 if (type == CTRL_X_FUNCTION)
2722 return &curbuf->b_cfu_cb;
2723 if (type == CTRL_X_OMNI)
2724 return &curbuf->b_ofu_cb;
2725 // CTRL_X_THESAURUS
2726 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2727}
2728
2729/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002730 * Execute user defined complete function 'completefunc', 'omnifunc' or
2731 * 'thesaurusfunc', and get matches in "matches".
2732 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002733 */
2734 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002735expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002736{
2737 list_T *matchlist = NULL;
2738 dict_T *matchdict = NULL;
2739 typval_T args[3];
2740 char_u *funcname;
2741 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002742 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002743 typval_T rettv;
2744 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002745 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002746
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002747 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002748 if (*funcname == NUL)
2749 return;
2750
2751 // Call 'completefunc' to obtain the list of matches.
2752 args[0].v_type = VAR_NUMBER;
2753 args[0].vval.v_number = 0;
2754 args[1].v_type = VAR_STRING;
2755 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2756 args[2].v_type = VAR_UNKNOWN;
2757
2758 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002759 // Lock the text to avoid weird things from happening. Also disallow
2760 // switching to another window, it should not be needed and may end up in
2761 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002762 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002763
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002764 cb = get_insert_callback(type);
2765 retval = call_callback(cb, 0, &rettv, 2, args);
2766
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002767 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002768 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002769 {
2770 switch (rettv.v_type)
2771 {
2772 case VAR_LIST:
2773 matchlist = rettv.vval.v_list;
2774 break;
2775 case VAR_DICT:
2776 matchdict = rettv.vval.v_dict;
2777 break;
2778 case VAR_SPECIAL:
2779 if (rettv.vval.v_number == VVAL_NONE)
2780 compl_opt_suppress_empty = TRUE;
2781 // FALLTHROUGH
2782 default:
2783 // TODO: Give error message?
2784 clear_tv(&rettv);
2785 break;
2786 }
2787 }
zeertzjqcfe45652022-05-27 17:26:55 +01002788 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002789
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002790 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002791 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002792 validate_cursor();
2793 if (!EQUAL_POS(curwin->w_cursor, pos))
2794 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002795 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002796 goto theend;
2797 }
2798
2799 if (matchlist != NULL)
2800 ins_compl_add_list(matchlist);
2801 else if (matchdict != NULL)
2802 ins_compl_add_dict(matchdict);
2803
2804theend:
2805 // Restore State, it might have been changed.
2806 State = save_State;
2807
2808 if (matchdict != NULL)
2809 dict_unref(matchdict);
2810 if (matchlist != NULL)
2811 list_unref(matchlist);
2812}
2813#endif // FEAT_COMPL_FUNC
2814
2815#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2816/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002817 * Add a match to the list of matches from a typeval_T.
2818 * If the given string is already in the list of completions, then return
2819 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2820 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002821 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002822 */
2823 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002824ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002825{
2826 char_u *word;
2827 int dup = FALSE;
2828 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002829 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002830 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002831 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002832 int status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002833
Bram Moolenaar08928322020-01-04 14:32:48 +01002834 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002835 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2836 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002837 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2838 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2839 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2840 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2841 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
2842 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2843 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2844 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002845 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002846 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2847 dup = dict_get_number(tv->vval.v_dict, "dup");
2848 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2849 empty = dict_get_number(tv->vval.v_dict, "empty");
2850 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2851 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002852 flags |= CP_EQUAL;
2853 }
2854 else
2855 {
2856 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002857 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002858 }
2859 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002860 {
2861 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002862 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002863 }
2864 status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
2865 if (status != OK)
2866 clear_tv(&user_data);
2867 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002868}
2869
2870/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002871 * Add completions from a list.
2872 */
2873 static void
2874ins_compl_add_list(list_T *list)
2875{
2876 listitem_T *li;
2877 int dir = compl_direction;
2878
2879 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002880 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002881 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002882 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002883 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002884 // if dir was BACKWARD then honor it just once
2885 dir = FORWARD;
2886 else if (did_emsg)
2887 break;
2888 }
2889}
2890
2891/*
2892 * Add completions from a dict.
2893 */
2894 static void
2895ins_compl_add_dict(dict_T *dict)
2896{
2897 dictitem_T *di_refresh;
2898 dictitem_T *di_words;
2899
2900 // Check for optional "refresh" item.
2901 compl_opt_refresh_always = FALSE;
2902 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2903 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2904 {
2905 char_u *v = di_refresh->di_tv.vval.v_string;
2906
2907 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2908 compl_opt_refresh_always = TRUE;
2909 }
2910
2911 // Add completions from a "words" list.
2912 di_words = dict_find(dict, (char_u *)"words", 5);
2913 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2914 ins_compl_add_list(di_words->di_tv.vval.v_list);
2915}
2916
2917/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002918 * Start completion for the complete() function.
2919 * "startcol" is where the matched text starts (1 is first column).
2920 * "list" is the list of matches.
2921 */
2922 static void
2923set_completion(colnr_T startcol, list_T *list)
2924{
2925 int save_w_wrow = curwin->w_wrow;
2926 int save_w_leftcol = curwin->w_leftcol;
2927 int flags = CP_ORIGINAL_TEXT;
zeertzjq529b9ad2024-06-05 20:27:06 +02002928 int cur_cot_flags = get_cot_flags();
2929 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2930 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2931 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002932
2933 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002934 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002935 ins_compl_prep(' ');
2936 ins_compl_clear();
2937 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002938 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002939
2940 compl_direction = FORWARD;
2941 if (startcol > curwin->w_cursor.col)
2942 startcol = curwin->w_cursor.col;
2943 compl_col = startcol;
2944 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2945 // compl_pattern doesn't need to be set
2946 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2947 if (p_ic)
2948 flags |= CP_ICASE;
2949 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002950 -1, NULL, NULL, NULL, 0,
2951 flags | CP_FAST, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002952 return;
2953
2954 ctrl_x_mode = CTRL_X_EVAL;
2955
2956 ins_compl_add_list(list);
2957 compl_matches = ins_compl_make_cyclic();
2958 compl_started = TRUE;
2959 compl_used_match = TRUE;
2960 compl_cont_status = 0;
2961
2962 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01002963 int no_select = compl_no_select || compl_longest;
2964 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002965 {
2966 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01002967 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002968 // Down/Up has no real effect.
2969 ins_complete(K_UP, FALSE);
2970 }
2971 else
2972 ins_complete(Ctrl_N, FALSE);
2973 compl_enter_selects = compl_no_insert;
2974
2975 // Lazily show the popup menu, unless we got interrupted.
2976 if (!compl_interrupted)
2977 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01002978 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002979 out_flush();
2980}
2981
2982/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002983 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002984 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002985 void
2986f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002987{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002988 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002989
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002990 if (in_vim9script()
2991 && (check_for_number_arg(argvars, 0) == FAIL
2992 || check_for_list_arg(argvars, 1) == FAIL))
2993 return;
2994
Bram Moolenaar24959102022-05-07 20:01:16 +01002995 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002996 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00002997 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002998 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002999 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003000
3001 // Check for undo allowed here, because if something was already inserted
3002 // the line was already saved for undo and this check isn't done.
3003 if (!undo_allowed())
3004 return;
3005
Bram Moolenaard83392a2022-09-01 12:22:46 +01003006 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003007 {
3008 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3009 if (startcol > 0)
3010 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003011 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003012}
3013
3014/*
3015 * "complete_add()" function
3016 */
3017 void
3018f_complete_add(typval_T *argvars, typval_T *rettv)
3019{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003020 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003021 return;
3022
Bram Moolenaar440cf092021-04-03 20:13:30 +02003023 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003024}
3025
3026/*
3027 * "complete_check()" function
3028 */
3029 void
3030f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3031{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003032 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003033 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003034
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003035 ins_compl_check_keys(0, TRUE);
3036 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003037
3038 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003039}
3040
3041/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003042 * Return Insert completion mode name string
3043 */
3044 static char_u *
3045ins_compl_mode(void)
3046{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003047 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003048 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3049
3050 return (char_u *)"";
3051}
3052
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003053/*
3054 * Assign the sequence number to all the completion matches which don't have
3055 * one assigned yet.
3056 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003057 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003058ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003059{
3060 int number = 0;
3061 compl_T *match;
3062
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003063 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003064 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003065 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003066 // This should normally succeed already at the first loop
3067 // cycle, so it's fast!
3068 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003069 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003070 if (match->cp_number != -1)
3071 {
3072 number = match->cp_number;
3073 break;
3074 }
3075 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003076 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003077 for (match = match->cp_next;
3078 match != NULL && match->cp_number == -1;
3079 match = match->cp_next)
3080 match->cp_number = ++number;
3081 }
3082 else // BACKWARD
3083 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003084 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003085 // number. This should normally succeed already at the
3086 // first loop cycle, so it's fast!
3087 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003088 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003089 if (match->cp_number != -1)
3090 {
3091 number = match->cp_number;
3092 break;
3093 }
3094 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003095 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003096 for (match = match->cp_prev; match
3097 && match->cp_number == -1;
3098 match = match->cp_prev)
3099 match->cp_number = ++number;
3100 }
3101}
3102
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003103/*
3104 * Get complete information
3105 */
3106 static void
3107get_complete_info(list_T *what_list, dict_T *retdict)
3108{
3109 int ret = OK;
3110 listitem_T *item;
3111#define CI_WHAT_MODE 0x01
3112#define CI_WHAT_PUM_VISIBLE 0x02
3113#define CI_WHAT_ITEMS 0x04
3114#define CI_WHAT_SELECTED 0x08
3115#define CI_WHAT_INSERTED 0x10
3116#define CI_WHAT_ALL 0xff
3117 int what_flag;
3118
3119 if (what_list == NULL)
3120 what_flag = CI_WHAT_ALL;
3121 else
3122 {
3123 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003124 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003125 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003126 {
3127 char_u *what = tv_get_string(&item->li_tv);
3128
3129 if (STRCMP(what, "mode") == 0)
3130 what_flag |= CI_WHAT_MODE;
3131 else if (STRCMP(what, "pum_visible") == 0)
3132 what_flag |= CI_WHAT_PUM_VISIBLE;
3133 else if (STRCMP(what, "items") == 0)
3134 what_flag |= CI_WHAT_ITEMS;
3135 else if (STRCMP(what, "selected") == 0)
3136 what_flag |= CI_WHAT_SELECTED;
3137 else if (STRCMP(what, "inserted") == 0)
3138 what_flag |= CI_WHAT_INSERTED;
3139 }
3140 }
3141
3142 if (ret == OK && (what_flag & CI_WHAT_MODE))
3143 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3144
3145 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3146 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3147
Girish Palya8950bf72024-03-20 20:07:29 +01003148 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003149 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003150 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003151 dict_T *di;
3152 compl_T *match;
3153 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003154
Girish Palya8950bf72024-03-20 20:07:29 +01003155 if (what_flag & CI_WHAT_ITEMS)
3156 {
3157 li = list_alloc();
3158 if (li == NULL)
3159 return;
3160 ret = dict_add_list(retdict, "items", li);
3161 }
3162 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3163 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3164 ins_compl_update_sequence_numbers();
3165 if (ret == OK && compl_first_match != NULL)
3166 {
3167 int list_idx = 0;
3168 match = compl_first_match;
3169 do
3170 {
3171 if (!match_at_original_text(match))
3172 {
3173 if (what_flag & CI_WHAT_ITEMS)
3174 {
3175 di = dict_alloc();
3176 if (di == NULL)
3177 return;
3178 ret = list_append_dict(li, di);
3179 if (ret != OK)
3180 return;
3181 dict_add_string(di, "word", match->cp_str);
3182 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3183 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3184 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3185 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3186 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3187 // Add an empty string for backwards compatibility
3188 dict_add_string(di, "user_data", (char_u *)"");
3189 else
3190 dict_add_tv(di, "user_data", &match->cp_user_data);
3191 }
3192 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3193 selected_idx = list_idx;
3194 list_idx += 1;
3195 }
3196 match = match->cp_next;
3197 }
3198 while (match != NULL && !is_first_match(match));
3199 }
3200 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3201 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003202 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003203
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003204 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3205 {
3206 // TODO
3207 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003208}
3209
3210/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003211 * "complete_info()" function
3212 */
3213 void
3214f_complete_info(typval_T *argvars, typval_T *rettv)
3215{
3216 list_T *what_list = NULL;
3217
Bram Moolenaar93a10962022-06-16 11:42:09 +01003218 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003219 return;
3220
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003221 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3222 return;
3223
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003224 if (argvars[0].v_type != VAR_UNKNOWN)
3225 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003226 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003227 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003228 what_list = argvars[0].vval.v_list;
3229 }
3230 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003231}
3232#endif
3233
3234/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003235 * Returns TRUE when using a user-defined function for thesaurus completion.
3236 */
3237 static int
3238thesaurus_func_complete(int type UNUSED)
3239{
3240#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003241 return type == CTRL_X_THESAURUS
3242 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003243#else
3244 return FALSE;
3245#endif
3246}
3247
3248/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003249 * Return value of process_next_cpt_value()
3250 */
3251enum
3252{
3253 INS_COMPL_CPT_OK = 1,
3254 INS_COMPL_CPT_CONT,
3255 INS_COMPL_CPT_END
3256};
3257
3258/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003259 * state information used for getting the next set of insert completion
3260 * matches.
3261 */
3262typedef struct
3263{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003264 char_u *e_cpt_copy; // copy of 'complete'
3265 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003266 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003267 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003268 pos_T prev_match_pos; // previous match position
3269 int set_match_pos; // save first_match_pos/last_match_pos
3270 pos_T first_match_pos; // first match position
3271 pos_T last_match_pos; // last match position
3272 int found_all; // found all matches of a certain type.
3273 char_u *dict; // dictionary file to search
3274 int dict_f; // "dict" is an exact file name or not
3275} ins_compl_next_state_T;
3276
3277/*
3278 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003279 *
3280 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003281 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003282 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003283 * st->found_all - all matches of this type are found
3284 * st->ins_buf - search for completions in this buffer
3285 * st->first_match_pos - position of the first completion match
3286 * st->last_match_pos - position of the last completion match
3287 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003288 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003289 * st->dict - name of the dictionary or thesaurus file to search
3290 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003291 *
3292 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003293 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3294 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003295 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003296 */
3297 static int
3298process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003299 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003300 int *compl_type_arg,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003301 pos_T *start_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003302{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003303 int compl_type = -1;
3304 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003305
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003306 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003307
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003308 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3309 st->e_cpt++;
3310
3311 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003312 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003313 st->ins_buf = curbuf;
3314 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003315 // Move the cursor back one character so that ^N can match the
3316 // word immediately after the cursor.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003317 if (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003318 {
3319 // Move the cursor to after the last character in the
3320 // buffer, so that word at start of buffer is found
3321 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003322 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003323 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003324 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003325 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003326 compl_type = 0;
3327
3328 // Remember the first match so that the loop stops when we
3329 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003330 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003331 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003332 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003333 && (st->ins_buf = ins_compl_next_buf(
3334 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003335 {
3336 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003337 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003338 {
3339 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003340 st->first_match_pos.col = st->last_match_pos.col = 0;
3341 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3342 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003343 compl_type = 0;
3344 }
3345 else // unloaded buffer, scan like dictionary
3346 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003347 st->found_all = TRUE;
3348 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003349 {
3350 status = INS_COMPL_CPT_CONT;
3351 goto done;
3352 }
3353 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003354 st->dict = st->ins_buf->b_fname;
3355 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003356 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003357 if (!shortmess(SHM_COMPLETIONSCAN))
3358 {
3359 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3360 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3361 st->ins_buf->b_fname == NULL
3362 ? buf_spname(st->ins_buf)
3363 : st->ins_buf->b_sfname == NULL
3364 ? st->ins_buf->b_fname
3365 : st->ins_buf->b_sfname);
3366 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3367 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003368 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003369 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003370 status = INS_COMPL_CPT_END;
3371 else
3372 {
3373 if (ctrl_x_mode_line_or_eval())
3374 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003375 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003376 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003377 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003378 compl_type = CTRL_X_DICTIONARY;
3379 else
3380 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003381 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003382 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003383 st->dict = st->e_cpt;
3384 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003385 }
3386 }
3387#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003388 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003389 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003390 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003391 compl_type = CTRL_X_PATH_DEFINES;
3392#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003393 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003395 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003396 if (!shortmess(SHM_COMPLETIONSCAN))
3397 {
3398 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3399 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3400 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3401 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003402 }
3403 else
3404 compl_type = -1;
3405
3406 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003407 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003408
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003409 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003410 if (compl_type == -1)
3411 status = INS_COMPL_CPT_CONT;
3412 }
3413
3414done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003415 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003416 return status;
3417}
3418
3419#ifdef FEAT_FIND_ID
3420/*
3421 * Get the next set of identifiers or defines matching "compl_pattern" in
3422 * included files.
3423 */
3424 static void
3425get_next_include_file_completion(int compl_type)
3426{
3427 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003428 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003429 (compl_type == CTRL_X_PATH_DEFINES
3430 && !(compl_cont_status & CONT_SOL))
3431 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003432 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003433}
3434#endif
3435
3436/*
3437 * Get the next set of words matching "compl_pattern" in dictionary or
3438 * thesaurus files.
3439 */
3440 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003441get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003442{
3443#ifdef FEAT_COMPL_FUNC
3444 if (thesaurus_func_complete(compl_type))
3445 expand_by_function(compl_type, compl_pattern);
3446 else
3447#endif
3448 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003449 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003450 : (compl_type == CTRL_X_THESAURUS
3451 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3452 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3453 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003454 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003455 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003456}
3457
3458/*
3459 * Get the next set of tag names matching "compl_pattern".
3460 */
3461 static void
3462get_next_tag_completion(void)
3463{
3464 int save_p_ic;
3465 char_u **matches;
3466 int num_matches;
3467
3468 // set p_ic according to p_ic, p_scs and pat for find_tags().
3469 save_p_ic = p_ic;
3470 p_ic = ignorecase(compl_pattern);
3471
3472 // Find up to TAG_MANY matches. Avoids that an enormous number
3473 // of matches is found when compl_pattern is empty
3474 g_tag_at_cursor = TRUE;
3475 if (find_tags(compl_pattern, &num_matches, &matches,
3476 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003477 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003478 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3479 ins_compl_add_matches(num_matches, matches, p_ic);
3480 g_tag_at_cursor = FALSE;
3481 p_ic = save_p_ic;
3482}
3483
3484/*
3485 * Get the next set of filename matching "compl_pattern".
3486 */
3487 static void
3488get_next_filename_completion(void)
3489{
3490 char_u **matches;
3491 int num_matches;
3492
3493 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3494 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3495 return;
3496
3497 // May change home directory back to "~".
3498 tilde_replace(compl_pattern, num_matches, matches);
3499#ifdef BACKSLASH_IN_FILENAME
3500 if (curbuf->b_p_csl[0] != NUL)
3501 {
3502 int i;
3503
3504 for (i = 0; i < num_matches; ++i)
3505 {
3506 char_u *ptr = matches[i];
3507
3508 while (*ptr != NUL)
3509 {
3510 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3511 *ptr = '/';
3512 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3513 *ptr = '\\';
3514 ptr += (*mb_ptr2len)(ptr);
3515 }
3516 }
3517 }
3518#endif
3519 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
3520}
3521
3522/*
3523 * Get the next set of command-line completions matching "compl_pattern".
3524 */
3525 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003526get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003527{
3528 char_u **matches;
3529 int num_matches;
3530
3531 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003532 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003533 ins_compl_add_matches(num_matches, matches, FALSE);
3534}
3535
3536/*
3537 * Get the next set of spell suggestions matching "compl_pattern".
3538 */
3539 static void
3540get_next_spell_completion(linenr_T lnum UNUSED)
3541{
3542#ifdef FEAT_SPELL
3543 char_u **matches;
3544 int num_matches;
3545
3546 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3547 if (num_matches > 0)
3548 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003549 else
3550 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003551#endif
3552}
3553
3554/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003555 * Return the next word or line from buffer "ins_buf" at position
3556 * "cur_match_pos" for completion. The length of the match is set in "len".
3557 */
3558 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003559ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003560 buf_T *ins_buf, // buffer being scanned
3561 pos_T *cur_match_pos, // current match position
3562 int *match_len,
3563 int *cont_s_ipos) // next ^X<> will set initial_pos
3564{
3565 char_u *ptr;
3566 int len;
3567
3568 *match_len = 0;
3569 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3570 cur_match_pos->col;
3571 if (ctrl_x_mode_line_or_eval())
3572 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003573 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003574 {
3575 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3576 return NULL;
3577 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3578 if (!p_paste)
3579 ptr = skipwhite(ptr);
3580 }
3581 len = (int)STRLEN(ptr);
3582 }
3583 else
3584 {
3585 char_u *tmp_ptr = ptr;
3586
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003587 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003588 {
3589 tmp_ptr += compl_length;
3590 // Skip if already inside a word.
3591 if (vim_iswordp(tmp_ptr))
3592 return NULL;
3593 // Find start of next word.
3594 tmp_ptr = find_word_start(tmp_ptr);
3595 }
3596 // Find end of this word.
3597 tmp_ptr = find_word_end(tmp_ptr);
3598 len = (int)(tmp_ptr - ptr);
3599
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003600 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003601 {
3602 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3603 {
3604 // Try next line, if any. the new word will be
3605 // "join" as if the normal command "J" was used.
3606 // IOSIZE is always greater than
3607 // compl_length, so the next STRNCPY always
3608 // works -- Acevedo
3609 STRNCPY(IObuff, ptr, len);
3610 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3611 tmp_ptr = ptr = skipwhite(ptr);
3612 // Find start of next word.
3613 tmp_ptr = find_word_start(tmp_ptr);
3614 // Find end of next word.
3615 tmp_ptr = find_word_end(tmp_ptr);
3616 if (tmp_ptr > ptr)
3617 {
3618 if (*ptr != ')' && IObuff[len - 1] != TAB)
3619 {
3620 if (IObuff[len - 1] != ' ')
3621 IObuff[len++] = ' ';
3622 // IObuf =~ "\k.* ", thus len >= 2
3623 if (p_js
3624 && (IObuff[len - 2] == '.'
3625 || (vim_strchr(p_cpo, CPO_JOINSP)
3626 == NULL
3627 && (IObuff[len - 2] == '?'
3628 || IObuff[len - 2] == '!'))))
3629 IObuff[len++] = ' ';
3630 }
3631 // copy as much as possible of the new word
3632 if (tmp_ptr - ptr >= IOSIZE - len)
3633 tmp_ptr = ptr + IOSIZE - len - 1;
3634 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3635 len += (int)(tmp_ptr - ptr);
3636 *cont_s_ipos = TRUE;
3637 }
3638 IObuff[len] = NUL;
3639 ptr = IObuff;
3640 }
3641 if (len == compl_length)
3642 return NULL;
3643 }
3644 }
3645
3646 *match_len = len;
3647 return ptr;
3648}
3649
3650/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003651 * Get the next set of words matching "compl_pattern" for default completion(s)
3652 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003653 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3654 * position "st->start_pos" in the "compl_direction" direction. If
3655 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3656 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003657 * Returns OK if a new next match is found, otherwise returns FAIL.
3658 */
3659 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003660get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003661{
3662 int found_new_match = FAIL;
3663 int save_p_scs;
3664 int save_p_ws;
3665 int looped_around = FALSE;
3666 char_u *ptr;
3667 int len;
3668
3669 // If 'infercase' is set, don't use 'smartcase' here
3670 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003671 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003672 p_scs = FALSE;
3673
3674 // Buffers other than curbuf are scanned from the beginning or the
3675 // end but never from the middle, thus setting nowrapscan in this
3676 // buffer is a good idea, on the other hand, we always set
3677 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3678 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003679 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003680 p_ws = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003681 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003682 p_ws = TRUE;
3683 looped_around = FALSE;
3684 for (;;)
3685 {
3686 int cont_s_ipos = FALSE;
3687
3688 ++msg_silent; // Don't want messages for wrapscan.
3689
3690 // ctrl_x_mode_line_or_eval() || word-wise search that
3691 // has added a word that was at the beginning of the line
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003692 if (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003693 found_new_match = search_for_exact_line(st->ins_buf,
3694 st->cur_match_pos, compl_direction, compl_pattern);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003695 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003696 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003697 NULL, compl_direction, compl_pattern, compl_patternlen,
3698 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003699 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003700 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003701 {
3702 // set "compl_started" even on fail
3703 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003704 st->first_match_pos = *st->cur_match_pos;
3705 st->last_match_pos = *st->cur_match_pos;
3706 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003707 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003708 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3709 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003710 {
3711 found_new_match = FAIL;
3712 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003713 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003714 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3715 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3716 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003717 {
3718 if (looped_around)
3719 found_new_match = FAIL;
3720 else
3721 looped_around = TRUE;
3722 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003723 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003724 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3725 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3726 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003727 {
3728 if (looped_around)
3729 found_new_match = FAIL;
3730 else
3731 looped_around = TRUE;
3732 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003733 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003734 if (found_new_match == FAIL)
3735 break;
3736
3737 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003738 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003739 && start_pos->lnum == st->cur_match_pos->lnum
3740 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003741 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003742
zeertzjq440d4cb2023-03-02 17:51:32 +00003743 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3744 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003745 if (ptr == NULL)
3746 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003747
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003748 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003749 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003750 0, cont_s_ipos) != NOTDONE)
3751 {
3752 found_new_match = OK;
3753 break;
3754 }
3755 }
3756 p_scs = save_p_scs;
3757 p_ws = save_p_ws;
3758
3759 return found_new_match;
3760}
3761
3762/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003763 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003764 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003765 */
3766 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003767get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003768{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003769 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003770
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003771 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003772 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003773 case -1:
3774 break;
3775#ifdef FEAT_FIND_ID
3776 case CTRL_X_PATH_PATTERNS:
3777 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003778 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003779 break;
3780#endif
3781
3782 case CTRL_X_DICTIONARY:
3783 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003784 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3785 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003786 break;
3787
3788 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003789 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003790 break;
3791
3792 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003793 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003794 break;
3795
3796 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003797 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003798 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003799 break;
3800
3801#ifdef FEAT_COMPL_FUNC
3802 case CTRL_X_FUNCTION:
3803 case CTRL_X_OMNI:
3804 expand_by_function(type, compl_pattern);
3805 break;
3806#endif
3807
3808 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003809 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003810 break;
3811
3812 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003813 found_new_match = get_next_default_completion(st, ini);
3814 if (found_new_match == FAIL && st->ins_buf == curbuf)
3815 st->found_all = TRUE;
3816 }
3817
3818 // check if compl_curr_match has changed, (e.g. other type of
3819 // expansion added something)
3820 if (type != 0 && compl_curr_match != compl_old_match)
3821 found_new_match = OK;
3822
3823 return found_new_match;
3824}
3825
3826/*
3827 * Get the next expansion(s), using "compl_pattern".
3828 * The search starts at position "ini" in curbuf and in the direction
3829 * compl_direction.
3830 * When "compl_started" is FALSE start at that position, otherwise continue
3831 * where we stopped searching before.
3832 * This may return before finding all the matches.
3833 * Return the total number of matches or -1 if still unknown -- Acevedo
3834 */
3835 static int
3836ins_compl_get_exp(pos_T *ini)
3837{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003838 static ins_compl_next_state_T st;
3839 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003840 int i;
3841 int found_new_match;
3842 int type = ctrl_x_mode;
3843
3844 if (!compl_started)
3845 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003846 buf_T *buf;
3847
3848 FOR_ALL_BUFFERS(buf)
3849 buf->b_scanned = 0;
3850 if (!st_cleared)
3851 {
3852 CLEAR_FIELD(st);
3853 st_cleared = TRUE;
3854 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003855 st.found_all = FALSE;
3856 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003857 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003858 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003859 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
3860 ? (char_u *)"." : curbuf->b_p_cpt);
3861 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003862 st.last_match_pos = st.first_match_pos = *ini;
3863 }
3864 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
3865 st.ins_buf = curbuf; // In case the buffer was wiped out.
3866
3867 compl_old_match = compl_curr_match; // remember the last current match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003868 st.cur_match_pos = (compl_dir_forward())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003869 ? &st.last_match_pos : &st.first_match_pos;
3870
3871 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
3872 for (;;)
3873 {
3874 found_new_match = FAIL;
3875 st.set_match_pos = FALSE;
3876
3877 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
3878 // or if found_all says this entry is done. For ^X^L only use the
3879 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003880 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003881 && (!compl_started || st.found_all))
3882 {
3883 int status = process_next_cpt_value(&st, &type, ini);
3884
3885 if (status == INS_COMPL_CPT_END)
3886 break;
3887 if (status == INS_COMPL_CPT_CONT)
3888 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003889 }
3890
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003891 // If complete() was called then compl_pattern has been reset. The
3892 // following won't work then, bail out.
3893 if (compl_pattern == NULL)
3894 break;
3895
3896 // get the next set of completion matches
3897 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003898
3899 // break the loop for specialized modes (use 'complete' just for the
3900 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3901 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003902 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
3903 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003904 {
3905 if (got_int)
3906 break;
3907 // Fill the popup menu as soon as possible.
3908 if (type != -1)
3909 ins_compl_check_keys(0, FALSE);
3910
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003911 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003912 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3913 break;
3914 compl_started = TRUE;
3915 }
3916 else
3917 {
3918 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02003919 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003920 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003921
3922 compl_started = FALSE;
3923 }
3924 }
3925 compl_started = TRUE;
3926
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003927 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003928 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003929 found_new_match = FAIL;
3930
3931 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003932 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003933 && !ctrl_x_mode_line_or_eval()))
3934 i = ins_compl_make_cyclic();
3935
3936 if (compl_old_match != NULL)
3937 {
3938 // If several matches were added (FORWARD) or the search failed and has
3939 // just been made cyclic then we have to move compl_curr_match to the
3940 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003941 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003942 : compl_old_match->cp_prev;
3943 if (compl_curr_match == NULL)
3944 compl_curr_match = compl_old_match;
3945 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01003946 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003947
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003948 return i;
3949}
3950
3951/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003952 * Update "compl_shown_match" to the actually shown match, it may differ when
3953 * "compl_leader" is used to omit some of the matches.
3954 */
3955 static void
3956ins_compl_update_shown_match(void)
3957{
3958 while (!ins_compl_equal(compl_shown_match,
3959 compl_leader, (int)STRLEN(compl_leader))
3960 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003961 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003962 compl_shown_match = compl_shown_match->cp_next;
3963
3964 // If we didn't find it searching forward, and compl_shows_dir is
3965 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003966 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003967 && !ins_compl_equal(compl_shown_match,
3968 compl_leader, (int)STRLEN(compl_leader))
3969 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003970 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003971 {
3972 while (!ins_compl_equal(compl_shown_match,
3973 compl_leader, (int)STRLEN(compl_leader))
3974 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003975 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003976 compl_shown_match = compl_shown_match->cp_prev;
3977 }
3978}
3979
3980/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003981 * Delete the old text being completed.
3982 */
3983 void
3984ins_compl_delete(void)
3985{
3986 int col;
3987
3988 // In insert mode: Delete the typed part.
3989 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003990 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003991 if ((int)curwin->w_cursor.col > col)
3992 {
3993 if (stop_arrow() == FAIL)
3994 return;
3995 backspace_until_column(col);
3996 }
3997
3998 // TODO: is this sufficient for redrawing? Redrawing everything causes
3999 // flicker, thus we can't do that.
4000 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004001#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004002 // clear v:completed_item
4003 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004004#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004005}
4006
4007/*
4008 * Insert the new text being completed.
4009 * "in_compl_func" is TRUE when called from complete_check().
4010 */
4011 void
4012ins_compl_insert(int in_compl_func)
4013{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004014 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004015
4016 // Make sure we don't go over the end of the string, this can happen with
4017 // illegal bytes.
4018 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4019 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004020 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004021 compl_used_match = FALSE;
4022 else
4023 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004024#ifdef FEAT_EVAL
4025 {
4026 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4027
4028 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4029 }
4030#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004031 if (!in_compl_func)
4032 compl_curr_match = compl_shown_match;
4033}
4034
4035/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004036 * show the file name for the completion match (if any). Truncate the file
4037 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004038 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004039 static void
4040ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004041{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004042 char *lead = _("match in file");
4043 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4044 char_u *s;
4045 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004046
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004047 if (space <= 0)
4048 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004049
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004050 // We need the tail that fits. With double-byte encoding going
4051 // back from the end is very slow, thus go from the start and keep
4052 // the text that fits in "space" between "s" and "e".
4053 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004054 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004055 space -= ptr2cells(e);
4056 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004057 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004058 space += ptr2cells(s);
4059 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004060 }
4061 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004062 msg_hist_off = TRUE;
4063 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4064 s > compl_shown_match->cp_fname ? "<" : "", s);
4065 msg((char *)IObuff);
4066 msg_hist_off = FALSE;
4067 redraw_cmdline = FALSE; // don't overwrite!
4068}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004069
glepnirdca57fb2024-06-04 22:01:21 +02004070/*
zeertzjq551d8c32024-06-05 19:53:32 +02004071 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004072 */
glepnira218cc62024-06-03 19:32:39 +02004073 static compl_T *
4074find_comp_when_fuzzy(void)
4075{
4076 int score;
4077 char_u* str;
4078 int target_idx = -1;
4079 int is_forward = compl_shows_dir_forward();
4080 int is_backward = compl_shows_dir_backward();
4081 compl_T *comp = NULL;
4082
4083 if (compl_match_array == NULL ||
4084 (is_forward && compl_selected_item == compl_match_arraysize - 1)
4085 || (is_backward && compl_selected_item == 0))
4086 return compl_first_match;
4087
4088 if (is_forward)
4089 target_idx = compl_selected_item + 1;
4090 else if (is_backward)
4091 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004092 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004093
4094 score = compl_match_array[target_idx].pum_score;
4095 str = compl_match_array[target_idx].pum_text;
4096
4097 comp = compl_first_match;
4098 do {
4099 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4100 return comp;
4101 comp = comp->cp_next;
4102 } while (comp != NULL && !is_first_match(comp));
4103
4104 return NULL;
4105}
4106
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004107/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004108 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004109 * times. The number of matches found is returned in 'num_matches'.
4110 *
4111 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4112 * get more completions. If it is FALSE, then do nothing when there are no more
4113 * completions in the given direction.
4114 *
4115 * If "advance" is TRUE, then completion will move to the first match.
4116 * Otherwise, the original text will be shown.
4117 *
4118 * Returns OK on success and -1 if the number of matches are unknown.
4119 */
4120 static int
4121find_next_completion_match(
4122 int allow_get_expansion,
4123 int todo, // repeat completion this many times
4124 int advance,
4125 int *num_matches)
4126{
4127 int found_end = FALSE;
4128 compl_T *found_compl = NULL;
zeertzjq529b9ad2024-06-05 20:27:06 +02004129 int cur_cot_flags = get_cot_flags();
4130 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4131 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004132
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004133 while (--todo >= 0)
4134 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004135 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004136 {
glepnira218cc62024-06-03 19:32:39 +02004137 compl_shown_match = !compl_fuzzy_match ? compl_shown_match->cp_next
4138 : find_comp_when_fuzzy();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004139 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004140 && (is_first_match(compl_shown_match->cp_next)
4141 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004142 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004143 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004144 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004145 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004146 found_end = is_first_match(compl_shown_match);
glepnira218cc62024-06-03 19:32:39 +02004147 compl_shown_match = !compl_fuzzy_match ? compl_shown_match->cp_prev
4148 : find_comp_when_fuzzy();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004149 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004150 }
4151 else
4152 {
4153 if (!allow_get_expansion)
4154 {
4155 if (advance)
4156 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004157 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004158 compl_pending -= todo + 1;
4159 else
4160 compl_pending += todo + 1;
4161 }
4162 return -1;
4163 }
4164
4165 if (!compl_no_select && advance)
4166 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004167 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004168 --compl_pending;
4169 else
4170 ++compl_pending;
4171 }
4172
4173 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004174 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004175
4176 // handle any pending completions
4177 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004178 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004179 {
4180 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4181 {
4182 compl_shown_match = compl_shown_match->cp_next;
4183 --compl_pending;
4184 }
4185 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4186 {
4187 compl_shown_match = compl_shown_match->cp_prev;
4188 ++compl_pending;
4189 }
4190 else
4191 break;
4192 }
4193 found_end = FALSE;
4194 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004195 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004196 && compl_leader != NULL
4197 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004198 compl_leader, (int)STRLEN(compl_leader))
4199 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004200 ++todo;
4201 else
4202 // Remember a matching item.
4203 found_compl = compl_shown_match;
4204
4205 // Stop at the end of the list when we found a usable match.
4206 if (found_end)
4207 {
4208 if (found_compl != NULL)
4209 {
4210 compl_shown_match = found_compl;
4211 break;
4212 }
4213 todo = 1; // use first usable match after wrapping around
4214 }
4215 }
4216
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004217 return OK;
4218}
4219
4220/*
4221 * Fill in the next completion in the current direction.
4222 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4223 * get more completions. If it is FALSE, then we just do nothing when there
4224 * are no more completions in a given direction. The latter case is used when
4225 * we are still in the middle of finding completions, to allow browsing
4226 * through the ones found so far.
4227 * Return the total number of matches, or -1 if still unknown -- webb.
4228 *
4229 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4230 * compl_shown_match here.
4231 *
4232 * Note that this function may be called recursively once only. First with
4233 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4234 * calls this function with "allow_get_expansion" FALSE.
4235 */
4236 static int
4237ins_compl_next(
4238 int allow_get_expansion,
4239 int count, // repeat completion this many times; should
4240 // be at least 1
4241 int insert_match, // Insert the newly selected match
4242 int in_compl_func) // called from complete_check()
4243{
4244 int num_matches = -1;
4245 int todo = count;
4246 int advance;
4247 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004248 buf_T *orig_curbuf = curbuf;
zeertzjq529b9ad2024-06-05 20:27:06 +02004249 int cur_cot_flags = get_cot_flags();
4250 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4251 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004252
4253 // When user complete function return -1 for findstart which is next
4254 // time of 'always', compl_shown_match become NULL.
4255 if (compl_shown_match == NULL)
4256 return -1;
4257
glepnira218cc62024-06-03 19:32:39 +02004258 if (compl_leader != NULL
4259 && !match_at_original_text(compl_shown_match)
4260 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004261 // Update "compl_shown_match" to the actually shown match
4262 ins_compl_update_shown_match();
4263
4264 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004265 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004266 // Delete old text to be replaced
4267 ins_compl_delete();
4268
4269 // When finding the longest common text we stick at the original text,
4270 // don't let CTRL-N or CTRL-P move to the first match.
4271 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4272
4273 // When restarting the search don't insert the first match either.
4274 if (compl_restarting)
4275 {
4276 advance = FALSE;
4277 compl_restarting = FALSE;
4278 }
4279
4280 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4281 // around.
4282 if (find_next_completion_match(allow_get_expansion, todo, advance,
4283 &num_matches) == -1)
4284 return -1;
4285
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004286 if (curbuf != orig_curbuf)
4287 {
4288 // In case some completion function switched buffer, don't want to
4289 // insert the completion elsewhere.
4290 return -1;
4291 }
4292
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004293 // Insert the text of the new completion, or the compl_leader.
4294 if (compl_no_insert && !started)
4295 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004296 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004297 compl_used_match = FALSE;
4298 }
4299 else if (insert_match)
4300 {
4301 if (!compl_get_longest || compl_used_match)
4302 ins_compl_insert(in_compl_func);
4303 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004304 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004305 }
4306 else
4307 compl_used_match = FALSE;
4308
4309 if (!allow_get_expansion)
4310 {
4311 // may undisplay the popup menu first
4312 ins_compl_upd_pum();
4313
4314 if (pum_enough_matches())
4315 // Will display the popup menu, don't redraw yet to avoid flicker.
4316 pum_call_update_screen();
4317 else
4318 // Not showing the popup menu yet, redraw to show the user what was
4319 // inserted.
4320 update_screen(0);
4321
4322 // display the updated popup menu
4323 ins_compl_show_pum();
4324#ifdef FEAT_GUI
4325 if (gui.in_use)
4326 {
4327 // Show the cursor after the match, not after the redrawn text.
4328 setcursor();
4329 out_flush_cursor(FALSE, FALSE);
4330 }
4331#endif
4332
4333 // Delete old text to be replaced, since we're still searching and
4334 // don't want to match ourselves!
4335 ins_compl_delete();
4336 }
4337
4338 // Enter will select a match when the match wasn't inserted and the popup
4339 // menu is visible.
4340 if (compl_no_insert && !started)
4341 compl_enter_selects = TRUE;
4342 else
4343 compl_enter_selects = !insert_match && compl_match_array != NULL;
4344
4345 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004346 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004347 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004348
4349 return num_matches;
4350}
4351
4352/*
4353 * Call this while finding completions, to check whether the user has hit a key
4354 * that should change the currently displayed completion, or exit completion
4355 * mode. Also, when compl_pending is not zero, show a completion as soon as
4356 * possible. -- webb
4357 * "frequency" specifies out of how many calls we actually check.
4358 * "in_compl_func" is TRUE when called from complete_check(), don't set
4359 * compl_curr_match.
4360 */
4361 void
4362ins_compl_check_keys(int frequency, int in_compl_func)
4363{
4364 static int count = 0;
4365 int c;
4366
4367 // Don't check when reading keys from a script, :normal or feedkeys().
4368 // That would break the test scripts. But do check for keys when called
4369 // from complete_check().
4370 if (!in_compl_func && (using_script() || ex_normal_busy))
4371 return;
4372
4373 // Only do this at regular intervals
4374 if (++count < frequency)
4375 return;
4376 count = 0;
4377
4378 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4379 // can't do its work correctly.
4380 c = vpeekc_any();
4381 if (c != NUL)
4382 {
4383 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4384 {
4385 c = safe_vgetc(); // Eat the character
4386 compl_shows_dir = ins_compl_key2dir(c);
4387 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4388 c != K_UP && c != K_DOWN, in_compl_func);
4389 }
4390 else
4391 {
4392 // Need to get the character to have KeyTyped set. We'll put it
4393 // back with vungetc() below. But skip K_IGNORE.
4394 c = safe_vgetc();
4395 if (c != K_IGNORE)
4396 {
4397 // Don't interrupt completion when the character wasn't typed,
4398 // e.g., when doing @q to replay keys.
4399 if (c != Ctrl_R && KeyTyped)
4400 compl_interrupted = TRUE;
4401
4402 vungetc(c);
4403 }
4404 }
4405 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004406 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004407 {
4408 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4409
4410 compl_pending = 0;
4411 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4412 }
4413}
4414
4415/*
4416 * Decide the direction of Insert mode complete from the key typed.
4417 * Returns BACKWARD or FORWARD.
4418 */
4419 static int
4420ins_compl_key2dir(int c)
4421{
4422 if (c == Ctrl_P || c == Ctrl_L
4423 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4424 return BACKWARD;
4425 return FORWARD;
4426}
4427
4428/*
4429 * Return TRUE for keys that are used for completion only when the popup menu
4430 * is visible.
4431 */
4432 static int
4433ins_compl_pum_key(int c)
4434{
4435 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4436 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4437 || c == K_UP || c == K_DOWN);
4438}
4439
4440/*
4441 * Decide the number of completions to move forward.
4442 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4443 */
4444 static int
4445ins_compl_key2count(int c)
4446{
4447 int h;
4448
4449 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4450 {
4451 h = pum_get_height();
4452 if (h > 3)
4453 h -= 2; // keep some context
4454 return h;
4455 }
4456 return 1;
4457}
4458
4459/*
4460 * Return TRUE if completion with "c" should insert the match, FALSE if only
4461 * to change the currently selected completion.
4462 */
4463 static int
4464ins_compl_use_match(int c)
4465{
4466 switch (c)
4467 {
4468 case K_UP:
4469 case K_DOWN:
4470 case K_PAGEDOWN:
4471 case K_KPAGEDOWN:
4472 case K_S_DOWN:
4473 case K_PAGEUP:
4474 case K_KPAGEUP:
4475 case K_S_UP:
4476 return FALSE;
4477 }
4478 return TRUE;
4479}
4480
4481/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004482 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4483 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004484 * Sets the global variables: compl_col, compl_length, compl_pattern and
4485 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004486 * Uses the global variables: compl_cont_status and ctrl_x_mode
4487 */
4488 static int
4489get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4490{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004491 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004492 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004493 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004494 {
4495 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4496 ;
4497 compl_col += ++startcol;
4498 compl_length = curs_col - startcol;
4499 }
4500 if (p_ic)
4501 compl_pattern = str_foldcase(line + compl_col,
4502 compl_length, NULL, 0);
4503 else
4504 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4505 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004506 {
4507 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004508 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004509 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004510 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004511 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004512 {
4513 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004514 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004515
4516 // we need up to 2 extra chars for the prefix
4517 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004518 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004519 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004520 {
4521 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004522 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004523 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004524 if (!vim_iswordp(line + compl_col)
4525 || (compl_col > 0
4526 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004527 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004528 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004529 prefixlen = 0;
4530 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004531 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004532 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004533 line + compl_col, compl_length);
4534 }
4535 else if (--startcol < 0
4536 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4537 {
4538 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004539 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
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 compl_col += curs_col;
4546 compl_length = 0;
4547 }
4548 else
4549 {
4550 // Search the point of change class of multibyte character
4551 // or not a word single byte character backward.
4552 if (has_mbyte)
4553 {
4554 int base_class;
4555 int head_off;
4556
4557 startcol -= (*mb_head_off)(line, line + startcol);
4558 base_class = mb_get_class(line + startcol);
4559 while (--startcol >= 0)
4560 {
4561 head_off = (*mb_head_off)(line, line + startcol);
4562 if (base_class != mb_get_class(line + startcol
4563 - head_off))
4564 break;
4565 startcol -= head_off;
4566 }
4567 }
4568 else
4569 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4570 ;
4571 compl_col += ++startcol;
4572 compl_length = (int)curs_col - startcol;
4573 if (compl_length == 1)
4574 {
4575 // Only match word with at least two chars -- webb
4576 // there's no need to call quote_meta,
4577 // alloc(7) is enough -- Acevedo
4578 compl_pattern = alloc(7);
4579 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004580 {
4581 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004582 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004583 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004584 STRCPY((char *)compl_pattern, "\\<");
4585 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4586 STRCAT((char *)compl_pattern, "\\k");
4587 }
4588 else
4589 {
4590 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4591 compl_length) + 2);
4592 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004593 {
4594 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004595 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004596 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004597 STRCPY((char *)compl_pattern, "\\<");
4598 (void)quote_meta(compl_pattern + 2, line + compl_col,
4599 compl_length);
4600 }
4601 }
4602
John Marriott8c85a2a2024-05-20 19:18:26 +02004603 compl_patternlen = STRLEN(compl_pattern);
4604
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004605 return OK;
4606}
4607
4608/*
4609 * Get the pattern, column and length for whole line completion or for the
4610 * complete() function.
4611 * Sets the global variables: compl_col, compl_length and compl_pattern.
4612 */
4613 static int
4614get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4615{
4616 compl_col = (colnr_T)getwhitecols(line);
4617 compl_length = (int)curs_col - (int)compl_col;
4618 if (compl_length < 0) // cursor in indent: empty pattern
4619 compl_length = 0;
4620 if (p_ic)
4621 compl_pattern = str_foldcase(line + compl_col, compl_length,
4622 NULL, 0);
4623 else
4624 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4625 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004626 {
4627 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004628 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004629 }
4630
4631 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004632
4633 return OK;
4634}
4635
4636/*
4637 * Get the pattern, column and length for filename completion.
4638 * Sets the global variables: compl_col, compl_length and compl_pattern.
4639 */
4640 static int
4641get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4642{
4643 // Go back to just before the first filename character.
4644 if (startcol > 0)
4645 {
4646 char_u *p = line + startcol;
4647
4648 MB_PTR_BACK(line, p);
4649 while (p > line && vim_isfilec(PTR2CHAR(p)))
4650 MB_PTR_BACK(line, p);
4651 if (p == line && vim_isfilec(PTR2CHAR(p)))
4652 startcol = 0;
4653 else
4654 startcol = (int)(p - line) + 1;
4655 }
4656
4657 compl_col += startcol;
4658 compl_length = (int)curs_col - startcol;
4659 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4660 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004661 {
4662 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004663 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004664 }
4665
4666 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004667
4668 return OK;
4669}
4670
4671/*
4672 * Get the pattern, column and length for command-line completion.
4673 * Sets the global variables: compl_col, compl_length and compl_pattern.
4674 */
4675 static int
4676get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4677{
4678 compl_pattern = vim_strnsave(line, curs_col);
4679 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004680 {
4681 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004682 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004683 }
4684 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004685 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004686 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004687 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4688 || compl_xp.xp_context == EXPAND_NOTHING)
4689 // No completion possible, use an empty pattern to get a
4690 // "pattern not found" message.
4691 compl_col = curs_col;
4692 else
4693 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4694 compl_length = curs_col - compl_col;
4695
4696 return OK;
4697}
4698
4699/*
4700 * Get the pattern, column and length for user defined completion ('omnifunc',
4701 * 'completefunc' and 'thesaurusfunc')
4702 * Sets the global variables: compl_col, compl_length and compl_pattern.
4703 * Uses the global variable: spell_bad_len
4704 */
4705 static int
4706get_userdefined_compl_info(colnr_T curs_col UNUSED)
4707{
4708 int ret = FAIL;
4709
4710#ifdef FEAT_COMPL_FUNC
4711 // Call user defined function 'completefunc' with "a:findstart"
4712 // set to 1 to obtain the length of text to use for completion.
4713 char_u *line;
4714 typval_T args[3];
4715 int col;
4716 char_u *funcname;
4717 pos_T pos;
4718 int save_State = State;
4719 callback_T *cb;
4720
4721 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4722 // length as a string
4723 funcname = get_complete_funcname(ctrl_x_mode);
4724 if (*funcname == NUL)
4725 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004726 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004727 ? "completefunc" : "omnifunc");
4728 return FAIL;
4729 }
4730
4731 args[0].v_type = VAR_NUMBER;
4732 args[0].vval.v_number = 1;
4733 args[1].v_type = VAR_STRING;
4734 args[1].vval.v_string = (char_u *)"";
4735 args[2].v_type = VAR_UNKNOWN;
4736 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004737 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004738 cb = get_insert_callback(ctrl_x_mode);
4739 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004740 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004741
4742 State = save_State;
4743 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004744 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004745 validate_cursor();
4746 if (!EQUAL_POS(curwin->w_cursor, pos))
4747 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004748 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004749 return FAIL;
4750 }
4751
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004752 // Return value -2 means the user complete function wants to cancel the
4753 // complete without an error, do the same if the function did not execute
4754 // successfully.
4755 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004756 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004757 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004758 if (col == -3)
4759 {
4760 ctrl_x_mode = CTRL_X_NORMAL;
4761 edit_submode = NULL;
4762 if (!shortmess(SHM_COMPLETIONMENU))
4763 msg_clr_cmdline();
4764 return FAIL;
4765 }
4766
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004767 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004768 // completion.
4769 compl_opt_refresh_always = FALSE;
4770 compl_opt_suppress_empty = FALSE;
4771
4772 if (col < 0)
4773 col = curs_col;
4774 compl_col = col;
4775 if (compl_col > curs_col)
4776 compl_col = curs_col;
4777
4778 // Setup variables for completion. Need to obtain "line" again,
4779 // it may have become invalid.
4780 line = ml_get(curwin->w_cursor.lnum);
4781 compl_length = curs_col - compl_col;
4782 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4783 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004784 {
4785 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004786 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004787 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004788
John Marriott8c85a2a2024-05-20 19:18:26 +02004789 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004790 ret = OK;
4791#endif
4792
4793 return ret;
4794}
4795
4796/*
4797 * Get the pattern, column and length for spell completion.
4798 * Sets the global variables: compl_col, compl_length and compl_pattern.
4799 * Uses the global variable: spell_bad_len
4800 */
4801 static int
4802get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4803{
4804 int ret = FAIL;
4805#ifdef FEAT_SPELL
4806 char_u *line;
4807
4808 if (spell_bad_len > 0)
4809 compl_col = curs_col - spell_bad_len;
4810 else
4811 compl_col = spell_word_start(startcol);
4812 if (compl_col >= (colnr_T)startcol)
4813 {
4814 compl_length = 0;
4815 compl_col = curs_col;
4816 }
4817 else
4818 {
4819 spell_expand_check_cap(compl_col);
4820 compl_length = (int)curs_col - compl_col;
4821 }
4822 // Need to obtain "line" again, it may have become invalid.
4823 line = ml_get(curwin->w_cursor.lnum);
4824 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4825 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004826 {
4827 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004828 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004829 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004830
John Marriott8c85a2a2024-05-20 19:18:26 +02004831 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004832 ret = OK;
4833#endif
4834
4835 return ret;
4836}
4837
4838/*
4839 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004840 * "startcol" - start column number of the completion pattern/text
4841 * "cur_col" - current cursor column
4842 * On return, "line_invalid" is set to TRUE, if the current line may have
4843 * become invalid and needs to be fetched again.
4844 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004845 */
4846 static int
4847compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
4848{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004849 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004850 || (ctrl_x_mode & CTRL_X_WANT_IDENT
4851 && !thesaurus_func_complete(ctrl_x_mode)))
4852 {
4853 return get_normal_compl_info(line, startcol, curs_col);
4854 }
4855 else if (ctrl_x_mode_line_or_eval())
4856 {
4857 return get_wholeline_compl_info(line, curs_col);
4858 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004859 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004860 {
4861 return get_filename_compl_info(line, startcol, curs_col);
4862 }
4863 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4864 {
4865 return get_cmdline_compl_info(line, curs_col);
4866 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004867 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004868 || thesaurus_func_complete(ctrl_x_mode))
4869 {
4870 if (get_userdefined_compl_info(curs_col) == FAIL)
4871 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004872 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004873 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004874 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004875 {
4876 if (get_spell_compl_info(startcol, curs_col) == FAIL)
4877 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004878 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004879 }
4880 else
4881 {
4882 internal_error("ins_complete()");
4883 return FAIL;
4884 }
4885
4886 return OK;
4887}
4888
4889/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004890 * Continue an interrupted completion mode search in "line".
4891 *
4892 * If this same ctrl_x_mode has been interrupted use the text from
4893 * "compl_startpos" to the cursor as a pattern to add a new word instead of
4894 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
4895 * the same line as the cursor then fix it (the line has been split because it
4896 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
4897 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004898 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004899 static void
4900ins_compl_continue_search(char_u *line)
4901{
4902 // it is a continued search
4903 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004904 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
4905 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004906 {
4907 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4908 {
4909 // line (probably) wrapped, set compl_startpos to the
4910 // first non_blank in the line, if it is not a wordchar
4911 // include it to get a better pattern, but then we don't
4912 // want the "\\<" prefix, check it below
4913 compl_col = (colnr_T)getwhitecols(line);
4914 compl_startpos.col = compl_col;
4915 compl_startpos.lnum = curwin->w_cursor.lnum;
4916 compl_cont_status &= ~CONT_SOL; // clear SOL if present
4917 }
4918 else
4919 {
4920 // S_IPOS was set when we inserted a word that was at the
4921 // beginning of the line, which means that we'll go to SOL
4922 // mode but first we need to redefine compl_startpos
4923 if (compl_cont_status & CONT_S_IPOS)
4924 {
4925 compl_cont_status |= CONT_SOL;
4926 compl_startpos.col = (colnr_T)(skipwhite(
4927 line + compl_length
4928 + compl_startpos.col) - line);
4929 }
4930 compl_col = compl_startpos.col;
4931 }
4932 compl_length = curwin->w_cursor.col - (int)compl_col;
4933 // IObuff is used to add a "word from the next line" would we
4934 // have enough space? just being paranoid
4935#define MIN_SPACE 75
4936 if (compl_length > (IOSIZE - MIN_SPACE))
4937 {
4938 compl_cont_status &= ~CONT_SOL;
4939 compl_length = (IOSIZE - MIN_SPACE);
4940 compl_col = curwin->w_cursor.col - compl_length;
4941 }
4942 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4943 if (compl_length < 1)
4944 compl_cont_status &= CONT_LOCAL;
4945 }
4946 else if (ctrl_x_mode_line_or_eval())
4947 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4948 else
4949 compl_cont_status = 0;
4950}
4951
4952/*
4953 * start insert mode completion
4954 */
4955 static int
4956ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004957{
4958 char_u *line;
4959 int startcol = 0; // column where searched text starts
4960 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004961 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004962 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004963 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004964
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004965 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004966
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004967 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004968 did_si = FALSE;
4969 can_si = FALSE;
4970 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004971 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004972 return FAIL;
4973
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004974 line = ml_get(curwin->w_cursor.lnum);
4975 curs_col = curwin->w_cursor.col;
4976 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004977
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004978 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4979 && compl_cont_mode == ctrl_x_mode)
4980 // this same ctrl-x_mode was interrupted previously. Continue the
4981 // completion.
4982 ins_compl_continue_search(line);
4983 else
4984 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004985
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004986 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004988 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004989 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004990 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
4991 compl_cont_status = 0;
4992 compl_cont_status |= CONT_N_ADDS;
4993 compl_startpos = curwin->w_cursor;
4994 startcol = (int)curs_col;
4995 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004996 }
4997
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004998 // Work out completion pattern and original text -- webb
4999 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5000 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005001 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5002 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005003 // restore did_ai, so that adding comment leader works
5004 did_ai = save_did_ai;
5005 return FAIL;
5006 }
5007 // If "line" was changed while getting completion info get it again.
5008 if (line_invalid)
5009 line = ml_get(curwin->w_cursor.lnum);
5010
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005011 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005012 {
5013 edit_submode_pre = (char_u *)_(" Adding");
5014 if (ctrl_x_mode_line_or_eval())
5015 {
5016 // Insert a new line, keep indentation but ignore 'comments'.
5017 char_u *old = curbuf->b_p_com;
5018
5019 curbuf->b_p_com = (char_u *)"";
5020 compl_startpos.lnum = curwin->w_cursor.lnum;
5021 compl_startpos.col = compl_col;
5022 ins_eol('\r');
5023 curbuf->b_p_com = old;
5024 compl_length = 0;
5025 compl_col = curwin->w_cursor.col;
5026 }
5027 }
5028 else
5029 {
5030 edit_submode_pre = NULL;
5031 compl_startpos.col = compl_col;
5032 }
5033
5034 if (compl_cont_status & CONT_LOCAL)
5035 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5036 else
5037 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5038
5039 // If any of the original typed text has been changed we need to fix
5040 // the redo buffer.
5041 ins_compl_fixRedoBufForLeader(NULL);
5042
5043 // Always add completion for the original text.
5044 vim_free(compl_orig_text);
5045 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5046 if (p_ic)
5047 flags |= CP_ICASE;
5048 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5049 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
5050 {
5051 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005052 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005053 VIM_CLEAR(compl_orig_text);
5054 return FAIL;
5055 }
5056
5057 // showmode might reset the internal line pointers, so it must
5058 // be called before line = ml_get(), or when this address is no
5059 // longer needed. -- Acevedo.
5060 edit_submode_extra = (char_u *)_("-- Searching...");
5061 edit_submode_highl = HLF_COUNT;
5062 showmode();
5063 edit_submode_extra = NULL;
5064 out_flush();
5065
5066 return OK;
5067}
5068
5069/*
5070 * display the completion status message
5071 */
5072 static void
5073ins_compl_show_statusmsg(void)
5074{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005075 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005076 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005077 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005078 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005079 ? (char_u *)_("Hit end of paragraph")
5080 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005081 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005082 }
5083
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005084 if (edit_submode_extra == NULL)
5085 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005086 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005087 {
5088 edit_submode_extra = (char_u *)_("Back at original");
5089 edit_submode_highl = HLF_W;
5090 }
5091 else if (compl_cont_status & CONT_S_IPOS)
5092 {
5093 edit_submode_extra = (char_u *)_("Word from other line");
5094 edit_submode_highl = HLF_COUNT;
5095 }
5096 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5097 {
5098 edit_submode_extra = (char_u *)_("The only match");
5099 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005100 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005101 }
5102 else
5103 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005104#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005105 // Update completion sequence number when needed.
5106 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005107 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005108#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005109 // The match should always have a sequence number now, this is
5110 // just a safety check.
5111 if (compl_curr_match->cp_number != -1)
5112 {
5113 // Space for 10 text chars. + 2x10-digit no.s = 31.
5114 // Translations may need more than twice that.
5115 static char_u match_ref[81];
5116
5117 if (compl_matches > 0)
5118 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005119 _("match %d of %d"),
5120 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005121 else
5122 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005123 _("match %d"),
5124 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005125 edit_submode_extra = match_ref;
5126 edit_submode_highl = HLF_R;
5127 if (dollar_vcol >= 0)
5128 curs_columns(FALSE);
5129 }
5130 }
5131 }
5132
5133 // Show a message about what (completion) mode we're in.
5134 if (!compl_opt_suppress_empty)
5135 {
5136 showmode();
5137 if (!shortmess(SHM_COMPLETIONMENU))
5138 {
5139 if (edit_submode_extra != NULL)
5140 {
5141 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005142 {
5143 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005144 msg_attr((char *)edit_submode_extra,
5145 edit_submode_highl < HLF_COUNT
5146 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005147 msg_hist_off = FALSE;
5148 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005149 }
5150 else
5151 msg_clr_cmdline(); // necessary for "noshowmode"
5152 }
5153 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005154}
5155
5156/*
5157 * Do Insert mode completion.
5158 * Called when character "c" was typed, which has a meaning for completion.
5159 * Returns OK if completion was done, FAIL if something failed (out of mem).
5160 */
5161 int
5162ins_complete(int c, int enable_pum)
5163{
5164 int n;
5165 int save_w_wrow;
5166 int save_w_leftcol;
5167 int insert_match;
5168
5169 compl_direction = ins_compl_key2dir(c);
5170 insert_match = ins_compl_use_match(c);
5171
5172 if (!compl_started)
5173 {
5174 if (ins_compl_start() == FAIL)
5175 return FAIL;
5176 }
5177 else if (insert_match && stop_arrow() == FAIL)
5178 return FAIL;
5179
5180 compl_shown_match = compl_curr_match;
5181 compl_shows_dir = compl_direction;
5182
5183 // Find next match (and following matches).
5184 save_w_wrow = curwin->w_wrow;
5185 save_w_leftcol = curwin->w_leftcol;
5186 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5187
5188 // may undisplay the popup menu
5189 ins_compl_upd_pum();
5190
5191 if (n > 1) // all matches have been found
5192 compl_matches = n;
5193 compl_curr_match = compl_shown_match;
5194 compl_direction = compl_shows_dir;
5195
5196 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5197 // mode.
5198 if (got_int && !global_busy)
5199 {
5200 (void)vgetc();
5201 got_int = FALSE;
5202 }
5203
5204 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005205 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005206 {
5207 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5208 // because we couldn't expand anything at first place, but if we used
5209 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5210 // (such as M in M'exico) if not tried already. -- Acevedo
5211 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005212 || compl_status_adding()
5213 || (ctrl_x_mode_not_default()
5214 && !ctrl_x_mode_path_patterns()
5215 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005216 compl_cont_status &= ~CONT_N_ADDS;
5217 }
5218
5219 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5220 compl_cont_status |= CONT_S_IPOS;
5221 else
5222 compl_cont_status &= ~CONT_S_IPOS;
5223
5224 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005225
5226 // Show the popup menu, unless we got interrupted.
5227 if (enable_pum && !compl_interrupted)
5228 show_pum(save_w_wrow, save_w_leftcol);
5229
5230 compl_was_interrupted = compl_interrupted;
5231 compl_interrupted = FALSE;
5232
5233 return OK;
5234}
5235
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005236/*
5237 * Remove (if needed) and show the popup menu
5238 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005239 static void
5240show_pum(int prev_w_wrow, int prev_w_leftcol)
5241{
5242 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005243 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005244 RedrawingDisabled = 0;
5245
5246 // If the cursor moved or the display scrolled we need to remove the pum
5247 // first.
5248 setcursor();
5249 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5250 ins_compl_del_pum();
5251
5252 ins_compl_show_pum();
5253 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005254
5255 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005256}
5257
5258/*
5259 * Looks in the first "len" chars. of "src" for search-metachars.
5260 * If dest is not NULL the chars. are copied there quoting (with
5261 * a backslash) the metachars, and dest would be NUL terminated.
5262 * Returns the length (needed) of dest
5263 */
5264 static unsigned
5265quote_meta(char_u *dest, char_u *src, int len)
5266{
5267 unsigned m = (unsigned)len + 1; // one extra for the NUL
5268
5269 for ( ; --len >= 0; src++)
5270 {
5271 switch (*src)
5272 {
5273 case '.':
5274 case '*':
5275 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005276 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005277 break;
5278 // FALLTHROUGH
5279 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005280 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005281 break;
5282 // FALLTHROUGH
5283 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005284 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005285 break;
5286 // FALLTHROUGH
5287 case '^': // currently it's not needed.
5288 case '$':
5289 m++;
5290 if (dest != NULL)
5291 *dest++ = '\\';
5292 break;
5293 }
5294 if (dest != NULL)
5295 *dest++ = *src;
5296 // Copy remaining bytes of a multibyte character.
5297 if (has_mbyte)
5298 {
5299 int i, mb_len;
5300
5301 mb_len = (*mb_ptr2len)(src) - 1;
5302 if (mb_len > 0 && len >= mb_len)
5303 for (i = 0; i < mb_len; ++i)
5304 {
5305 --len;
5306 ++src;
5307 if (dest != NULL)
5308 *dest++ = *src;
5309 }
5310 }
5311 }
5312 if (dest != NULL)
5313 *dest = NUL;
5314
5315 return m;
5316}
5317
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005318#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005319 void
5320free_insexpand_stuff(void)
5321{
5322 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005323# ifdef FEAT_EVAL
5324 free_callback(&cfu_cb);
5325 free_callback(&ofu_cb);
5326 free_callback(&tsrfu_cb);
5327# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005328}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005329#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005330
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005331#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005332/*
5333 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5334 * spelled word, if there is one.
5335 */
5336 static void
5337spell_back_to_badword(void)
5338{
5339 pos_T tpos = curwin->w_cursor;
5340
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005341 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005342 if (curwin->w_cursor.col != tpos.col)
5343 start_arrow(&tpos);
5344}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005345#endif