blob: c673df927c933319dbf9d41e51df610ccb0eff43 [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
61 N_(" Spelling suggestion (s^N^P)"),
62 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
91 * Array indexes used for cp_text[].
92 */
93#define CPT_ABBR 0 // "abbr"
94#define CPT_MENU 1 // "menu"
95#define CPT_KIND 2 // "kind"
96#define CPT_INFO 3 // "info"
Bram Moolenaar08928322020-01-04 14:32:48 +010097#define CPT_COUNT 4 // Number of entries
Bram Moolenaar7591bb32019-03-30 13:53:47 +010098
99/*
100 * Structure used to store one match for insert completion.
101 */
102typedef struct compl_S compl_T;
103struct compl_S
104{
105 compl_T *cp_next;
106 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200107 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200108 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100109#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100110 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100111#endif
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200112 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113 // cp_flags has CP_FREE_FNAME
114 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200115 int cp_number; // sequence number
glepnira218cc62024-06-03 19:32:39 +0200116 int cp_score; // fuzzy match score
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100117};
118
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200119// values for cp_flags
120# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
121# define CP_FREE_FNAME 2 // cp_fname is allocated
122# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
123# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
124# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200125# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100127/*
128 * All the current matches are stored in a list.
129 * "compl_first_match" points to the start of the list.
130 * "compl_curr_match" points to the currently selected entry.
131 * "compl_shown_match" is different from compl_curr_match during
132 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000133 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100134 */
135static compl_T *compl_first_match = NULL;
136static compl_T *compl_curr_match = NULL;
137static compl_T *compl_shown_match = NULL;
138static compl_T *compl_old_match = NULL;
139
140// After using a cursor key <Enter> selects a match in the popup menu,
141// otherwise it inserts a line break.
142static int compl_enter_selects = FALSE;
143
144// When "compl_leader" is not NULL only matches that start with this string
145// are used.
146static char_u *compl_leader = NULL;
147
148static int compl_get_longest = FALSE; // put longest common string
149 // in compl_leader
150
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100151// Selected one of the matches. When FALSE the match was edited or using the
152// longest common string.
153static int compl_used_match;
154
155// didn't finish finding completions.
156static int compl_was_interrupted = FALSE;
157
158// Set when character typed while looking for matches and it means we should
159// stop looking for matches.
160static int compl_interrupted = FALSE;
161
162static int compl_restarting = FALSE; // don't insert match
163
164// When the first completion is done "compl_started" is set. When it's
165// FALSE the word to be completed must be located.
166static int compl_started = FALSE;
167
168// Which Ctrl-X mode are we in?
169static int ctrl_x_mode = CTRL_X_NORMAL;
170
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000171static int compl_matches = 0; // number of completion matches
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100172static char_u *compl_pattern = NULL;
John Marriott8c85a2a2024-05-20 19:18:26 +0200173static size_t compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100174static int compl_direction = FORWARD;
175static int compl_shows_dir = FORWARD;
176static int compl_pending = 0; // > 1 for postponed CTRL-N
177static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000178// Length in bytes of the text being completed (this is deleted to be replaced
179// by the match.)
180static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100181static colnr_T compl_col = 0; // column where the text starts
182 // that is being completed
183static char_u *compl_orig_text = NULL; // text as it was before
184 // completion started
185static int compl_cont_mode = 0;
186static expand_T compl_xp;
187
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000188// List of flags for method of completion.
189static int compl_cont_status = 0;
190# define CONT_ADDING 1 // "normal" or "adding" expansion
191# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
192 // it's set only iff N_ADDS is set
193# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
194# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
195 // if so, word-wise-expansion will set SOL
196# define CONT_SOL 16 // pattern includes start of line, just for
197 // word-wise expansion, not set for ^X^L
198# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
199 // expansion, (eg use complete=.)
200
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100201static int compl_opt_refresh_always = FALSE;
202static int compl_opt_suppress_empty = FALSE;
203
glepnira218cc62024-06-03 19:32:39 +0200204static int compl_selected_item = -1;
205
Bram Moolenaar08928322020-01-04 14:32:48 +0100206static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100207static void ins_compl_longest_match(compl_T *match);
208static void ins_compl_del_pum(void);
209static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
210static char_u *find_line_end(char_u *ptr);
211static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100212static int ins_compl_need_restart(void);
213static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000214static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100215static void ins_compl_restart(void);
216static void ins_compl_set_original_text(char_u *str);
217static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
218# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
219static void ins_compl_add_list(list_T *list);
220static void ins_compl_add_dict(dict_T *dict);
221# endif
222static int ins_compl_key2dir(int c);
223static int ins_compl_pum_key(int c);
224static int ins_compl_key2count(int c);
225static void show_pum(int prev_w_wrow, int prev_w_leftcol);
226static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100227
228#ifdef FEAT_SPELL
229static void spell_back_to_badword(void);
230static int spell_bad_len = 0; // length of located bad word
231#endif
232
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100233/*
234 * CTRL-X pressed in Insert mode.
235 */
236 void
237ins_ctrl_x(void)
238{
zeertzjqdca29d92021-08-31 19:12:51 +0200239 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100240 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000241 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242 if (compl_cont_status & CONT_N_ADDS)
243 compl_cont_status |= CONT_INTRPT;
244 else
245 compl_cont_status = 0;
246 // We're not sure which CTRL-X mode it will be yet
247 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
248 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
249 edit_submode_pre = NULL;
250 showmode();
251 }
zeertzjqdca29d92021-08-31 19:12:51 +0200252 else
253 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
254 // CTRL-V look like CTRL-N
255 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100256
LemonBoy2bf52dd2022-04-09 18:17:34 +0100257 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100258}
259
260/*
261 * Functions to check the current CTRL-X mode.
262 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000263int ctrl_x_mode_none(void)
264 { return ctrl_x_mode == 0; }
265int ctrl_x_mode_normal(void)
266 { return ctrl_x_mode == CTRL_X_NORMAL; }
267int ctrl_x_mode_scroll(void)
268 { return ctrl_x_mode == CTRL_X_SCROLL; }
269int ctrl_x_mode_whole_line(void)
270 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
271int ctrl_x_mode_files(void)
272 { return ctrl_x_mode == CTRL_X_FILES; }
273int ctrl_x_mode_tags(void)
274 { return ctrl_x_mode == CTRL_X_TAGS; }
275int ctrl_x_mode_path_patterns(void)
276 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
277int ctrl_x_mode_path_defines(void)
278 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
279int ctrl_x_mode_dictionary(void)
280 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
281int ctrl_x_mode_thesaurus(void)
282 { return ctrl_x_mode == CTRL_X_THESAURUS; }
283int ctrl_x_mode_cmdline(void)
284 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200285 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000286int ctrl_x_mode_function(void)
287 { return ctrl_x_mode == CTRL_X_FUNCTION; }
288int ctrl_x_mode_omni(void)
289 { return ctrl_x_mode == CTRL_X_OMNI; }
290int ctrl_x_mode_spell(void)
291 { return ctrl_x_mode == CTRL_X_SPELL; }
292static int ctrl_x_mode_eval(void)
293 { return ctrl_x_mode == CTRL_X_EVAL; }
294int ctrl_x_mode_line_or_eval(void)
295 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100296
297/*
298 * Whether other than default completion has been selected.
299 */
300 int
301ctrl_x_mode_not_default(void)
302{
303 return ctrl_x_mode != CTRL_X_NORMAL;
304}
305
306/*
zeertzjqdca29d92021-08-31 19:12:51 +0200307 * Whether CTRL-X was typed without a following character,
308 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100309 */
310 int
311ctrl_x_mode_not_defined_yet(void)
312{
313 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
314}
315
316/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000317 * Return TRUE if currently in "normal" or "adding" insert completion matches
318 * state
319 */
320 int
321compl_status_adding(void)
322{
323 return compl_cont_status & CONT_ADDING;
324}
325
326/*
327 * Return TRUE if the completion pattern includes start of line, just for
328 * word-wise expansion.
329 */
330 int
331compl_status_sol(void)
332{
333 return compl_cont_status & CONT_SOL;
334}
335
336/*
337 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
338 */
339 int
340compl_status_local(void)
341{
342 return compl_cont_status & CONT_LOCAL;
343}
344
345/*
346 * Clear the completion status flags
347 */
348 void
349compl_status_clear(void)
350{
351 compl_cont_status = 0;
352}
353
354/*
355 * Return TRUE if completion is using the forward direction matches
356 */
357 static int
358compl_dir_forward(void)
359{
360 return compl_direction == FORWARD;
361}
362
363/*
364 * Return TRUE if currently showing forward completion matches
365 */
366 static int
367compl_shows_dir_forward(void)
368{
369 return compl_shows_dir == FORWARD;
370}
371
372/*
373 * Return TRUE if currently showing backward completion matches
374 */
375 static int
376compl_shows_dir_backward(void)
377{
378 return compl_shows_dir == BACKWARD;
379}
380
381/*
382 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100383 */
384 int
385has_compl_option(int dict_opt)
386{
387 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200388#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100389 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200390#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100391 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100392 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
393#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100394 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100395#endif
396 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100397 {
398 ctrl_x_mode = CTRL_X_NORMAL;
399 edit_submode = NULL;
400 msg_attr(dict_opt ? _("'dictionary' option is empty")
401 : _("'thesaurus' option is empty"),
402 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100403 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100404 {
405 vim_beep(BO_COMPL);
406 setcursor();
407 out_flush();
408#ifdef FEAT_EVAL
409 if (!get_vim_var_nr(VV_TESTING))
410#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100411 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100412 }
413 return FALSE;
414 }
415 return TRUE;
416}
417
418/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000419 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100420 * This depends on the current mode.
421 */
422 int
423vim_is_ctrl_x_key(int c)
424{
425 // Always allow ^R - let its results then be checked
426 if (c == Ctrl_R)
427 return TRUE;
428
429 // Accept <PageUp> and <PageDown> if the popup menu is visible.
430 if (ins_compl_pum_key(c))
431 return TRUE;
432
433 switch (ctrl_x_mode)
434 {
435 case 0: // Not in any CTRL-X mode
436 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
437 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200438 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100439 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
440 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
441 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
442 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
443 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200444 || c == Ctrl_S || c == Ctrl_K || c == 's'
445 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100446 case CTRL_X_SCROLL:
447 return (c == Ctrl_Y || c == Ctrl_E);
448 case CTRL_X_WHOLE_LINE:
449 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
450 case CTRL_X_FILES:
451 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
452 case CTRL_X_DICTIONARY:
453 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
454 case CTRL_X_THESAURUS:
455 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
456 case CTRL_X_TAGS:
457 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
458#ifdef FEAT_FIND_ID
459 case CTRL_X_PATH_PATTERNS:
460 return (c == Ctrl_P || c == Ctrl_N);
461 case CTRL_X_PATH_DEFINES:
462 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
463#endif
464 case CTRL_X_CMDLINE:
465 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
466 || c == Ctrl_X);
467#ifdef FEAT_COMPL_FUNC
468 case CTRL_X_FUNCTION:
469 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
470 case CTRL_X_OMNI:
471 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
472#endif
473 case CTRL_X_SPELL:
474 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
475 case CTRL_X_EVAL:
476 return (c == Ctrl_P || c == Ctrl_N);
477 }
478 internal_error("vim_is_ctrl_x_key()");
479 return FALSE;
480}
481
482/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000483 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000484 */
485 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000486match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000487{
488 return match->cp_flags & CP_ORIGINAL_TEXT;
489}
490
491/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000492 * Returns TRUE if "match" is the first match in the completion list.
493 */
494 static int
495is_first_match(compl_T *match)
496{
497 return match == compl_first_match;
498}
499
500/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100501 * Return TRUE when character "c" is part of the item currently being
502 * completed. Used to decide whether to abandon complete mode when the menu
503 * is visible.
504 */
505 int
506ins_compl_accept_char(int c)
507{
508 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
509 // When expanding an identifier only accept identifier chars.
510 return vim_isIDc(c);
511
512 switch (ctrl_x_mode)
513 {
514 case CTRL_X_FILES:
515 // When expanding file name only accept file name chars. But not
516 // path separators, so that "proto/<Tab>" expands files in
517 // "proto", not "proto/" as a whole
518 return vim_isfilec(c) && !vim_ispathsep(c);
519
520 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200521 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100522 case CTRL_X_OMNI:
523 // Command line and Omni completion can work with just about any
524 // printable character, but do stop at white space.
525 return vim_isprintc(c) && !VIM_ISWHITE(c);
526
527 case CTRL_X_WHOLE_LINE:
528 // For while line completion a space can be part of the line.
529 return vim_isprintc(c);
530 }
531 return vim_iswordc(c);
532}
533
534/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000535 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100536 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000537 */
538 static char_u *
539ins_compl_infercase_gettext(
540 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100541 int char_len,
542 int compl_char_len,
543 int min_len,
544 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000545{
546 int *wca; // Wide character array.
547 char_u *p;
548 int i, c;
549 int has_lower = FALSE;
550 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100551 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000552
553 IObuff[0] = NUL;
554
555 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100556 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000557 if (wca == NULL)
558 return IObuff;
559
560 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100561 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000562 if (has_mbyte)
563 wca[i] = mb_ptr2char_adv(&p);
564 else
565 wca[i] = *(p++);
566
567 // Rule 1: Were any chars converted to lower?
568 p = compl_orig_text;
569 for (i = 0; i < min_len; ++i)
570 {
571 if (has_mbyte)
572 c = mb_ptr2char_adv(&p);
573 else
574 c = *(p++);
575 if (MB_ISLOWER(c))
576 {
577 has_lower = TRUE;
578 if (MB_ISUPPER(wca[i]))
579 {
580 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100581 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 wca[i] = MB_TOLOWER(wca[i]);
583 break;
584 }
585 }
586 }
587
588 // Rule 2: No lower case, 2nd consecutive letter converted to
589 // upper case.
590 if (!has_lower)
591 {
592 p = compl_orig_text;
593 for (i = 0; i < min_len; ++i)
594 {
595 if (has_mbyte)
596 c = mb_ptr2char_adv(&p);
597 else
598 c = *(p++);
599 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
600 {
601 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100602 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000603 wca[i] = MB_TOUPPER(wca[i]);
604 break;
605 }
606 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
607 }
608 }
609
610 // Copy the original case of the part we typed.
611 p = compl_orig_text;
612 for (i = 0; i < min_len; ++i)
613 {
614 if (has_mbyte)
615 c = mb_ptr2char_adv(&p);
616 else
617 c = *(p++);
618 if (MB_ISLOWER(c))
619 wca[i] = MB_TOLOWER(wca[i]);
620 else if (MB_ISUPPER(c))
621 wca[i] = MB_TOUPPER(wca[i]);
622 }
623
624 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000625 p = IObuff;
626 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100627 ga_init2(&gap, 1, 500);
628 while (i < char_len)
629 {
630 if (gap.ga_data != NULL)
631 {
632 if (ga_grow(&gap, 10) == FAIL)
633 {
634 ga_clear(&gap);
635 return (char_u *)"[failed]";
636 }
637 p = (char_u *)gap.ga_data + gap.ga_len;
638 if (has_mbyte)
639 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
640 else
641 {
642 *p = wca[i++];
643 ++gap.ga_len;
644 }
645 }
646 else if ((p - IObuff) + 6 >= IOSIZE)
647 {
648 // Multi-byte characters can occupy up to five bytes more than
649 // ASCII characters, and we also need one byte for NUL, so when
650 // getting to six bytes from the edge of IObuff switch to using a
651 // growarray. Add the character in the next round.
652 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100653 {
654 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100655 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100656 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100657 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100658 STRCPY(gap.ga_data, IObuff);
Bram Moolenaarc7bd2f02022-07-15 20:45:20 +0100659 gap.ga_len = (int)STRLEN(IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100660 }
661 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000662 p += (*mb_char2bytes)(wca[i++], p);
663 else
664 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100665 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000666 vim_free(wca);
667
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100668 if (gap.ga_data != NULL)
669 {
670 *tofree = gap.ga_data;
671 return gap.ga_data;
672 }
673
674 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000675 return IObuff;
676}
677
678/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100679 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
680 * case of the originally typed text is used, and the case of the completed
681 * text is inferred, ie this tries to work out what case you probably wanted
682 * the rest of the word to be in -- webb
683 */
684 int
685ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200686 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100687 int len,
688 int icase,
689 char_u *fname,
690 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200691 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200693 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100694 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 int char_len; // count multi-byte characters
696 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100697 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200698 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100699 int res;
700 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100701
702 if (p_ic && curbuf->b_p_inf && len > 0)
703 {
704 // Infer case of completed part.
705
706 // Find actual length of completion.
707 if (has_mbyte)
708 {
709 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100710 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100711 while (*p != NUL)
712 {
713 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100714 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100715 }
716 }
717 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100718 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719
720 // Find actual length of original text.
721 if (has_mbyte)
722 {
723 p = compl_orig_text;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100724 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 while (*p != NUL)
726 {
727 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100728 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100729 }
730 }
731 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100732 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100734 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100737
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 str = ins_compl_infercase_gettext(str, char_len,
739 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100740 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200741 if (cont_s_ipos)
742 flags |= CP_CONT_S_IPOS;
743 if (icase)
744 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200745
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100746 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);
747 vim_free(tofree);
748 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100749}
750
751/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000752 * Add a match to the list of matches. The arguments are:
753 * str - text of the match to add
754 * len - length of "str". If -1, then the length of "str" is
755 * computed.
756 * fname - file name to associate with this match.
757 * cptext - list of strings to use with this match (for abbr, menu, info
758 * and kind)
759 * user_data - user supplied data (any vim type) for this match
760 * cdir - match direction. If 0, use "compl_direction".
761 * flags_arg - match flags (cp_flags)
762 * adup - accept this match even if it is already present.
763 * If "cdir" is FORWARD, then the match is added after the current match.
764 * Otherwise, it is added before the current match.
765 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 * If the given string is already in the list of completions, then return
767 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
768 * maybe because alloc() returns NULL, then FAIL is returned.
769 */
770 static int
771ins_compl_add(
772 char_u *str,
773 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100774 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100775 char_u **cptext, // extra text for popup menu or NULL
776 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200778 int flags_arg,
Bram Moolenaar08928322020-01-04 14:32:48 +0100779 int adup) // accept duplicate match
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780{
781 compl_T *match;
782 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200783 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784
Bram Moolenaarceb06192021-04-04 15:05:22 +0200785 if (flags & CP_FAST)
786 fast_breakcheck();
787 else
788 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100789 if (got_int)
790 return FAIL;
791 if (len < 0)
792 len = (int)STRLEN(str);
793
794 // If the same match is already present, don't add it.
795 if (compl_first_match != NULL && !adup)
796 {
797 match = compl_first_match;
798 do
799 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000800 if (!match_at_original_text(match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100801 && STRNCMP(match->cp_str, str, len) == 0
Bram Moolenaarbaefde12022-07-07 19:59:49 +0100802 && ((int)STRLEN(match->cp_str) <= len
803 || match->cp_str[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100804 return NOTDONE;
805 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000806 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100807 }
808
809 // Remove any popup menu before changing the list of matches.
810 ins_compl_del_pum();
811
812 // Allocate a new match structure.
813 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200814 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100815 if (match == NULL)
816 return FAIL;
817 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200818 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 match->cp_number = 0;
820 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
821 {
822 vim_free(match);
823 return FAIL;
824 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100825
826 // match-fname is:
827 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200828 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829 // - NULL otherwise. --Acevedo
830 if (fname != NULL
831 && compl_curr_match != NULL
832 && compl_curr_match->cp_fname != NULL
833 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
834 match->cp_fname = compl_curr_match->cp_fname;
835 else if (fname != NULL)
836 {
837 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200838 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100839 }
840 else
841 match->cp_fname = NULL;
842 match->cp_flags = flags;
843
844 if (cptext != NULL)
845 {
846 int i;
847
848 for (i = 0; i < CPT_COUNT; ++i)
849 if (cptext[i] != NULL && *cptext[i] != NUL)
850 match->cp_text[i] = vim_strsave(cptext[i]);
851 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100852#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100853 if (user_data != NULL)
854 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100855#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000857 // Link the new match structure after (FORWARD) or before (BACKWARD) the
858 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859 if (compl_first_match == NULL)
860 match->cp_next = match->cp_prev = NULL;
861 else if (dir == FORWARD)
862 {
863 match->cp_next = compl_curr_match->cp_next;
864 match->cp_prev = compl_curr_match;
865 }
866 else // BACKWARD
867 {
868 match->cp_next = compl_curr_match;
869 match->cp_prev = compl_curr_match->cp_prev;
870 }
871 if (match->cp_next)
872 match->cp_next->cp_prev = match;
873 if (match->cp_prev)
874 match->cp_prev->cp_next = match;
875 else // if there's nothing before, it is the first match
876 compl_first_match = match;
877 compl_curr_match = match;
878
879 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200880 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881 ins_compl_longest_match(match);
882
883 return OK;
884}
885
886/*
887 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 */
890 static int
891ins_compl_equal(compl_T *match, char_u *str, int len)
892{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200893 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200894 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200895 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100896 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
897 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
898}
899
900/*
901 * Reduce the longest common string for match "match".
902 */
903 static void
904ins_compl_longest_match(compl_T *match)
905{
906 char_u *p, *s;
907 int c1, c2;
908 int had_match;
909
910 if (compl_leader == NULL)
911 {
912 // First match, use it as a whole.
913 compl_leader = vim_strsave(match->cp_str);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000914 if (compl_leader == NULL)
915 return;
916
917 had_match = (curwin->w_cursor.col > compl_col);
918 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000919 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000920 ins_redraw(FALSE);
921
922 // When the match isn't there (to avoid matching itself) remove it
923 // again after redrawing.
924 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100925 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000927
928 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100929 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000930
931 // Reduce the text if this match differs from compl_leader.
932 p = compl_leader;
933 s = match->cp_str;
934 while (*p != NUL)
935 {
936 if (has_mbyte)
937 {
938 c1 = mb_ptr2char(p);
939 c2 = mb_ptr2char(s);
940 }
941 else
942 {
943 c1 = *p;
944 c2 = *s;
945 }
946 if ((match->cp_flags & CP_ICASE)
947 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
948 break;
949 if (has_mbyte)
950 {
951 MB_PTR_ADV(p);
952 MB_PTR_ADV(s);
953 }
954 else
955 {
956 ++p;
957 ++s;
958 }
959 }
960
961 if (*p != NUL)
962 {
963 // Leader was shortened, need to change the inserted text.
964 *p = NUL;
965 had_match = (curwin->w_cursor.col > compl_col);
966 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000967 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000968 ins_redraw(FALSE);
969
970 // When the match isn't there (to avoid matching itself) remove it
971 // again after redrawing.
972 if (!had_match)
973 ins_compl_delete();
974 }
975
976 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100977}
978
979/*
980 * Add an array of matches to the list of matches.
981 * Frees matches[].
982 */
983 static void
984ins_compl_add_matches(
985 int num_matches,
986 char_u **matches,
987 int icase)
988{
989 int i;
990 int add_r = OK;
991 int dir = compl_direction;
992
993 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100994 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
Bram Moolenaar440cf092021-04-03 20:13:30 +0200995 CP_FAST | (icase ? CP_ICASE : 0), FALSE)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100996 // if dir was BACKWARD then honor it just once
997 dir = FORWARD;
998 FreeWild(num_matches, matches);
999}
1000
1001/*
1002 * Make the completion list cyclic.
1003 * Return the number of matches (excluding the original).
1004 */
1005 static int
1006ins_compl_make_cyclic(void)
1007{
1008 compl_T *match;
1009 int count = 0;
1010
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001011 if (compl_first_match == NULL)
1012 return 0;
1013
1014 // Find the end of the list.
1015 match = compl_first_match;
1016 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001017 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001018 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001019 match = match->cp_next;
1020 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001021 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001022 match->cp_next = compl_first_match;
1023 compl_first_match->cp_prev = match;
1024
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001025 return count;
1026}
1027
1028/*
1029 * Return whether there currently is a shown match.
1030 */
1031 int
1032ins_compl_has_shown_match(void)
1033{
1034 return compl_shown_match == NULL
1035 || compl_shown_match != compl_shown_match->cp_next;
1036}
1037
1038/*
1039 * Return whether the shown match is long enough.
1040 */
1041 int
1042ins_compl_long_shown_match(void)
1043{
1044 return (int)STRLEN(compl_shown_match->cp_str)
1045 > curwin->w_cursor.col - compl_col;
1046}
1047
1048/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001049 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001050 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001051 unsigned int
1052get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001053{
zeertzjq529b9ad2024-06-05 20:27:06 +02001054 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001055}
1056
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001057
1058// "compl_match_array" points the currently displayed list of entries in the
1059// popup menu. It is NULL when there is no popup menu.
1060static pumitem_T *compl_match_array = NULL;
1061static int compl_match_arraysize;
1062
1063/*
1064 * Update the screen and when there is any scrolling remove the popup menu.
1065 */
1066 static void
1067ins_compl_upd_pum(void)
1068{
1069 int h;
1070
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001071 if (compl_match_array == NULL)
1072 return;
1073
1074 h = curwin->w_cline_height;
1075 // Update the screen later, before drawing the popup menu over it.
1076 pum_call_update_screen();
1077 if (h != curwin->w_cline_height)
1078 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001079}
1080
1081/*
1082 * Remove any popup menu.
1083 */
1084 static void
1085ins_compl_del_pum(void)
1086{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001087 if (compl_match_array == NULL)
1088 return;
1089
1090 pum_undisplay();
1091 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001092}
1093
1094/*
1095 * Return TRUE if the popup menu should be displayed.
1096 */
1097 int
1098pum_wanted(void)
1099{
1100 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001101 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001102 return FALSE;
1103
1104 // The display looks bad on a B&W display.
1105 if (t_colors < 8
1106#ifdef FEAT_GUI
1107 && !gui.in_use
1108#endif
1109 )
1110 return FALSE;
1111 return TRUE;
1112}
1113
1114/*
1115 * Return TRUE if there are two or more matches to be shown in the popup menu.
1116 * One if 'completopt' contains "menuone".
1117 */
1118 static int
1119pum_enough_matches(void)
1120{
1121 compl_T *compl;
1122 int i;
1123
1124 // Don't display the popup menu if there are no matches or there is only
1125 // one (ignoring the original text).
1126 compl = compl_first_match;
1127 i = 0;
1128 do
1129 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001130 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001131 break;
1132 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001133 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134
zeertzjq529b9ad2024-06-05 20:27:06 +02001135 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001136 return (i >= 1);
1137 return (i >= 2);
1138}
1139
Bram Moolenaar3075a452021-11-17 15:51:52 +00001140#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001141/*
1142 * Allocate Dict for the completed item.
1143 * { word, abbr, menu, kind, info }
1144 */
1145 static dict_T *
1146ins_compl_dict_alloc(compl_T *match)
1147{
1148 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1149
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001150 if (dict == NULL)
1151 return NULL;
1152
1153 dict_add_string(dict, "word", match->cp_str);
1154 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1155 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1156 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1157 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1158 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1159 dict_add_string(dict, "user_data", (char_u *)"");
1160 else
1161 dict_add_tv(dict, "user_data", &match->cp_user_data);
1162
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001163 return dict;
1164}
1165
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001166/*
1167 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1168 * completion menu is changed.
1169 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001170 static void
1171trigger_complete_changed_event(int cur)
1172{
1173 dict_T *v_event;
1174 dict_T *item;
1175 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001176 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001177
1178 if (recursive)
1179 return;
1180
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001181 if (cur < 0)
1182 item = dict_alloc();
1183 else
1184 item = ins_compl_dict_alloc(compl_curr_match);
1185 if (item == NULL)
1186 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001187 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001188 dict_add_dict(v_event, "completed_item", item);
1189 pum_set_event_info(v_event);
1190 dict_set_items_ro(v_event);
1191
1192 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001193 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001194 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001195 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001196 recursive = FALSE;
1197
Bram Moolenaar3075a452021-11-17 15:51:52 +00001198 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001199}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001200#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001201
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001202/*
glepnira218cc62024-06-03 19:32:39 +02001203 * pumitem qsort compare func
1204 */
1205 static int
zeertzjq8e567472024-06-14 20:04:42 +02001206ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001207{
1208 const int sa = (*(pumitem_T *)a).pum_score;
1209 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001210 const int ia = (*(pumitem_T *)a).pum_idx;
1211 const int ib = (*(pumitem_T *)b).pum_idx;
1212 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001213}
1214
1215/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001216 * Build a popup menu to show the completion matches.
1217 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1218 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001219 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001220 static int
1221ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001222{
1223 compl_T *compl;
1224 compl_T *shown_compl = NULL;
1225 int did_find_shown_match = FALSE;
1226 int shown_match_ok = FALSE;
1227 int i;
1228 int cur = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001229 int lead_len = 0;
glepnira218cc62024-06-03 19:32:39 +02001230 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001231 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001232 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1233 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001234
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001235 // Need to build the popup menu list.
1236 compl_match_arraysize = 0;
1237 compl = compl_first_match;
1238 if (compl_leader != NULL)
1239 lead_len = (int)STRLEN(compl_leader);
1240
1241 do
1242 {
zeertzjq551d8c32024-06-05 19:53:32 +02001243 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1244 // set the cp_score for later comparisons.
glepnira218cc62024-06-03 19:32:39 +02001245 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1246 compl->cp_score = fuzzy_match_str(compl->cp_str, compl_leader);
1247
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001248 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001249 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001250 || ins_compl_equal(compl, compl_leader, lead_len)
1251 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001252 ++compl_match_arraysize;
1253 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001254 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001255
1256 if (compl_match_arraysize == 0)
1257 return -1;
1258
1259 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1260 if (compl_match_array == NULL)
1261 return -1;
1262
1263 // If the current match is the original text don't find the first
1264 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001265 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001266 shown_match_ok = TRUE;
1267
glepnir53387c52024-05-27 15:11:01 +02001268 if (compl_leader != NULL
1269 && STRCMP(compl_leader, compl_orig_text) == 0
1270 && shown_match_ok == FALSE)
1271 compl_shown_match = compl_no_select ? compl_first_match
1272 : compl_first_match->cp_next;
1273
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001274 i = 0;
1275 compl = compl_first_match;
1276 do
1277 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001278 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001279 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001280 || ins_compl_equal(compl, compl_leader, lead_len)
1281 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001282 {
glepnira218cc62024-06-03 19:32:39 +02001283 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001284 {
1285 if (compl == compl_shown_match || did_find_shown_match)
1286 {
1287 // This item is the shown match or this is the
1288 // first displayed item after the shown match.
1289 compl_shown_match = compl;
1290 did_find_shown_match = TRUE;
1291 shown_match_ok = TRUE;
1292 }
1293 else
1294 // Remember this displayed match for when the
1295 // shown match is just below it.
1296 shown_compl = compl;
1297 cur = i;
1298 }
glepnira218cc62024-06-03 19:32:39 +02001299 else if (compl_fuzzy_match)
1300 {
glepnirf94c9c42024-06-14 21:11:56 +02001301 if (i == 0)
glepnir105f7412024-06-15 15:32:22 +02001302 shown_compl = compl;
glepnirdca57fb2024-06-04 22:01:21 +02001303 // Update the maximum fuzzy score and the shown match
1304 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001305 if (compl->cp_score > max_fuzzy_score)
1306 {
1307 did_find_shown_match = TRUE;
1308 max_fuzzy_score = compl->cp_score;
1309 compl_shown_match = compl;
1310 shown_match_ok = TRUE;
1311 }
1312
glepnirdca57fb2024-06-04 22:01:21 +02001313 // If there is no "no select" condition and the max fuzzy
1314 // score is positive, or there is no completion leader or the
1315 // leader length is zero, mark the shown match as valid and
1316 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001317 if (!compl_no_select
1318 && (max_fuzzy_score > 0
1319 || (compl_leader == NULL || lead_len == 0)))
1320 {
1321 shown_match_ok = TRUE;
1322 cur = 0;
glepnirf94c9c42024-06-14 21:11:56 +02001323 if (match_at_original_text(compl_shown_match))
glepnir105f7412024-06-15 15:32:22 +02001324 compl_shown_match = shown_compl;
glepnira218cc62024-06-03 19:32:39 +02001325 }
1326 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001327
1328 if (compl->cp_text[CPT_ABBR] != NULL)
1329 compl_match_array[i].pum_text =
1330 compl->cp_text[CPT_ABBR];
1331 else
1332 compl_match_array[i].pum_text = compl->cp_str;
1333 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1334 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001335 compl_match_array[i].pum_score = compl->cp_score;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001336 if (compl->cp_text[CPT_MENU] != NULL)
1337 compl_match_array[i++].pum_extra =
1338 compl->cp_text[CPT_MENU];
1339 else
1340 compl_match_array[i++].pum_extra = compl->cp_fname;
1341 }
1342
glepnira218cc62024-06-03 19:32:39 +02001343 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001344 {
1345 did_find_shown_match = TRUE;
1346
1347 // When the original text is the shown match don't set
1348 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001349 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001350 shown_match_ok = TRUE;
1351
1352 if (!shown_match_ok && shown_compl != NULL)
1353 {
1354 // The shown match isn't displayed, set it to the
1355 // previously displayed match.
1356 compl_shown_match = shown_compl;
1357 shown_match_ok = TRUE;
1358 }
1359 }
1360 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001361 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001362
glepnira218cc62024-06-03 19:32:39 +02001363 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001364 {
1365 for (i = 0; i < compl_match_arraysize; i++)
1366 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001367 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001368 qsort(compl_match_array, (size_t)compl_match_arraysize,
1369 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
1370 }
glepnira218cc62024-06-03 19:32:39 +02001371
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001372 if (!shown_match_ok) // no displayed match at all
1373 cur = -1;
1374
1375 return cur;
1376}
1377
1378/*
1379 * Show the popup menu for the list of matches.
1380 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1381 */
1382 void
1383ins_compl_show_pum(void)
1384{
1385 int i;
1386 int cur = -1;
1387 colnr_T col;
1388
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001389 if (!pum_wanted() || !pum_enough_matches())
1390 return;
1391
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001392 // Update the screen later, before drawing the popup menu over it.
1393 pum_call_update_screen();
1394
1395 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001396 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001397 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001398 else
1399 {
1400 // popup menu already exists, only need to find the current item.
1401 for (i = 0; i < compl_match_arraysize; ++i)
1402 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1403 || compl_match_array[i].pum_text
1404 == compl_shown_match->cp_text[CPT_ABBR])
1405 {
1406 cur = i;
1407 break;
1408 }
1409 }
1410
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001411 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001412 {
1413#ifdef FEAT_EVAL
1414 if (compl_started && has_completechanged())
1415 trigger_complete_changed_event(cur);
1416#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001417 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001418 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001419
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001420 // In Replace mode when a $ is displayed at the end of the line only
1421 // part of the screen would be updated. We do need to redraw here.
1422 dollar_vcol = -1;
1423
1424 // Compute the screen column of the start of the completed text.
1425 // Use the cursor to get all wrapping and other settings right.
1426 col = curwin->w_cursor.col;
1427 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001428 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001429 pum_display(compl_match_array, compl_match_arraysize, cur);
1430 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001431
glepnircbb46b42024-02-03 18:11:13 +01001432 // After adding leader, set the current match to shown match.
1433 if (compl_started && compl_curr_match != compl_shown_match)
1434 compl_curr_match = compl_shown_match;
1435
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001436#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001437 if (has_completechanged())
1438 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001439#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001440}
1441
1442#define DICT_FIRST (1) // use just first element in "dict"
1443#define DICT_EXACT (2) // "dict" is the exact name of a file
1444
1445/*
glepnir40c1c332024-06-11 19:37:04 +02001446 * Get current completion leader
1447 */
1448 char_u *
1449ins_compl_leader(void)
1450{
glepnirf1891382024-06-17 18:35:25 +02001451 return compl_leader != NULL ? compl_leader : compl_orig_text;
glepnir40c1c332024-06-11 19:37:04 +02001452}
1453
1454/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001455 * Add any identifiers that match the given pattern "pat" in the list of
1456 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001457 */
1458 static void
1459ins_compl_dictionaries(
1460 char_u *dict_start,
1461 char_u *pat,
1462 int flags, // DICT_FIRST and/or DICT_EXACT
1463 int thesaurus) // Thesaurus completion
1464{
1465 char_u *dict = dict_start;
1466 char_u *ptr;
1467 char_u *buf;
1468 regmatch_T regmatch;
1469 char_u **files;
1470 int count;
1471 int save_p_scs;
1472 int dir = compl_direction;
1473
1474 if (*dict == NUL)
1475 {
1476#ifdef FEAT_SPELL
1477 // When 'dictionary' is empty and spell checking is enabled use
1478 // "spell".
1479 if (!thesaurus && curwin->w_p_spell)
1480 dict = (char_u *)"spell";
1481 else
1482#endif
1483 return;
1484 }
1485
1486 buf = alloc(LSIZE);
1487 if (buf == NULL)
1488 return;
1489 regmatch.regprog = NULL; // so that we can goto theend
1490
1491 // If 'infercase' is set, don't use 'smartcase' here
1492 save_p_scs = p_scs;
1493 if (curbuf->b_p_inf)
1494 p_scs = FALSE;
1495
1496 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1497 // to only match at the start of a line. Otherwise just match the
1498 // pattern. Also need to double backslashes.
1499 if (ctrl_x_mode_line_or_eval())
1500 {
1501 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1502 size_t len;
1503
1504 if (pat_esc == NULL)
1505 goto theend;
1506 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001507 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001508 if (ptr == NULL)
1509 {
1510 vim_free(pat_esc);
1511 goto theend;
1512 }
1513 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1514 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1515 vim_free(pat_esc);
1516 vim_free(ptr);
1517 }
1518 else
1519 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001520 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001521 if (regmatch.regprog == NULL)
1522 goto theend;
1523 }
1524
1525 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1526 regmatch.rm_ic = ignorecase(pat);
1527 while (*dict != NUL && !got_int && !compl_interrupted)
1528 {
1529 // copy one dictionary file name into buf
1530 if (flags == DICT_EXACT)
1531 {
1532 count = 1;
1533 files = &dict;
1534 }
1535 else
1536 {
1537 // Expand wildcards in the dictionary name, but do not allow
1538 // backticks (for security, the 'dict' option may have been set in
1539 // a modeline).
1540 copy_option_part(&dict, buf, LSIZE, ",");
1541# ifdef FEAT_SPELL
1542 if (!thesaurus && STRCMP(buf, "spell") == 0)
1543 count = -1;
1544 else
1545# endif
1546 if (vim_strchr(buf, '`') != NULL
1547 || expand_wildcards(1, &buf, &count, &files,
1548 EW_FILE|EW_SILENT) != OK)
1549 count = 0;
1550 }
1551
1552# ifdef FEAT_SPELL
1553 if (count == -1)
1554 {
1555 // Complete from active spelling. Skip "\<" in the pattern, we
1556 // don't use it as a RE.
1557 if (pat[0] == '\\' && pat[1] == '<')
1558 ptr = pat + 2;
1559 else
1560 ptr = pat;
1561 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1562 }
1563 else
1564# endif
1565 if (count > 0) // avoid warning for using "files" uninit
1566 {
1567 ins_compl_files(count, files, thesaurus, flags,
1568 &regmatch, buf, &dir);
1569 if (flags != DICT_EXACT)
1570 FreeWild(count, files);
1571 }
1572 if (flags != 0)
1573 break;
1574 }
1575
1576theend:
1577 p_scs = save_p_scs;
1578 vim_regfree(regmatch.regprog);
1579 vim_free(buf);
1580}
1581
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001582/*
1583 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1584 * skipping the word at 'skip_word'. Returns OK on success.
1585 */
1586 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001587thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001588 char_u *fname,
1589 char_u **buf_arg,
1590 int dir,
1591 char_u *skip_word)
1592{
1593 int status = OK;
1594 char_u *ptr;
1595 char_u *wstart;
1596
1597 // Add the other matches on the line
1598 ptr = *buf_arg;
1599 while (!got_int)
1600 {
1601 // Find start of the next word. Skip white
1602 // space and punctuation.
1603 ptr = find_word_start(ptr);
1604 if (*ptr == NUL || *ptr == NL)
1605 break;
1606 wstart = ptr;
1607
1608 // Find end of the word.
1609 if (has_mbyte)
1610 // Japanese words may have characters in
1611 // different classes, only separate words
1612 // with single-byte non-word characters.
1613 while (*ptr != NUL)
1614 {
1615 int l = (*mb_ptr2len)(ptr);
1616
1617 if (l < 2 && !vim_iswordc(*ptr))
1618 break;
1619 ptr += l;
1620 }
1621 else
1622 ptr = find_word_end(ptr);
1623
1624 // Add the word. Skip the regexp match.
1625 if (wstart != skip_word)
1626 {
1627 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1628 fname, dir, FALSE);
1629 if (status == FAIL)
1630 break;
1631 }
1632 }
1633
1634 *buf_arg = ptr;
1635 return status;
1636}
1637
1638/*
1639 * Process "count" dictionary/thesaurus "files" and add the text matching
1640 * "regmatch".
1641 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001642 static void
1643ins_compl_files(
1644 int count,
1645 char_u **files,
1646 int thesaurus,
1647 int flags,
1648 regmatch_T *regmatch,
1649 char_u *buf,
1650 int *dir)
1651{
1652 char_u *ptr;
1653 int i;
1654 FILE *fp;
1655 int add_r;
1656
1657 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1658 {
1659 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001660 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001661 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001662 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001663 vim_snprintf((char *)IObuff, IOSIZE,
1664 _("Scanning dictionary: %s"), (char *)files[i]);
1665 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1666 }
1667
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001668 if (fp == NULL)
1669 continue;
1670
1671 // Read dictionary file line by line.
1672 // Check each line for a match.
1673 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001674 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001675 ptr = buf;
1676 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001677 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001678 ptr = regmatch->startp[0];
1679 if (ctrl_x_mode_line_or_eval())
1680 ptr = find_line_end(ptr);
1681 else
1682 ptr = find_word_end(ptr);
1683 add_r = ins_compl_add_infercase(regmatch->startp[0],
1684 (int)(ptr - regmatch->startp[0]),
1685 p_ic, files[i], *dir, FALSE);
1686 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001687 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001688 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001689 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001690 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001691 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001692 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001693 if (add_r == OK)
1694 // if dir was BACKWARD then honor it just once
1695 *dir = FORWARD;
1696 else if (add_r == FAIL)
1697 break;
1698 // avoid expensive call to vim_regexec() when at end
1699 // of line
1700 if (*ptr == '\n' || got_int)
1701 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001702 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001703 line_breakcheck();
1704 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001705 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001706 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001707 }
1708}
1709
1710/*
1711 * Find the start of the next word.
1712 * Returns a pointer to the first char of the word. Also stops at a NUL.
1713 */
1714 char_u *
1715find_word_start(char_u *ptr)
1716{
1717 if (has_mbyte)
1718 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1719 ptr += (*mb_ptr2len)(ptr);
1720 else
1721 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1722 ++ptr;
1723 return ptr;
1724}
1725
1726/*
1727 * Find the end of the word. Assumes it starts inside a word.
1728 * Returns a pointer to just after the word.
1729 */
1730 char_u *
1731find_word_end(char_u *ptr)
1732{
1733 int start_class;
1734
1735 if (has_mbyte)
1736 {
1737 start_class = mb_get_class(ptr);
1738 if (start_class > 1)
1739 while (*ptr != NUL)
1740 {
1741 ptr += (*mb_ptr2len)(ptr);
1742 if (mb_get_class(ptr) != start_class)
1743 break;
1744 }
1745 }
1746 else
1747 while (vim_iswordc(*ptr))
1748 ++ptr;
1749 return ptr;
1750}
1751
1752/*
1753 * Find the end of the line, omitting CR and NL at the end.
1754 * Returns a pointer to just after the line.
1755 */
1756 static char_u *
1757find_line_end(char_u *ptr)
1758{
1759 char_u *s;
1760
1761 s = ptr + STRLEN(ptr);
1762 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1763 --s;
1764 return s;
1765}
1766
1767/*
1768 * Free the list of completions
1769 */
1770 static void
1771ins_compl_free(void)
1772{
1773 compl_T *match;
1774 int i;
1775
1776 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001777 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001778 VIM_CLEAR(compl_leader);
1779
1780 if (compl_first_match == NULL)
1781 return;
1782
1783 ins_compl_del_pum();
1784 pum_clear();
1785
1786 compl_curr_match = compl_first_match;
1787 do
1788 {
1789 match = compl_curr_match;
1790 compl_curr_match = compl_curr_match->cp_next;
1791 vim_free(match->cp_str);
1792 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001793 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001794 vim_free(match->cp_fname);
1795 for (i = 0; i < CPT_COUNT; ++i)
1796 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001797#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001798 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001799#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001800 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001801 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001802 compl_first_match = compl_curr_match = NULL;
1803 compl_shown_match = NULL;
1804 compl_old_match = NULL;
1805}
1806
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001807/*
1808 * Reset/clear the completion state.
1809 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001810 void
1811ins_compl_clear(void)
1812{
1813 compl_cont_status = 0;
1814 compl_started = FALSE;
1815 compl_matches = 0;
1816 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001817 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001818 VIM_CLEAR(compl_leader);
1819 edit_submode_extra = NULL;
1820 VIM_CLEAR(compl_orig_text);
1821 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001822#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001823 // clear v:completed_item
1824 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001825#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001826}
1827
1828/*
1829 * Return TRUE when Insert completion is active.
1830 */
1831 int
1832ins_compl_active(void)
1833{
1834 return compl_started;
1835}
1836
1837/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001838 * Selected one of the matches. When FALSE the match was edited or using the
1839 * longest common string.
1840 */
1841 int
1842ins_compl_used_match(void)
1843{
1844 return compl_used_match;
1845}
1846
1847/*
1848 * Initialize get longest common string.
1849 */
1850 void
1851ins_compl_init_get_longest(void)
1852{
1853 compl_get_longest = FALSE;
1854}
1855
1856/*
1857 * Returns TRUE when insert completion is interrupted.
1858 */
1859 int
1860ins_compl_interrupted(void)
1861{
1862 return compl_interrupted;
1863}
1864
1865/*
1866 * Returns TRUE if the <Enter> key selects a match in the completion popup
1867 * menu.
1868 */
1869 int
1870ins_compl_enter_selects(void)
1871{
1872 return compl_enter_selects;
1873}
1874
1875/*
1876 * Return the column where the text starts that is being completed
1877 */
1878 colnr_T
1879ins_compl_col(void)
1880{
1881 return compl_col;
1882}
1883
1884/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001885 * Return the length in bytes of the text being completed
1886 */
1887 int
1888ins_compl_len(void)
1889{
1890 return compl_length;
1891}
1892
1893/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001894 * Delete one character before the cursor and show the subset of the matches
1895 * that match the word that is now before the cursor.
1896 * Returns the character to be used, NUL if the work is done and another char
1897 * to be got from the user.
1898 */
1899 int
1900ins_compl_bs(void)
1901{
1902 char_u *line;
1903 char_u *p;
1904
1905 line = ml_get_curline();
1906 p = line + curwin->w_cursor.col;
1907 MB_PTR_BACK(line, p);
1908
1909 // Stop completion when the whole word was deleted. For Omni completion
1910 // allow the word to be deleted, we won't match everything.
1911 // Respect the 'backspace' option.
1912 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001913 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1914 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001915 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1916 - compl_length < 0))
1917 return K_BS;
1918
1919 // Deleted more than what was used to find matches or didn't finish
1920 // finding all matches: need to look for matches all over again.
1921 if (curwin->w_cursor.col <= compl_col + compl_length
1922 || ins_compl_need_restart())
1923 ins_compl_restart();
1924
1925 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001926 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001927 if (compl_leader == NULL)
1928 return K_BS;
1929
1930 ins_compl_new_leader();
1931 if (compl_shown_match != NULL)
1932 // Make sure current match is not a hidden item.
1933 compl_curr_match = compl_shown_match;
1934 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001935}
1936
1937/*
1938 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1939 * be called.
1940 */
1941 static int
1942ins_compl_need_restart(void)
1943{
1944 // Return TRUE if we didn't complete finding matches or when the
1945 // 'completefunc' returned "always" in the "refresh" dictionary item.
1946 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001947 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001948 && compl_opt_refresh_always);
1949}
1950
1951/*
1952 * Called after changing "compl_leader".
1953 * Show the popup menu with a different set of matches.
1954 * May also search for matches again if the previous search was interrupted.
1955 */
1956 static void
1957ins_compl_new_leader(void)
1958{
1959 ins_compl_del_pum();
1960 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001961 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001962 compl_used_match = FALSE;
1963
1964 if (compl_started)
1965 ins_compl_set_original_text(compl_leader);
1966 else
1967 {
1968#ifdef FEAT_SPELL
1969 spell_bad_len = 0; // need to redetect bad word
1970#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001971 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001972 // the popup menu display the changed text before the cursor. Set
1973 // "compl_restarting" to avoid that the first match is inserted.
1974 pum_call_update_screen();
1975#ifdef FEAT_GUI
1976 if (gui.in_use)
1977 {
1978 // Show the cursor after the match, not after the redrawn text.
1979 setcursor();
1980 out_flush_cursor(FALSE, FALSE);
1981 }
1982#endif
1983 compl_restarting = TRUE;
1984 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1985 compl_cont_status = 0;
1986 compl_restarting = FALSE;
1987 }
1988
1989 compl_enter_selects = !compl_used_match;
1990
1991 // Show the popup menu with a different set of matches.
1992 ins_compl_show_pum();
1993
1994 // Don't let Enter select the original text when there is no popup menu.
1995 if (compl_match_array == NULL)
1996 compl_enter_selects = FALSE;
1997}
1998
1999/*
2000 * Return the length of the completion, from the completion start column to
2001 * the cursor column. Making sure it never goes below zero.
2002 */
2003 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002004get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002005{
2006 int off = (int)curwin->w_cursor.col - (int)compl_col;
2007
2008 if (off < 0)
2009 return 0;
2010 return off;
2011}
2012
2013/*
2014 * Append one character to the match leader. May reduce the number of
2015 * matches.
2016 */
2017 void
2018ins_compl_addleader(int c)
2019{
2020 int cc;
2021
2022 if (stop_arrow() == FAIL)
2023 return;
2024 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2025 {
2026 char_u buf[MB_MAXBYTES + 1];
2027
2028 (*mb_char2bytes)(c, buf);
2029 buf[cc] = NUL;
2030 ins_char_bytes(buf, cc);
2031 if (compl_opt_refresh_always)
2032 AppendToRedobuff(buf);
2033 }
2034 else
2035 {
2036 ins_char(c);
2037 if (compl_opt_refresh_always)
2038 AppendCharToRedobuff(c);
2039 }
2040
2041 // If we didn't complete finding matches we must search again.
2042 if (ins_compl_need_restart())
2043 ins_compl_restart();
2044
2045 // When 'always' is set, don't reset compl_leader. While completing,
2046 // cursor doesn't point original position, changing compl_leader would
2047 // break redo.
2048 if (!compl_opt_refresh_always)
2049 {
2050 vim_free(compl_leader);
2051 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002052 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002053 if (compl_leader != NULL)
2054 ins_compl_new_leader();
2055 }
2056}
2057
2058/*
2059 * Setup for finding completions again without leaving CTRL-X mode. Used when
2060 * BS or a key was typed while still searching for matches.
2061 */
2062 static void
2063ins_compl_restart(void)
2064{
2065 ins_compl_free();
2066 compl_started = FALSE;
2067 compl_matches = 0;
2068 compl_cont_status = 0;
2069 compl_cont_mode = 0;
2070}
2071
2072/*
2073 * Set the first match, the original text.
2074 */
2075 static void
2076ins_compl_set_original_text(char_u *str)
2077{
2078 char_u *p;
2079
2080 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002081 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2082 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002083 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002084 {
2085 p = vim_strsave(str);
2086 if (p != NULL)
2087 {
2088 vim_free(compl_first_match->cp_str);
2089 compl_first_match->cp_str = p;
2090 }
2091 }
2092 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002093 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002094 {
2095 p = vim_strsave(str);
2096 if (p != NULL)
2097 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002098 vim_free(compl_first_match->cp_prev->cp_str);
2099 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002100 }
2101 }
2102}
2103
2104/*
2105 * Append one character to the match leader. May reduce the number of
2106 * matches.
2107 */
2108 void
2109ins_compl_addfrommatch(void)
2110{
2111 char_u *p;
2112 int len = (int)curwin->w_cursor.col - (int)compl_col;
2113 int c;
2114 compl_T *cp;
2115
2116 p = compl_shown_match->cp_str;
2117 if ((int)STRLEN(p) <= len) // the match is too short
2118 {
2119 // When still at the original match use the first entry that matches
2120 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002121 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002122 return;
2123
2124 p = NULL;
2125 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002126 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002127 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002128 if (compl_leader == NULL
2129 || ins_compl_equal(cp, compl_leader,
2130 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002131 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002132 p = cp->cp_str;
2133 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002134 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002135 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002136 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002137 return;
2138 }
2139 p += len;
2140 c = PTR2CHAR(p);
2141 ins_compl_addleader(c);
2142}
2143
2144/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002145 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002146 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2147 * compl_cont_mode and compl_cont_status.
2148 * Returns TRUE when the character is not to be inserted.
2149 */
2150 static int
2151set_ctrl_x_mode(int c)
2152{
2153 int retval = FALSE;
2154
2155 switch (c)
2156 {
2157 case Ctrl_E:
2158 case Ctrl_Y:
2159 // scroll the window one line up or down
2160 ctrl_x_mode = CTRL_X_SCROLL;
2161 if (!(State & REPLACE_FLAG))
2162 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2163 else
2164 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2165 edit_submode_pre = NULL;
2166 showmode();
2167 break;
2168 case Ctrl_L:
2169 // complete whole line
2170 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2171 break;
2172 case Ctrl_F:
2173 // complete filenames
2174 ctrl_x_mode = CTRL_X_FILES;
2175 break;
2176 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002177 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002178 ctrl_x_mode = CTRL_X_DICTIONARY;
2179 break;
2180 case Ctrl_R:
2181 // Register insertion without exiting CTRL-X mode
2182 // Simply allow ^R to happen without affecting ^X mode
2183 break;
2184 case Ctrl_T:
2185 // complete words from a thesaurus
2186 ctrl_x_mode = CTRL_X_THESAURUS;
2187 break;
2188#ifdef FEAT_COMPL_FUNC
2189 case Ctrl_U:
2190 // user defined completion
2191 ctrl_x_mode = CTRL_X_FUNCTION;
2192 break;
2193 case Ctrl_O:
2194 // omni completion
2195 ctrl_x_mode = CTRL_X_OMNI;
2196 break;
2197#endif
2198 case 's':
2199 case Ctrl_S:
2200 // complete spelling suggestions
2201 ctrl_x_mode = CTRL_X_SPELL;
2202#ifdef FEAT_SPELL
2203 ++emsg_off; // Avoid getting the E756 error twice.
2204 spell_back_to_badword();
2205 --emsg_off;
2206#endif
2207 break;
2208 case Ctrl_RSB:
2209 // complete tag names
2210 ctrl_x_mode = CTRL_X_TAGS;
2211 break;
2212#ifdef FEAT_FIND_ID
2213 case Ctrl_I:
2214 case K_S_TAB:
2215 // complete keywords from included files
2216 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2217 break;
2218 case Ctrl_D:
2219 // complete definitions from included files
2220 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2221 break;
2222#endif
2223 case Ctrl_V:
2224 case Ctrl_Q:
2225 // complete vim commands
2226 ctrl_x_mode = CTRL_X_CMDLINE;
2227 break;
2228 case Ctrl_Z:
2229 // stop completion
2230 ctrl_x_mode = CTRL_X_NORMAL;
2231 edit_submode = NULL;
2232 showmode();
2233 retval = TRUE;
2234 break;
2235 case Ctrl_P:
2236 case Ctrl_N:
2237 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2238 // just started ^X mode, or there were enough ^X's to cancel
2239 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2240 // do normal expansion when interrupting a different mode (say
2241 // ^X^F^X^P or ^P^X^X^P, see below)
2242 // nothing changes if interrupting mode 0, (eg, the flag
2243 // doesn't change when going to ADDING mode -- Acevedo
2244 if (!(compl_cont_status & CONT_INTRPT))
2245 compl_cont_status |= CONT_LOCAL;
2246 else if (compl_cont_mode != 0)
2247 compl_cont_status &= ~CONT_LOCAL;
2248 // FALLTHROUGH
2249 default:
2250 // If we have typed at least 2 ^X's... for modes != 0, we set
2251 // compl_cont_status = 0 (eg, as if we had just started ^X
2252 // mode).
2253 // For mode 0, we set "compl_cont_mode" to an impossible
2254 // value, in both cases ^X^X can be used to restart the same
2255 // mode (avoiding ADDING mode).
2256 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2257 // 'complete' and local ^P expansions respectively.
2258 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2259 // mode -- Acevedo
2260 if (c == Ctrl_X)
2261 {
2262 if (compl_cont_mode != 0)
2263 compl_cont_status = 0;
2264 else
2265 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2266 }
2267 ctrl_x_mode = CTRL_X_NORMAL;
2268 edit_submode = NULL;
2269 showmode();
2270 break;
2271 }
2272
2273 return retval;
2274}
2275
2276/*
2277 * Stop insert completion mode
2278 */
2279 static int
2280ins_compl_stop(int c, int prev_mode, int retval)
2281{
2282 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002283 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002284
2285 // Get here when we have finished typing a sequence of ^N and
2286 // ^P or other completion characters in CTRL-X mode. Free up
2287 // memory that was used, and make sure we can redo the insert.
2288 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2289 {
2290 // If any of the original typed text has been changed, eg when
2291 // ignorecase is set, we must add back-spaces to the redo
2292 // buffer. We add as few as necessary to delete just the part
2293 // of the original text that has changed.
2294 // When using the longest match, edited the match or used
2295 // CTRL-E then don't use the current match.
2296 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2297 ptr = compl_curr_match->cp_str;
2298 else
2299 ptr = NULL;
2300 ins_compl_fixRedoBufForLeader(ptr);
2301 }
2302
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002303 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002304
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002305 // When completing whole lines: fix indent for 'cindent'.
2306 // Otherwise, break line if it's too long.
2307 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2308 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002309 // re-indent the current line
2310 if (want_cindent)
2311 {
2312 do_c_expr_indent();
2313 want_cindent = FALSE; // don't do it again
2314 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002315 }
2316 else
2317 {
2318 int prev_col = curwin->w_cursor.col;
2319
2320 // put the cursor on the last char, for 'tw' formatting
2321 if (prev_col > 0)
2322 dec_cursor();
2323 // only format when something was inserted
2324 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2325 insertchar(NUL, 0, -1);
2326 if (prev_col > 0
2327 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2328 inc_cursor();
2329 }
2330
2331 // If the popup menu is displayed pressing CTRL-Y means accepting
2332 // the selection without inserting anything. When
2333 // compl_enter_selects is set the Enter key does the same.
2334 if ((c == Ctrl_Y || (compl_enter_selects
2335 && (c == CAR || c == K_KENTER || c == NL)))
2336 && pum_visible())
2337 retval = TRUE;
2338
2339 // CTRL-E means completion is Ended, go back to the typed text.
2340 // but only do this, if the Popup is still visible
2341 if (c == Ctrl_E)
2342 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002343 char_u *p = NULL;
2344
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002345 ins_compl_delete();
2346 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002347 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002348 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002349 p = compl_orig_text;
2350 if (p != NULL)
2351 {
2352 int compl_len = get_compl_len();
2353 int len = (int)STRLEN(p);
2354
2355 if (len > compl_len)
2356 ins_bytes_len(p + compl_len, len - compl_len);
2357 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002358 retval = TRUE;
2359 }
2360
2361 auto_format(FALSE, TRUE);
2362
2363 // Trigger the CompleteDonePre event to give scripts a chance to
2364 // act upon the completion before clearing the info, and restore
2365 // ctrl_x_mode, so that complete_info() can be used.
2366 ctrl_x_mode = prev_mode;
2367 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2368
2369 ins_compl_free();
2370 compl_started = FALSE;
2371 compl_matches = 0;
2372 if (!shortmess(SHM_COMPLETIONMENU))
2373 msg_clr_cmdline(); // necessary for "noshowmode"
2374 ctrl_x_mode = CTRL_X_NORMAL;
2375 compl_enter_selects = FALSE;
2376 if (edit_submode != NULL)
2377 {
2378 edit_submode = NULL;
2379 showmode();
2380 }
2381
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002382 if (c == Ctrl_C && cmdwin_type != 0)
2383 // Avoid the popup menu remains displayed when leaving the
2384 // command line window.
2385 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002386 // Indent now if a key was typed that is in 'cinkeys'.
2387 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2388 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002389 // Trigger the CompleteDone event to give scripts a chance to act
2390 // upon the end of completion.
2391 ins_apply_autocmds(EVENT_COMPLETEDONE);
2392
2393 return retval;
2394}
2395
2396/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002397 * Prepare for Insert mode completion, or stop it.
2398 * Called just after typing a character in Insert mode.
2399 * Returns TRUE when the character is not to be inserted;
2400 */
2401 int
2402ins_compl_prep(int c)
2403{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002404 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002405 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002406
2407 // Forget any previous 'special' messages if this is actually
2408 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2409 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2410 edit_submode_extra = NULL;
2411
zeertzjq440d4cb2023-03-02 17:51:32 +00002412 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002413 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002414 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002415 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002416 return retval;
2417
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002418#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002419 // Ignore mouse events in a popup window
2420 if (is_mouse_key(c))
2421 {
2422 // Ignore drag and release events, the position does not need to be in
2423 // the popup and it may have just closed.
2424 if (c == K_LEFTRELEASE
2425 || c == K_LEFTRELEASE_NM
2426 || c == K_MIDDLERELEASE
2427 || c == K_RIGHTRELEASE
2428 || c == K_X1RELEASE
2429 || c == K_X2RELEASE
2430 || c == K_LEFTDRAG
2431 || c == K_MIDDLEDRAG
2432 || c == K_RIGHTDRAG
2433 || c == K_X1DRAG
2434 || c == K_X2DRAG)
2435 return retval;
2436 if (popup_visible)
2437 {
2438 int row = mouse_row;
2439 int col = mouse_col;
2440 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2441
2442 if (wp != NULL && WIN_IS_POPUP(wp))
2443 return retval;
2444 }
2445 }
2446#endif
2447
zeertzjqdca29d92021-08-31 19:12:51 +02002448 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2449 {
2450 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2451 || !vim_is_ctrl_x_key(c))
2452 {
2453 // Not starting another completion mode.
2454 ctrl_x_mode = CTRL_X_CMDLINE;
2455
2456 // CTRL-X CTRL-Z should stop completion without inserting anything
2457 if (c == Ctrl_Z)
2458 retval = TRUE;
2459 }
2460 else
2461 {
2462 ctrl_x_mode = CTRL_X_CMDLINE;
2463
2464 // Other CTRL-X keys first stop completion, then start another
2465 // completion mode.
2466 ins_compl_prep(' ');
2467 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2468 }
2469 }
2470
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002471 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002472 if (ctrl_x_mode_not_defined_yet()
2473 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002474 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002475 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002476 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002477 }
2478
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002479 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002480 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2481 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002482 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002483 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002484 {
2485 // We're already in CTRL-X mode, do we stay in it?
2486 if (!vim_is_ctrl_x_key(c))
2487 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002488 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002489 ctrl_x_mode = CTRL_X_NORMAL;
2490 else
2491 ctrl_x_mode = CTRL_X_FINISHED;
2492 edit_submode = NULL;
2493 }
2494 showmode();
2495 }
2496
2497 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2498 {
2499 // Show error message from attempted keyword completion (probably
2500 // 'Pattern not found') until another key is hit, then go back to
2501 // showing what mode we are in.
2502 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002503 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002504 && c != Ctrl_R && !ins_compl_pum_key(c))
2505 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002506 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002507 }
2508 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2509 // Trigger the CompleteDone event to give scripts a chance to act
2510 // upon the (possibly failed) completion.
2511 ins_apply_autocmds(EVENT_COMPLETEDONE);
2512
LemonBoy2bf52dd2022-04-09 18:17:34 +01002513 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002514
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002515 // reset continue_* if we left expansion-mode, if we stay they'll be
2516 // (re)set properly in ins_complete()
2517 if (!vim_is_ctrl_x_key(c))
2518 {
2519 compl_cont_status = 0;
2520 compl_cont_mode = 0;
2521 }
2522
2523 return retval;
2524}
2525
2526/*
2527 * Fix the redo buffer for the completion leader replacing some of the typed
2528 * text. This inserts backspaces and appends the changed text.
2529 * "ptr" is the known leader text or NUL.
2530 */
2531 static void
2532ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2533{
2534 int len;
2535 char_u *p;
2536 char_u *ptr = ptr_arg;
2537
2538 if (ptr == NULL)
2539 {
2540 if (compl_leader != NULL)
2541 ptr = compl_leader;
2542 else
2543 return; // nothing to do
2544 }
2545 if (compl_orig_text != NULL)
2546 {
2547 p = compl_orig_text;
2548 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2549 ;
2550 if (len > 0)
2551 len -= (*mb_head_off)(p, p + len);
2552 for (p += len; *p != NUL; MB_PTR_ADV(p))
2553 AppendCharToRedobuff(K_BS);
2554 }
2555 else
2556 len = 0;
2557 if (ptr != NULL)
2558 AppendToRedobuffLit(ptr + len, -1);
2559}
2560
2561/*
2562 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2563 * (depending on flag) starting from buf and looking for a non-scanned
2564 * buffer (other than curbuf). curbuf is special, if it is called with
2565 * buf=curbuf then it has to be the first call for a given flag/expansion.
2566 *
2567 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2568 */
2569 static buf_T *
2570ins_compl_next_buf(buf_T *buf, int flag)
2571{
2572 static win_T *wp = NULL;
2573
2574 if (flag == 'w') // just windows
2575 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002576 if (buf == curbuf || !win_valid(wp))
2577 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002578 wp = curwin;
2579 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2580 && wp->w_buffer->b_scanned)
2581 ;
2582 buf = wp->w_buffer;
2583 }
2584 else
2585 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2586 // (unlisted buffers)
2587 // When completing whole lines skip unloaded buffers.
2588 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2589 && ((flag == 'U'
2590 ? buf->b_p_bl
2591 : (!buf->b_p_bl
2592 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2593 || buf->b_scanned))
2594 ;
2595 return buf;
2596}
2597
2598#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002599
2600# ifdef FEAT_EVAL
2601static callback_T cfu_cb; // 'completefunc' callback function
2602static callback_T ofu_cb; // 'omnifunc' callback function
2603static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2604# endif
2605
2606/*
2607 * Copy a global callback function to a buffer local callback.
2608 */
2609 static void
2610copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2611{
2612 free_callback(bufcb);
2613 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2614 copy_callback(bufcb, globcb);
2615}
2616
2617/*
2618 * Parse the 'completefunc' option value and set the callback function.
2619 * Invoked when the 'completefunc' option is set. The option value can be a
2620 * name of a function (string), or function(<name>) or funcref(<name>) or a
2621 * lambda expression.
2622 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002623 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002624did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002625{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002626 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2627 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002628
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002629 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002630
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002631 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002632}
2633
2634/*
2635 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002636 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002637 */
2638 void
2639set_buflocal_cfu_callback(buf_T *buf UNUSED)
2640{
2641# ifdef FEAT_EVAL
2642 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2643# endif
2644}
2645
2646/*
2647 * Parse the 'omnifunc' option value and set the callback function.
2648 * Invoked when the 'omnifunc' option is set. The option value can be a
2649 * name of a function (string), or function(<name>) or funcref(<name>) or a
2650 * lambda expression.
2651 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002652 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002653did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002654{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002655 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2656 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002657
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002658 set_buflocal_ofu_callback(curbuf);
2659 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002660}
2661
2662/*
2663 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002664 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002665 */
2666 void
2667set_buflocal_ofu_callback(buf_T *buf UNUSED)
2668{
2669# ifdef FEAT_EVAL
2670 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2671# endif
2672}
2673
2674/*
2675 * Parse the 'thesaurusfunc' option value and set the callback function.
2676 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2677 * name of a function (string), or function(<name>) or funcref(<name>) or a
2678 * lambda expression.
2679 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002680 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002681did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002682{
2683 int retval;
2684
2685 if (*curbuf->b_p_tsrfu != NUL)
2686 {
2687 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002688 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2689 &curbuf->b_tsrfu_cb);
2690 }
2691 else
2692 {
2693 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002694 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2695 }
2696
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002697 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002698}
2699
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002700/*
2701 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002702 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002703 */
2704 int
2705set_ref_in_insexpand_funcs(int copyID)
2706{
2707 int abort = FALSE;
2708
2709 abort = set_ref_in_callback(&cfu_cb, copyID);
2710 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2711 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2712
2713 return abort;
2714}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002715
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002716/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002717 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002718 */
2719 static char_u *
2720get_complete_funcname(int type)
2721{
2722 switch (type)
2723 {
2724 case CTRL_X_FUNCTION:
2725 return curbuf->b_p_cfu;
2726 case CTRL_X_OMNI:
2727 return curbuf->b_p_ofu;
2728 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002729 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002730 default:
2731 return (char_u *)"";
2732 }
2733}
2734
2735/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002736 * Get the callback to use for insert mode completion.
2737 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002738 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002739get_insert_callback(int type)
2740{
2741 if (type == CTRL_X_FUNCTION)
2742 return &curbuf->b_cfu_cb;
2743 if (type == CTRL_X_OMNI)
2744 return &curbuf->b_ofu_cb;
2745 // CTRL_X_THESAURUS
2746 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2747}
2748
2749/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002750 * Execute user defined complete function 'completefunc', 'omnifunc' or
2751 * 'thesaurusfunc', and get matches in "matches".
2752 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002753 */
2754 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002755expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002756{
2757 list_T *matchlist = NULL;
2758 dict_T *matchdict = NULL;
2759 typval_T args[3];
2760 char_u *funcname;
2761 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002762 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002763 typval_T rettv;
2764 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002765 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002766
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002767 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002768 if (*funcname == NUL)
2769 return;
2770
2771 // Call 'completefunc' to obtain the list of matches.
2772 args[0].v_type = VAR_NUMBER;
2773 args[0].vval.v_number = 0;
2774 args[1].v_type = VAR_STRING;
2775 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2776 args[2].v_type = VAR_UNKNOWN;
2777
2778 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002779 // Lock the text to avoid weird things from happening. Also disallow
2780 // switching to another window, it should not be needed and may end up in
2781 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002782 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002783
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002784 cb = get_insert_callback(type);
2785 retval = call_callback(cb, 0, &rettv, 2, args);
2786
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002787 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002788 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002789 {
2790 switch (rettv.v_type)
2791 {
2792 case VAR_LIST:
2793 matchlist = rettv.vval.v_list;
2794 break;
2795 case VAR_DICT:
2796 matchdict = rettv.vval.v_dict;
2797 break;
2798 case VAR_SPECIAL:
2799 if (rettv.vval.v_number == VVAL_NONE)
2800 compl_opt_suppress_empty = TRUE;
2801 // FALLTHROUGH
2802 default:
2803 // TODO: Give error message?
2804 clear_tv(&rettv);
2805 break;
2806 }
2807 }
zeertzjqcfe45652022-05-27 17:26:55 +01002808 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002809
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002810 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002811 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002812 validate_cursor();
2813 if (!EQUAL_POS(curwin->w_cursor, pos))
2814 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002815 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002816 goto theend;
2817 }
2818
2819 if (matchlist != NULL)
2820 ins_compl_add_list(matchlist);
2821 else if (matchdict != NULL)
2822 ins_compl_add_dict(matchdict);
2823
2824theend:
2825 // Restore State, it might have been changed.
2826 State = save_State;
2827
2828 if (matchdict != NULL)
2829 dict_unref(matchdict);
2830 if (matchlist != NULL)
2831 list_unref(matchlist);
2832}
2833#endif // FEAT_COMPL_FUNC
2834
2835#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2836/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002837 * Add a match to the list of matches from a typeval_T.
2838 * If the given string is already in the list of completions, then return
2839 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2840 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002841 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002842 */
2843 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002844ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002845{
2846 char_u *word;
2847 int dup = FALSE;
2848 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002849 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002850 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002851 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002852 int status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002853
Bram Moolenaar08928322020-01-04 14:32:48 +01002854 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002855 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2856 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002857 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2858 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2859 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2860 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2861 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
2862 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2863 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2864 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002865 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002866 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2867 dup = dict_get_number(tv->vval.v_dict, "dup");
2868 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2869 empty = dict_get_number(tv->vval.v_dict, "empty");
2870 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2871 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002872 flags |= CP_EQUAL;
2873 }
2874 else
2875 {
2876 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002877 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002878 }
2879 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002880 {
2881 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002882 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002883 }
2884 status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
2885 if (status != OK)
2886 clear_tv(&user_data);
2887 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002888}
2889
2890/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002891 * Add completions from a list.
2892 */
2893 static void
2894ins_compl_add_list(list_T *list)
2895{
2896 listitem_T *li;
2897 int dir = compl_direction;
2898
2899 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002900 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002901 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002902 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002903 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002904 // if dir was BACKWARD then honor it just once
2905 dir = FORWARD;
2906 else if (did_emsg)
2907 break;
2908 }
2909}
2910
2911/*
2912 * Add completions from a dict.
2913 */
2914 static void
2915ins_compl_add_dict(dict_T *dict)
2916{
2917 dictitem_T *di_refresh;
2918 dictitem_T *di_words;
2919
2920 // Check for optional "refresh" item.
2921 compl_opt_refresh_always = FALSE;
2922 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2923 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2924 {
2925 char_u *v = di_refresh->di_tv.vval.v_string;
2926
2927 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2928 compl_opt_refresh_always = TRUE;
2929 }
2930
2931 // Add completions from a "words" list.
2932 di_words = dict_find(dict, (char_u *)"words", 5);
2933 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2934 ins_compl_add_list(di_words->di_tv.vval.v_list);
2935}
2936
2937/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002938 * Start completion for the complete() function.
2939 * "startcol" is where the matched text starts (1 is first column).
2940 * "list" is the list of matches.
2941 */
2942 static void
2943set_completion(colnr_T startcol, list_T *list)
2944{
2945 int save_w_wrow = curwin->w_wrow;
2946 int save_w_leftcol = curwin->w_leftcol;
2947 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002948 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002949 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2950 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2951 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002952
2953 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002954 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002955 ins_compl_prep(' ');
2956 ins_compl_clear();
2957 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002958 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002959
2960 compl_direction = FORWARD;
2961 if (startcol > curwin->w_cursor.col)
2962 startcol = curwin->w_cursor.col;
2963 compl_col = startcol;
2964 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2965 // compl_pattern doesn't need to be set
2966 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2967 if (p_ic)
2968 flags |= CP_ICASE;
2969 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002970 -1, NULL, NULL, NULL, 0,
2971 flags | CP_FAST, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002972 return;
2973
2974 ctrl_x_mode = CTRL_X_EVAL;
2975
2976 ins_compl_add_list(list);
2977 compl_matches = ins_compl_make_cyclic();
2978 compl_started = TRUE;
2979 compl_used_match = TRUE;
2980 compl_cont_status = 0;
2981
2982 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01002983 int no_select = compl_no_select || compl_longest;
2984 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002985 {
2986 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01002987 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002988 // Down/Up has no real effect.
2989 ins_complete(K_UP, FALSE);
2990 }
2991 else
2992 ins_complete(Ctrl_N, FALSE);
2993 compl_enter_selects = compl_no_insert;
2994
2995 // Lazily show the popup menu, unless we got interrupted.
2996 if (!compl_interrupted)
2997 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01002998 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002999 out_flush();
3000}
3001
3002/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003003 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003004 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003005 void
3006f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003007{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003008 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003009
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003010 if (in_vim9script()
3011 && (check_for_number_arg(argvars, 0) == FAIL
3012 || check_for_list_arg(argvars, 1) == FAIL))
3013 return;
3014
Bram Moolenaar24959102022-05-07 20:01:16 +01003015 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003016 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003017 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003018 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003019 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003020
3021 // Check for undo allowed here, because if something was already inserted
3022 // the line was already saved for undo and this check isn't done.
3023 if (!undo_allowed())
3024 return;
3025
Bram Moolenaard83392a2022-09-01 12:22:46 +01003026 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003027 {
3028 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3029 if (startcol > 0)
3030 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003031 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003032}
3033
3034/*
3035 * "complete_add()" function
3036 */
3037 void
3038f_complete_add(typval_T *argvars, typval_T *rettv)
3039{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003040 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003041 return;
3042
Bram Moolenaar440cf092021-04-03 20:13:30 +02003043 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003044}
3045
3046/*
3047 * "complete_check()" function
3048 */
3049 void
3050f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3051{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003052 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003053 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003054
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003055 ins_compl_check_keys(0, TRUE);
3056 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003057
3058 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003059}
3060
3061/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003062 * Return Insert completion mode name string
3063 */
3064 static char_u *
3065ins_compl_mode(void)
3066{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003067 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003068 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3069
3070 return (char_u *)"";
3071}
3072
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003073/*
3074 * Assign the sequence number to all the completion matches which don't have
3075 * one assigned yet.
3076 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003077 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003078ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003079{
3080 int number = 0;
3081 compl_T *match;
3082
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003083 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003084 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003085 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003086 // This should normally succeed already at the first loop
3087 // cycle, so it's fast!
3088 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003089 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003090 if (match->cp_number != -1)
3091 {
3092 number = match->cp_number;
3093 break;
3094 }
3095 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003096 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003097 for (match = match->cp_next;
3098 match != NULL && match->cp_number == -1;
3099 match = match->cp_next)
3100 match->cp_number = ++number;
3101 }
3102 else // BACKWARD
3103 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003104 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003105 // number. This should normally succeed already at the
3106 // first loop cycle, so it's fast!
3107 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003108 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003109 if (match->cp_number != -1)
3110 {
3111 number = match->cp_number;
3112 break;
3113 }
3114 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003115 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003116 for (match = match->cp_prev; match
3117 && match->cp_number == -1;
3118 match = match->cp_prev)
3119 match->cp_number = ++number;
3120 }
3121}
3122
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003123/*
3124 * Get complete information
3125 */
3126 static void
3127get_complete_info(list_T *what_list, dict_T *retdict)
3128{
3129 int ret = OK;
3130 listitem_T *item;
3131#define CI_WHAT_MODE 0x01
3132#define CI_WHAT_PUM_VISIBLE 0x02
3133#define CI_WHAT_ITEMS 0x04
3134#define CI_WHAT_SELECTED 0x08
3135#define CI_WHAT_INSERTED 0x10
3136#define CI_WHAT_ALL 0xff
3137 int what_flag;
3138
3139 if (what_list == NULL)
3140 what_flag = CI_WHAT_ALL;
3141 else
3142 {
3143 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003144 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003145 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003146 {
3147 char_u *what = tv_get_string(&item->li_tv);
3148
3149 if (STRCMP(what, "mode") == 0)
3150 what_flag |= CI_WHAT_MODE;
3151 else if (STRCMP(what, "pum_visible") == 0)
3152 what_flag |= CI_WHAT_PUM_VISIBLE;
3153 else if (STRCMP(what, "items") == 0)
3154 what_flag |= CI_WHAT_ITEMS;
3155 else if (STRCMP(what, "selected") == 0)
3156 what_flag |= CI_WHAT_SELECTED;
3157 else if (STRCMP(what, "inserted") == 0)
3158 what_flag |= CI_WHAT_INSERTED;
3159 }
3160 }
3161
3162 if (ret == OK && (what_flag & CI_WHAT_MODE))
3163 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3164
3165 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3166 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3167
Girish Palya8950bf72024-03-20 20:07:29 +01003168 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003169 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003170 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003171 dict_T *di;
3172 compl_T *match;
3173 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003174
Girish Palya8950bf72024-03-20 20:07:29 +01003175 if (what_flag & CI_WHAT_ITEMS)
3176 {
3177 li = list_alloc();
3178 if (li == NULL)
3179 return;
3180 ret = dict_add_list(retdict, "items", li);
3181 }
3182 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3183 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3184 ins_compl_update_sequence_numbers();
3185 if (ret == OK && compl_first_match != NULL)
3186 {
3187 int list_idx = 0;
3188 match = compl_first_match;
3189 do
3190 {
3191 if (!match_at_original_text(match))
3192 {
3193 if (what_flag & CI_WHAT_ITEMS)
3194 {
3195 di = dict_alloc();
3196 if (di == NULL)
3197 return;
3198 ret = list_append_dict(li, di);
3199 if (ret != OK)
3200 return;
3201 dict_add_string(di, "word", match->cp_str);
3202 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3203 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3204 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3205 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3206 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3207 // Add an empty string for backwards compatibility
3208 dict_add_string(di, "user_data", (char_u *)"");
3209 else
3210 dict_add_tv(di, "user_data", &match->cp_user_data);
3211 }
3212 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3213 selected_idx = list_idx;
3214 list_idx += 1;
3215 }
3216 match = match->cp_next;
3217 }
3218 while (match != NULL && !is_first_match(match));
3219 }
3220 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3221 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003222 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003223
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003224 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3225 {
3226 // TODO
3227 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003228}
3229
3230/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003231 * "complete_info()" function
3232 */
3233 void
3234f_complete_info(typval_T *argvars, typval_T *rettv)
3235{
3236 list_T *what_list = NULL;
3237
Bram Moolenaar93a10962022-06-16 11:42:09 +01003238 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003239 return;
3240
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003241 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3242 return;
3243
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003244 if (argvars[0].v_type != VAR_UNKNOWN)
3245 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003246 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003247 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003248 what_list = argvars[0].vval.v_list;
3249 }
3250 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003251}
3252#endif
3253
3254/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003255 * Returns TRUE when using a user-defined function for thesaurus completion.
3256 */
3257 static int
3258thesaurus_func_complete(int type UNUSED)
3259{
3260#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003261 return type == CTRL_X_THESAURUS
3262 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003263#else
3264 return FALSE;
3265#endif
3266}
3267
3268/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003269 * Return value of process_next_cpt_value()
3270 */
3271enum
3272{
3273 INS_COMPL_CPT_OK = 1,
3274 INS_COMPL_CPT_CONT,
3275 INS_COMPL_CPT_END
3276};
3277
3278/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003279 * state information used for getting the next set of insert completion
3280 * matches.
3281 */
3282typedef struct
3283{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003284 char_u *e_cpt_copy; // copy of 'complete'
3285 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003286 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003287 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003288 pos_T prev_match_pos; // previous match position
3289 int set_match_pos; // save first_match_pos/last_match_pos
3290 pos_T first_match_pos; // first match position
3291 pos_T last_match_pos; // last match position
3292 int found_all; // found all matches of a certain type.
3293 char_u *dict; // dictionary file to search
3294 int dict_f; // "dict" is an exact file name or not
3295} ins_compl_next_state_T;
3296
3297/*
3298 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003299 *
3300 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003301 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003302 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003303 * st->found_all - all matches of this type are found
3304 * st->ins_buf - search for completions in this buffer
3305 * st->first_match_pos - position of the first completion match
3306 * st->last_match_pos - position of the last completion match
3307 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003308 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003309 * st->dict - name of the dictionary or thesaurus file to search
3310 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003311 *
3312 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003313 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3314 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003315 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003316 */
3317 static int
3318process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003319 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003320 int *compl_type_arg,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003321 pos_T *start_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003322{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003323 int compl_type = -1;
3324 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003325
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003326 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003327
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003328 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3329 st->e_cpt++;
3330
3331 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003332 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003333 st->ins_buf = curbuf;
3334 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003335 // Move the cursor back one character so that ^N can match the
3336 // word immediately after the cursor.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003337 if (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003338 {
3339 // Move the cursor to after the last character in the
3340 // buffer, so that word at start of buffer is found
3341 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003342 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003343 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003344 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003345 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003346 compl_type = 0;
3347
3348 // Remember the first match so that the loop stops when we
3349 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003350 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003351 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003352 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003353 && (st->ins_buf = ins_compl_next_buf(
3354 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003355 {
3356 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003357 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003358 {
3359 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003360 st->first_match_pos.col = st->last_match_pos.col = 0;
3361 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3362 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003363 compl_type = 0;
3364 }
3365 else // unloaded buffer, scan like dictionary
3366 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003367 st->found_all = TRUE;
3368 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003369 {
3370 status = INS_COMPL_CPT_CONT;
3371 goto done;
3372 }
3373 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003374 st->dict = st->ins_buf->b_fname;
3375 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003376 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003377 if (!shortmess(SHM_COMPLETIONSCAN))
3378 {
3379 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3380 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3381 st->ins_buf->b_fname == NULL
3382 ? buf_spname(st->ins_buf)
3383 : st->ins_buf->b_sfname == NULL
3384 ? st->ins_buf->b_fname
3385 : st->ins_buf->b_sfname);
3386 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3387 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003388 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003389 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003390 status = INS_COMPL_CPT_END;
3391 else
3392 {
3393 if (ctrl_x_mode_line_or_eval())
3394 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003395 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003396 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003397 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003398 compl_type = CTRL_X_DICTIONARY;
3399 else
3400 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003401 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003402 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003403 st->dict = st->e_cpt;
3404 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003405 }
3406 }
3407#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003408 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003409 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003410 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003411 compl_type = CTRL_X_PATH_DEFINES;
3412#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003413 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003414 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003415 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003416 if (!shortmess(SHM_COMPLETIONSCAN))
3417 {
3418 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3419 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3420 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3421 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003422 }
3423 else
3424 compl_type = -1;
3425
3426 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003427 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003428
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003429 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003430 if (compl_type == -1)
3431 status = INS_COMPL_CPT_CONT;
3432 }
3433
3434done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003435 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003436 return status;
3437}
3438
3439#ifdef FEAT_FIND_ID
3440/*
3441 * Get the next set of identifiers or defines matching "compl_pattern" in
3442 * included files.
3443 */
3444 static void
3445get_next_include_file_completion(int compl_type)
3446{
3447 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003448 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003449 (compl_type == CTRL_X_PATH_DEFINES
3450 && !(compl_cont_status & CONT_SOL))
3451 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003452 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003453}
3454#endif
3455
3456/*
3457 * Get the next set of words matching "compl_pattern" in dictionary or
3458 * thesaurus files.
3459 */
3460 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003461get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003462{
3463#ifdef FEAT_COMPL_FUNC
3464 if (thesaurus_func_complete(compl_type))
3465 expand_by_function(compl_type, compl_pattern);
3466 else
3467#endif
3468 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003469 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003470 : (compl_type == CTRL_X_THESAURUS
3471 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3472 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3473 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003474 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003475 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003476}
3477
3478/*
3479 * Get the next set of tag names matching "compl_pattern".
3480 */
3481 static void
3482get_next_tag_completion(void)
3483{
3484 int save_p_ic;
3485 char_u **matches;
3486 int num_matches;
3487
3488 // set p_ic according to p_ic, p_scs and pat for find_tags().
3489 save_p_ic = p_ic;
3490 p_ic = ignorecase(compl_pattern);
3491
3492 // Find up to TAG_MANY matches. Avoids that an enormous number
3493 // of matches is found when compl_pattern is empty
3494 g_tag_at_cursor = TRUE;
3495 if (find_tags(compl_pattern, &num_matches, &matches,
3496 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003497 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003498 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3499 ins_compl_add_matches(num_matches, matches, p_ic);
3500 g_tag_at_cursor = FALSE;
3501 p_ic = save_p_ic;
3502}
3503
3504/*
3505 * Get the next set of filename matching "compl_pattern".
3506 */
3507 static void
3508get_next_filename_completion(void)
3509{
3510 char_u **matches;
3511 int num_matches;
3512
3513 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3514 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3515 return;
3516
3517 // May change home directory back to "~".
3518 tilde_replace(compl_pattern, num_matches, matches);
3519#ifdef BACKSLASH_IN_FILENAME
3520 if (curbuf->b_p_csl[0] != NUL)
3521 {
3522 int i;
3523
3524 for (i = 0; i < num_matches; ++i)
3525 {
3526 char_u *ptr = matches[i];
3527
3528 while (*ptr != NUL)
3529 {
3530 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3531 *ptr = '/';
3532 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3533 *ptr = '\\';
3534 ptr += (*mb_ptr2len)(ptr);
3535 }
3536 }
3537 }
3538#endif
3539 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
3540}
3541
3542/*
3543 * Get the next set of command-line completions matching "compl_pattern".
3544 */
3545 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003546get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003547{
3548 char_u **matches;
3549 int num_matches;
3550
3551 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003552 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003553 ins_compl_add_matches(num_matches, matches, FALSE);
3554}
3555
3556/*
3557 * Get the next set of spell suggestions matching "compl_pattern".
3558 */
3559 static void
3560get_next_spell_completion(linenr_T lnum UNUSED)
3561{
3562#ifdef FEAT_SPELL
3563 char_u **matches;
3564 int num_matches;
3565
3566 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3567 if (num_matches > 0)
3568 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003569 else
3570 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003571#endif
3572}
3573
3574/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003575 * Return the next word or line from buffer "ins_buf" at position
3576 * "cur_match_pos" for completion. The length of the match is set in "len".
3577 */
3578 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003579ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003580 buf_T *ins_buf, // buffer being scanned
3581 pos_T *cur_match_pos, // current match position
3582 int *match_len,
3583 int *cont_s_ipos) // next ^X<> will set initial_pos
3584{
3585 char_u *ptr;
3586 int len;
3587
3588 *match_len = 0;
3589 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3590 cur_match_pos->col;
3591 if (ctrl_x_mode_line_or_eval())
3592 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003593 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003594 {
3595 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3596 return NULL;
3597 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3598 if (!p_paste)
3599 ptr = skipwhite(ptr);
3600 }
3601 len = (int)STRLEN(ptr);
3602 }
3603 else
3604 {
3605 char_u *tmp_ptr = ptr;
3606
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003607 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003608 {
3609 tmp_ptr += compl_length;
3610 // Skip if already inside a word.
3611 if (vim_iswordp(tmp_ptr))
3612 return NULL;
3613 // Find start of next word.
3614 tmp_ptr = find_word_start(tmp_ptr);
3615 }
3616 // Find end of this word.
3617 tmp_ptr = find_word_end(tmp_ptr);
3618 len = (int)(tmp_ptr - ptr);
3619
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003620 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003621 {
3622 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3623 {
3624 // Try next line, if any. the new word will be
3625 // "join" as if the normal command "J" was used.
3626 // IOSIZE is always greater than
3627 // compl_length, so the next STRNCPY always
3628 // works -- Acevedo
3629 STRNCPY(IObuff, ptr, len);
3630 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3631 tmp_ptr = ptr = skipwhite(ptr);
3632 // Find start of next word.
3633 tmp_ptr = find_word_start(tmp_ptr);
3634 // Find end of next word.
3635 tmp_ptr = find_word_end(tmp_ptr);
3636 if (tmp_ptr > ptr)
3637 {
3638 if (*ptr != ')' && IObuff[len - 1] != TAB)
3639 {
3640 if (IObuff[len - 1] != ' ')
3641 IObuff[len++] = ' ';
3642 // IObuf =~ "\k.* ", thus len >= 2
3643 if (p_js
3644 && (IObuff[len - 2] == '.'
3645 || (vim_strchr(p_cpo, CPO_JOINSP)
3646 == NULL
3647 && (IObuff[len - 2] == '?'
3648 || IObuff[len - 2] == '!'))))
3649 IObuff[len++] = ' ';
3650 }
3651 // copy as much as possible of the new word
3652 if (tmp_ptr - ptr >= IOSIZE - len)
3653 tmp_ptr = ptr + IOSIZE - len - 1;
3654 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3655 len += (int)(tmp_ptr - ptr);
3656 *cont_s_ipos = TRUE;
3657 }
3658 IObuff[len] = NUL;
3659 ptr = IObuff;
3660 }
3661 if (len == compl_length)
3662 return NULL;
3663 }
3664 }
3665
3666 *match_len = len;
3667 return ptr;
3668}
3669
3670/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003671 * Get the next set of words matching "compl_pattern" for default completion(s)
3672 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003673 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3674 * position "st->start_pos" in the "compl_direction" direction. If
3675 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3676 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003677 * Returns OK if a new next match is found, otherwise returns FAIL.
3678 */
3679 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003680get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003681{
3682 int found_new_match = FAIL;
3683 int save_p_scs;
3684 int save_p_ws;
3685 int looped_around = FALSE;
3686 char_u *ptr;
3687 int len;
3688
3689 // If 'infercase' is set, don't use 'smartcase' here
3690 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003691 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003692 p_scs = FALSE;
3693
3694 // Buffers other than curbuf are scanned from the beginning or the
3695 // end but never from the middle, thus setting nowrapscan in this
3696 // buffer is a good idea, on the other hand, we always set
3697 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3698 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003699 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003700 p_ws = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003701 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003702 p_ws = TRUE;
3703 looped_around = FALSE;
3704 for (;;)
3705 {
3706 int cont_s_ipos = FALSE;
3707
3708 ++msg_silent; // Don't want messages for wrapscan.
3709
3710 // ctrl_x_mode_line_or_eval() || word-wise search that
3711 // has added a word that was at the beginning of the line
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003712 if (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003713 found_new_match = search_for_exact_line(st->ins_buf,
3714 st->cur_match_pos, compl_direction, compl_pattern);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003715 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003716 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003717 NULL, compl_direction, compl_pattern, compl_patternlen,
3718 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003719 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003720 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003721 {
3722 // set "compl_started" even on fail
3723 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003724 st->first_match_pos = *st->cur_match_pos;
3725 st->last_match_pos = *st->cur_match_pos;
3726 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003727 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003728 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3729 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003730 {
3731 found_new_match = FAIL;
3732 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003733 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003734 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3735 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3736 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003737 {
3738 if (looped_around)
3739 found_new_match = FAIL;
3740 else
3741 looped_around = TRUE;
3742 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003743 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003744 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3745 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3746 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003747 {
3748 if (looped_around)
3749 found_new_match = FAIL;
3750 else
3751 looped_around = TRUE;
3752 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003753 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003754 if (found_new_match == FAIL)
3755 break;
3756
3757 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003758 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003759 && start_pos->lnum == st->cur_match_pos->lnum
3760 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003761 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003762
zeertzjq440d4cb2023-03-02 17:51:32 +00003763 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3764 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003765 if (ptr == NULL)
3766 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003767
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003768 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003769 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003770 0, cont_s_ipos) != NOTDONE)
3771 {
3772 found_new_match = OK;
3773 break;
3774 }
3775 }
3776 p_scs = save_p_scs;
3777 p_ws = save_p_ws;
3778
3779 return found_new_match;
3780}
3781
3782/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003783 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003784 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003785 */
3786 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003787get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003788{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003789 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003790
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003791 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003792 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003793 case -1:
3794 break;
3795#ifdef FEAT_FIND_ID
3796 case CTRL_X_PATH_PATTERNS:
3797 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003798 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003799 break;
3800#endif
3801
3802 case CTRL_X_DICTIONARY:
3803 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003804 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3805 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003806 break;
3807
3808 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003809 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003810 break;
3811
3812 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003813 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003814 break;
3815
3816 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003817 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003818 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003819 break;
3820
3821#ifdef FEAT_COMPL_FUNC
3822 case CTRL_X_FUNCTION:
3823 case CTRL_X_OMNI:
3824 expand_by_function(type, compl_pattern);
3825 break;
3826#endif
3827
3828 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003829 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003830 break;
3831
3832 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003833 found_new_match = get_next_default_completion(st, ini);
3834 if (found_new_match == FAIL && st->ins_buf == curbuf)
3835 st->found_all = TRUE;
3836 }
3837
3838 // check if compl_curr_match has changed, (e.g. other type of
3839 // expansion added something)
3840 if (type != 0 && compl_curr_match != compl_old_match)
3841 found_new_match = OK;
3842
3843 return found_new_match;
3844}
3845
3846/*
3847 * Get the next expansion(s), using "compl_pattern".
3848 * The search starts at position "ini" in curbuf and in the direction
3849 * compl_direction.
3850 * When "compl_started" is FALSE start at that position, otherwise continue
3851 * where we stopped searching before.
3852 * This may return before finding all the matches.
3853 * Return the total number of matches or -1 if still unknown -- Acevedo
3854 */
3855 static int
3856ins_compl_get_exp(pos_T *ini)
3857{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003858 static ins_compl_next_state_T st;
3859 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003860 int i;
3861 int found_new_match;
3862 int type = ctrl_x_mode;
3863
3864 if (!compl_started)
3865 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003866 buf_T *buf;
3867
3868 FOR_ALL_BUFFERS(buf)
3869 buf->b_scanned = 0;
3870 if (!st_cleared)
3871 {
3872 CLEAR_FIELD(st);
3873 st_cleared = TRUE;
3874 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003875 st.found_all = FALSE;
3876 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003877 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003878 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003879 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
3880 ? (char_u *)"." : curbuf->b_p_cpt);
3881 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003882 st.last_match_pos = st.first_match_pos = *ini;
3883 }
3884 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
3885 st.ins_buf = curbuf; // In case the buffer was wiped out.
3886
3887 compl_old_match = compl_curr_match; // remember the last current match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003888 st.cur_match_pos = (compl_dir_forward())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003889 ? &st.last_match_pos : &st.first_match_pos;
3890
3891 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
3892 for (;;)
3893 {
3894 found_new_match = FAIL;
3895 st.set_match_pos = FALSE;
3896
3897 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
3898 // or if found_all says this entry is done. For ^X^L only use the
3899 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003900 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003901 && (!compl_started || st.found_all))
3902 {
3903 int status = process_next_cpt_value(&st, &type, ini);
3904
3905 if (status == INS_COMPL_CPT_END)
3906 break;
3907 if (status == INS_COMPL_CPT_CONT)
3908 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003909 }
3910
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003911 // If complete() was called then compl_pattern has been reset. The
3912 // following won't work then, bail out.
3913 if (compl_pattern == NULL)
3914 break;
3915
3916 // get the next set of completion matches
3917 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003918
3919 // break the loop for specialized modes (use 'complete' just for the
3920 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3921 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003922 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
3923 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003924 {
3925 if (got_int)
3926 break;
3927 // Fill the popup menu as soon as possible.
3928 if (type != -1)
3929 ins_compl_check_keys(0, FALSE);
3930
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003931 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003932 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3933 break;
3934 compl_started = TRUE;
3935 }
3936 else
3937 {
3938 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02003939 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003940 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003941
3942 compl_started = FALSE;
3943 }
3944 }
3945 compl_started = TRUE;
3946
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003947 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003948 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003949 found_new_match = FAIL;
3950
3951 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003952 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003953 && !ctrl_x_mode_line_or_eval()))
3954 i = ins_compl_make_cyclic();
3955
3956 if (compl_old_match != NULL)
3957 {
3958 // If several matches were added (FORWARD) or the search failed and has
3959 // just been made cyclic then we have to move compl_curr_match to the
3960 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003961 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003962 : compl_old_match->cp_prev;
3963 if (compl_curr_match == NULL)
3964 compl_curr_match = compl_old_match;
3965 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01003966 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003967
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003968 return i;
3969}
3970
3971/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003972 * Update "compl_shown_match" to the actually shown match, it may differ when
3973 * "compl_leader" is used to omit some of the matches.
3974 */
3975 static void
3976ins_compl_update_shown_match(void)
3977{
3978 while (!ins_compl_equal(compl_shown_match,
3979 compl_leader, (int)STRLEN(compl_leader))
3980 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003981 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003982 compl_shown_match = compl_shown_match->cp_next;
3983
3984 // If we didn't find it searching forward, and compl_shows_dir is
3985 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003986 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003987 && !ins_compl_equal(compl_shown_match,
3988 compl_leader, (int)STRLEN(compl_leader))
3989 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003990 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003991 {
3992 while (!ins_compl_equal(compl_shown_match,
3993 compl_leader, (int)STRLEN(compl_leader))
3994 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003995 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003996 compl_shown_match = compl_shown_match->cp_prev;
3997 }
3998}
3999
4000/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004001 * Delete the old text being completed.
4002 */
4003 void
4004ins_compl_delete(void)
4005{
4006 int col;
4007
4008 // In insert mode: Delete the typed part.
4009 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004010 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004011 if ((int)curwin->w_cursor.col > col)
4012 {
4013 if (stop_arrow() == FAIL)
4014 return;
4015 backspace_until_column(col);
4016 }
4017
4018 // TODO: is this sufficient for redrawing? Redrawing everything causes
4019 // flicker, thus we can't do that.
4020 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004021#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004022 // clear v:completed_item
4023 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004024#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004025}
4026
4027/*
4028 * Insert the new text being completed.
4029 * "in_compl_func" is TRUE when called from complete_check().
4030 */
4031 void
4032ins_compl_insert(int in_compl_func)
4033{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004034 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004035
4036 // Make sure we don't go over the end of the string, this can happen with
4037 // illegal bytes.
4038 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4039 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004040 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004041 compl_used_match = FALSE;
4042 else
4043 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004044#ifdef FEAT_EVAL
4045 {
4046 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4047
4048 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4049 }
4050#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004051 if (!in_compl_func)
4052 compl_curr_match = compl_shown_match;
4053}
4054
4055/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004056 * show the file name for the completion match (if any). Truncate the file
4057 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004058 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004059 static void
4060ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004061{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004062 char *lead = _("match in file");
4063 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4064 char_u *s;
4065 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004066
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004067 if (space <= 0)
4068 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004069
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004070 // We need the tail that fits. With double-byte encoding going
4071 // back from the end is very slow, thus go from the start and keep
4072 // the text that fits in "space" between "s" and "e".
4073 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004074 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004075 space -= ptr2cells(e);
4076 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004077 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004078 space += ptr2cells(s);
4079 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004080 }
4081 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004082 msg_hist_off = TRUE;
4083 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4084 s > compl_shown_match->cp_fname ? "<" : "", s);
4085 msg((char *)IObuff);
4086 msg_hist_off = FALSE;
4087 redraw_cmdline = FALSE; // don't overwrite!
4088}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004089
glepnirdca57fb2024-06-04 22:01:21 +02004090/*
zeertzjq551d8c32024-06-05 19:53:32 +02004091 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004092 */
glepnira218cc62024-06-03 19:32:39 +02004093 static compl_T *
4094find_comp_when_fuzzy(void)
4095{
4096 int score;
4097 char_u* str;
4098 int target_idx = -1;
4099 int is_forward = compl_shows_dir_forward();
4100 int is_backward = compl_shows_dir_backward();
4101 compl_T *comp = NULL;
4102
4103 if (compl_match_array == NULL ||
4104 (is_forward && compl_selected_item == compl_match_arraysize - 1)
4105 || (is_backward && compl_selected_item == 0))
4106 return compl_first_match;
4107
4108 if (is_forward)
4109 target_idx = compl_selected_item + 1;
4110 else if (is_backward)
4111 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004112 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004113
4114 score = compl_match_array[target_idx].pum_score;
4115 str = compl_match_array[target_idx].pum_text;
4116
4117 comp = compl_first_match;
4118 do {
4119 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4120 return comp;
4121 comp = comp->cp_next;
4122 } while (comp != NULL && !is_first_match(comp));
4123
4124 return NULL;
4125}
4126
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004127/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004128 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004129 * times. The number of matches found is returned in 'num_matches'.
4130 *
4131 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4132 * get more completions. If it is FALSE, then do nothing when there are no more
4133 * completions in the given direction.
4134 *
4135 * If "advance" is TRUE, then completion will move to the first match.
4136 * Otherwise, the original text will be shown.
4137 *
4138 * Returns OK on success and -1 if the number of matches are unknown.
4139 */
4140 static int
4141find_next_completion_match(
4142 int allow_get_expansion,
4143 int todo, // repeat completion this many times
4144 int advance,
4145 int *num_matches)
4146{
4147 int found_end = FALSE;
4148 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004149 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004150 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4151 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004152
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004153 while (--todo >= 0)
4154 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004155 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004156 {
glepniraced8c22024-06-15 15:13:05 +02004157 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4158 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004159 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004160 && (is_first_match(compl_shown_match->cp_next)
4161 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004162 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004163 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004164 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004165 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004166 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004167 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4168 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004169 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004170 }
4171 else
4172 {
4173 if (!allow_get_expansion)
4174 {
4175 if (advance)
4176 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004177 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004178 compl_pending -= todo + 1;
4179 else
4180 compl_pending += todo + 1;
4181 }
4182 return -1;
4183 }
4184
4185 if (!compl_no_select && advance)
4186 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004187 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004188 --compl_pending;
4189 else
4190 ++compl_pending;
4191 }
4192
4193 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004194 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004195
4196 // handle any pending completions
4197 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004198 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004199 {
4200 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4201 {
4202 compl_shown_match = compl_shown_match->cp_next;
4203 --compl_pending;
4204 }
4205 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4206 {
4207 compl_shown_match = compl_shown_match->cp_prev;
4208 ++compl_pending;
4209 }
4210 else
4211 break;
4212 }
4213 found_end = FALSE;
4214 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004215 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004216 && compl_leader != NULL
4217 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004218 compl_leader, (int)STRLEN(compl_leader))
4219 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004220 ++todo;
4221 else
4222 // Remember a matching item.
4223 found_compl = compl_shown_match;
4224
4225 // Stop at the end of the list when we found a usable match.
4226 if (found_end)
4227 {
4228 if (found_compl != NULL)
4229 {
4230 compl_shown_match = found_compl;
4231 break;
4232 }
4233 todo = 1; // use first usable match after wrapping around
4234 }
4235 }
4236
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004237 return OK;
4238}
4239
4240/*
4241 * Fill in the next completion in the current direction.
4242 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4243 * get more completions. If it is FALSE, then we just do nothing when there
4244 * are no more completions in a given direction. The latter case is used when
4245 * we are still in the middle of finding completions, to allow browsing
4246 * through the ones found so far.
4247 * Return the total number of matches, or -1 if still unknown -- webb.
4248 *
4249 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4250 * compl_shown_match here.
4251 *
4252 * Note that this function may be called recursively once only. First with
4253 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4254 * calls this function with "allow_get_expansion" FALSE.
4255 */
4256 static int
4257ins_compl_next(
4258 int allow_get_expansion,
4259 int count, // repeat completion this many times; should
4260 // be at least 1
4261 int insert_match, // Insert the newly selected match
4262 int in_compl_func) // called from complete_check()
4263{
4264 int num_matches = -1;
4265 int todo = count;
4266 int advance;
4267 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004268 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004269 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004270 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4271 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004272
4273 // When user complete function return -1 for findstart which is next
4274 // time of 'always', compl_shown_match become NULL.
4275 if (compl_shown_match == NULL)
4276 return -1;
4277
glepnira218cc62024-06-03 19:32:39 +02004278 if (compl_leader != NULL
4279 && !match_at_original_text(compl_shown_match)
4280 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004281 // Update "compl_shown_match" to the actually shown match
4282 ins_compl_update_shown_match();
4283
4284 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004285 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004286 // Delete old text to be replaced
4287 ins_compl_delete();
4288
4289 // When finding the longest common text we stick at the original text,
4290 // don't let CTRL-N or CTRL-P move to the first match.
4291 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4292
4293 // When restarting the search don't insert the first match either.
4294 if (compl_restarting)
4295 {
4296 advance = FALSE;
4297 compl_restarting = FALSE;
4298 }
4299
4300 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4301 // around.
4302 if (find_next_completion_match(allow_get_expansion, todo, advance,
4303 &num_matches) == -1)
4304 return -1;
4305
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004306 if (curbuf != orig_curbuf)
4307 {
4308 // In case some completion function switched buffer, don't want to
4309 // insert the completion elsewhere.
4310 return -1;
4311 }
4312
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004313 // Insert the text of the new completion, or the compl_leader.
4314 if (compl_no_insert && !started)
4315 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004316 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004317 compl_used_match = FALSE;
4318 }
4319 else if (insert_match)
4320 {
4321 if (!compl_get_longest || compl_used_match)
4322 ins_compl_insert(in_compl_func);
4323 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004324 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004325 }
4326 else
4327 compl_used_match = FALSE;
4328
4329 if (!allow_get_expansion)
4330 {
4331 // may undisplay the popup menu first
4332 ins_compl_upd_pum();
4333
4334 if (pum_enough_matches())
4335 // Will display the popup menu, don't redraw yet to avoid flicker.
4336 pum_call_update_screen();
4337 else
4338 // Not showing the popup menu yet, redraw to show the user what was
4339 // inserted.
4340 update_screen(0);
4341
4342 // display the updated popup menu
4343 ins_compl_show_pum();
4344#ifdef FEAT_GUI
4345 if (gui.in_use)
4346 {
4347 // Show the cursor after the match, not after the redrawn text.
4348 setcursor();
4349 out_flush_cursor(FALSE, FALSE);
4350 }
4351#endif
4352
4353 // Delete old text to be replaced, since we're still searching and
4354 // don't want to match ourselves!
4355 ins_compl_delete();
4356 }
4357
4358 // Enter will select a match when the match wasn't inserted and the popup
4359 // menu is visible.
4360 if (compl_no_insert && !started)
4361 compl_enter_selects = TRUE;
4362 else
4363 compl_enter_selects = !insert_match && compl_match_array != NULL;
4364
4365 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004366 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004367 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004368
4369 return num_matches;
4370}
4371
4372/*
4373 * Call this while finding completions, to check whether the user has hit a key
4374 * that should change the currently displayed completion, or exit completion
4375 * mode. Also, when compl_pending is not zero, show a completion as soon as
4376 * possible. -- webb
4377 * "frequency" specifies out of how many calls we actually check.
4378 * "in_compl_func" is TRUE when called from complete_check(), don't set
4379 * compl_curr_match.
4380 */
4381 void
4382ins_compl_check_keys(int frequency, int in_compl_func)
4383{
4384 static int count = 0;
4385 int c;
4386
4387 // Don't check when reading keys from a script, :normal or feedkeys().
4388 // That would break the test scripts. But do check for keys when called
4389 // from complete_check().
4390 if (!in_compl_func && (using_script() || ex_normal_busy))
4391 return;
4392
4393 // Only do this at regular intervals
4394 if (++count < frequency)
4395 return;
4396 count = 0;
4397
4398 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4399 // can't do its work correctly.
4400 c = vpeekc_any();
4401 if (c != NUL)
4402 {
4403 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4404 {
4405 c = safe_vgetc(); // Eat the character
4406 compl_shows_dir = ins_compl_key2dir(c);
4407 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4408 c != K_UP && c != K_DOWN, in_compl_func);
4409 }
4410 else
4411 {
4412 // Need to get the character to have KeyTyped set. We'll put it
4413 // back with vungetc() below. But skip K_IGNORE.
4414 c = safe_vgetc();
4415 if (c != K_IGNORE)
4416 {
4417 // Don't interrupt completion when the character wasn't typed,
4418 // e.g., when doing @q to replay keys.
4419 if (c != Ctrl_R && KeyTyped)
4420 compl_interrupted = TRUE;
4421
4422 vungetc(c);
4423 }
4424 }
4425 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004426 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004427 {
4428 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4429
4430 compl_pending = 0;
4431 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4432 }
4433}
4434
4435/*
4436 * Decide the direction of Insert mode complete from the key typed.
4437 * Returns BACKWARD or FORWARD.
4438 */
4439 static int
4440ins_compl_key2dir(int c)
4441{
4442 if (c == Ctrl_P || c == Ctrl_L
4443 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4444 return BACKWARD;
4445 return FORWARD;
4446}
4447
4448/*
4449 * Return TRUE for keys that are used for completion only when the popup menu
4450 * is visible.
4451 */
4452 static int
4453ins_compl_pum_key(int c)
4454{
4455 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4456 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4457 || c == K_UP || c == K_DOWN);
4458}
4459
4460/*
4461 * Decide the number of completions to move forward.
4462 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4463 */
4464 static int
4465ins_compl_key2count(int c)
4466{
4467 int h;
4468
4469 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4470 {
4471 h = pum_get_height();
4472 if (h > 3)
4473 h -= 2; // keep some context
4474 return h;
4475 }
4476 return 1;
4477}
4478
4479/*
4480 * Return TRUE if completion with "c" should insert the match, FALSE if only
4481 * to change the currently selected completion.
4482 */
4483 static int
4484ins_compl_use_match(int c)
4485{
4486 switch (c)
4487 {
4488 case K_UP:
4489 case K_DOWN:
4490 case K_PAGEDOWN:
4491 case K_KPAGEDOWN:
4492 case K_S_DOWN:
4493 case K_PAGEUP:
4494 case K_KPAGEUP:
4495 case K_S_UP:
4496 return FALSE;
4497 }
4498 return TRUE;
4499}
4500
4501/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004502 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4503 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004504 * Sets the global variables: compl_col, compl_length, compl_pattern and
4505 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004506 * Uses the global variables: compl_cont_status and ctrl_x_mode
4507 */
4508 static int
4509get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4510{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004511 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004512 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004513 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004514 {
4515 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4516 ;
4517 compl_col += ++startcol;
4518 compl_length = curs_col - startcol;
4519 }
4520 if (p_ic)
4521 compl_pattern = str_foldcase(line + compl_col,
4522 compl_length, NULL, 0);
4523 else
4524 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4525 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004526 {
4527 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004528 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004529 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004530 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004531 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004532 {
4533 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004534 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004535
4536 // we need up to 2 extra chars for the prefix
4537 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004538 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004539 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004540 {
4541 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004542 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004543 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004544 if (!vim_iswordp(line + compl_col)
4545 || (compl_col > 0
4546 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004547 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004548 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004549 prefixlen = 0;
4550 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004551 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004552 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004553 line + compl_col, compl_length);
4554 }
4555 else if (--startcol < 0
4556 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4557 {
4558 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004559 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004560 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004561 {
4562 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004563 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004564 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004565 compl_col += curs_col;
4566 compl_length = 0;
4567 }
4568 else
4569 {
4570 // Search the point of change class of multibyte character
4571 // or not a word single byte character backward.
4572 if (has_mbyte)
4573 {
4574 int base_class;
4575 int head_off;
4576
4577 startcol -= (*mb_head_off)(line, line + startcol);
4578 base_class = mb_get_class(line + startcol);
4579 while (--startcol >= 0)
4580 {
4581 head_off = (*mb_head_off)(line, line + startcol);
4582 if (base_class != mb_get_class(line + startcol
4583 - head_off))
4584 break;
4585 startcol -= head_off;
4586 }
4587 }
4588 else
4589 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4590 ;
4591 compl_col += ++startcol;
4592 compl_length = (int)curs_col - startcol;
4593 if (compl_length == 1)
4594 {
4595 // Only match word with at least two chars -- webb
4596 // there's no need to call quote_meta,
4597 // alloc(7) is enough -- Acevedo
4598 compl_pattern = alloc(7);
4599 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004600 {
4601 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004602 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004603 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004604 STRCPY((char *)compl_pattern, "\\<");
4605 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4606 STRCAT((char *)compl_pattern, "\\k");
4607 }
4608 else
4609 {
4610 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4611 compl_length) + 2);
4612 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004613 {
4614 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004615 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004616 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004617 STRCPY((char *)compl_pattern, "\\<");
4618 (void)quote_meta(compl_pattern + 2, line + compl_col,
4619 compl_length);
4620 }
4621 }
4622
John Marriott8c85a2a2024-05-20 19:18:26 +02004623 compl_patternlen = STRLEN(compl_pattern);
4624
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004625 return OK;
4626}
4627
4628/*
4629 * Get the pattern, column and length for whole line completion or for the
4630 * complete() function.
4631 * Sets the global variables: compl_col, compl_length and compl_pattern.
4632 */
4633 static int
4634get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4635{
4636 compl_col = (colnr_T)getwhitecols(line);
4637 compl_length = (int)curs_col - (int)compl_col;
4638 if (compl_length < 0) // cursor in indent: empty pattern
4639 compl_length = 0;
4640 if (p_ic)
4641 compl_pattern = str_foldcase(line + compl_col, compl_length,
4642 NULL, 0);
4643 else
4644 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4645 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004646 {
4647 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004648 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004649 }
4650
4651 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004652
4653 return OK;
4654}
4655
4656/*
4657 * Get the pattern, column and length for filename completion.
4658 * Sets the global variables: compl_col, compl_length and compl_pattern.
4659 */
4660 static int
4661get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4662{
4663 // Go back to just before the first filename character.
4664 if (startcol > 0)
4665 {
4666 char_u *p = line + startcol;
4667
4668 MB_PTR_BACK(line, p);
4669 while (p > line && vim_isfilec(PTR2CHAR(p)))
4670 MB_PTR_BACK(line, p);
4671 if (p == line && vim_isfilec(PTR2CHAR(p)))
4672 startcol = 0;
4673 else
4674 startcol = (int)(p - line) + 1;
4675 }
4676
4677 compl_col += startcol;
4678 compl_length = (int)curs_col - startcol;
4679 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4680 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004681 {
4682 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004683 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004684 }
4685
4686 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004687
4688 return OK;
4689}
4690
4691/*
4692 * Get the pattern, column and length for command-line completion.
4693 * Sets the global variables: compl_col, compl_length and compl_pattern.
4694 */
4695 static int
4696get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4697{
4698 compl_pattern = vim_strnsave(line, curs_col);
4699 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004700 {
4701 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004702 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004703 }
4704 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004705 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004706 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004707 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4708 || compl_xp.xp_context == EXPAND_NOTHING)
4709 // No completion possible, use an empty pattern to get a
4710 // "pattern not found" message.
4711 compl_col = curs_col;
4712 else
4713 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4714 compl_length = curs_col - compl_col;
4715
4716 return OK;
4717}
4718
4719/*
4720 * Get the pattern, column and length for user defined completion ('omnifunc',
4721 * 'completefunc' and 'thesaurusfunc')
4722 * Sets the global variables: compl_col, compl_length and compl_pattern.
4723 * Uses the global variable: spell_bad_len
4724 */
4725 static int
4726get_userdefined_compl_info(colnr_T curs_col UNUSED)
4727{
4728 int ret = FAIL;
4729
4730#ifdef FEAT_COMPL_FUNC
4731 // Call user defined function 'completefunc' with "a:findstart"
4732 // set to 1 to obtain the length of text to use for completion.
4733 char_u *line;
4734 typval_T args[3];
4735 int col;
4736 char_u *funcname;
4737 pos_T pos;
4738 int save_State = State;
4739 callback_T *cb;
4740
4741 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4742 // length as a string
4743 funcname = get_complete_funcname(ctrl_x_mode);
4744 if (*funcname == NUL)
4745 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004746 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004747 ? "completefunc" : "omnifunc");
4748 return FAIL;
4749 }
4750
4751 args[0].v_type = VAR_NUMBER;
4752 args[0].vval.v_number = 1;
4753 args[1].v_type = VAR_STRING;
4754 args[1].vval.v_string = (char_u *)"";
4755 args[2].v_type = VAR_UNKNOWN;
4756 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004757 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004758 cb = get_insert_callback(ctrl_x_mode);
4759 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004760 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004761
4762 State = save_State;
4763 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004764 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004765 validate_cursor();
4766 if (!EQUAL_POS(curwin->w_cursor, pos))
4767 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004768 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004769 return FAIL;
4770 }
4771
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004772 // Return value -2 means the user complete function wants to cancel the
4773 // complete without an error, do the same if the function did not execute
4774 // successfully.
4775 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004776 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004777 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004778 if (col == -3)
4779 {
4780 ctrl_x_mode = CTRL_X_NORMAL;
4781 edit_submode = NULL;
4782 if (!shortmess(SHM_COMPLETIONMENU))
4783 msg_clr_cmdline();
4784 return FAIL;
4785 }
4786
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004787 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004788 // completion.
4789 compl_opt_refresh_always = FALSE;
4790 compl_opt_suppress_empty = FALSE;
4791
4792 if (col < 0)
4793 col = curs_col;
4794 compl_col = col;
4795 if (compl_col > curs_col)
4796 compl_col = curs_col;
4797
4798 // Setup variables for completion. Need to obtain "line" again,
4799 // it may have become invalid.
4800 line = ml_get(curwin->w_cursor.lnum);
4801 compl_length = curs_col - compl_col;
4802 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4803 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004804 {
4805 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004806 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004807 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004808
John Marriott8c85a2a2024-05-20 19:18:26 +02004809 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004810 ret = OK;
4811#endif
4812
4813 return ret;
4814}
4815
4816/*
4817 * Get the pattern, column and length for spell completion.
4818 * Sets the global variables: compl_col, compl_length and compl_pattern.
4819 * Uses the global variable: spell_bad_len
4820 */
4821 static int
4822get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4823{
4824 int ret = FAIL;
4825#ifdef FEAT_SPELL
4826 char_u *line;
4827
4828 if (spell_bad_len > 0)
4829 compl_col = curs_col - spell_bad_len;
4830 else
4831 compl_col = spell_word_start(startcol);
4832 if (compl_col >= (colnr_T)startcol)
4833 {
4834 compl_length = 0;
4835 compl_col = curs_col;
4836 }
4837 else
4838 {
4839 spell_expand_check_cap(compl_col);
4840 compl_length = (int)curs_col - compl_col;
4841 }
4842 // Need to obtain "line" again, it may have become invalid.
4843 line = ml_get(curwin->w_cursor.lnum);
4844 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4845 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004846 {
4847 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004848 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004849 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004850
John Marriott8c85a2a2024-05-20 19:18:26 +02004851 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004852 ret = OK;
4853#endif
4854
4855 return ret;
4856}
4857
4858/*
4859 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004860 * "startcol" - start column number of the completion pattern/text
4861 * "cur_col" - current cursor column
4862 * On return, "line_invalid" is set to TRUE, if the current line may have
4863 * become invalid and needs to be fetched again.
4864 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004865 */
4866 static int
4867compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
4868{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004869 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004870 || (ctrl_x_mode & CTRL_X_WANT_IDENT
4871 && !thesaurus_func_complete(ctrl_x_mode)))
4872 {
4873 return get_normal_compl_info(line, startcol, curs_col);
4874 }
4875 else if (ctrl_x_mode_line_or_eval())
4876 {
4877 return get_wholeline_compl_info(line, curs_col);
4878 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004879 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004880 {
4881 return get_filename_compl_info(line, startcol, curs_col);
4882 }
4883 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4884 {
4885 return get_cmdline_compl_info(line, curs_col);
4886 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004887 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004888 || thesaurus_func_complete(ctrl_x_mode))
4889 {
4890 if (get_userdefined_compl_info(curs_col) == FAIL)
4891 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004892 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004893 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004894 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004895 {
4896 if (get_spell_compl_info(startcol, curs_col) == FAIL)
4897 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004898 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004899 }
4900 else
4901 {
4902 internal_error("ins_complete()");
4903 return FAIL;
4904 }
4905
4906 return OK;
4907}
4908
4909/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004910 * Continue an interrupted completion mode search in "line".
4911 *
4912 * If this same ctrl_x_mode has been interrupted use the text from
4913 * "compl_startpos" to the cursor as a pattern to add a new word instead of
4914 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
4915 * the same line as the cursor then fix it (the line has been split because it
4916 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
4917 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004918 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004919 static void
4920ins_compl_continue_search(char_u *line)
4921{
4922 // it is a continued search
4923 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004924 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
4925 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004926 {
4927 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4928 {
4929 // line (probably) wrapped, set compl_startpos to the
4930 // first non_blank in the line, if it is not a wordchar
4931 // include it to get a better pattern, but then we don't
4932 // want the "\\<" prefix, check it below
4933 compl_col = (colnr_T)getwhitecols(line);
4934 compl_startpos.col = compl_col;
4935 compl_startpos.lnum = curwin->w_cursor.lnum;
4936 compl_cont_status &= ~CONT_SOL; // clear SOL if present
4937 }
4938 else
4939 {
4940 // S_IPOS was set when we inserted a word that was at the
4941 // beginning of the line, which means that we'll go to SOL
4942 // mode but first we need to redefine compl_startpos
4943 if (compl_cont_status & CONT_S_IPOS)
4944 {
4945 compl_cont_status |= CONT_SOL;
4946 compl_startpos.col = (colnr_T)(skipwhite(
4947 line + compl_length
4948 + compl_startpos.col) - line);
4949 }
4950 compl_col = compl_startpos.col;
4951 }
4952 compl_length = curwin->w_cursor.col - (int)compl_col;
4953 // IObuff is used to add a "word from the next line" would we
4954 // have enough space? just being paranoid
4955#define MIN_SPACE 75
4956 if (compl_length > (IOSIZE - MIN_SPACE))
4957 {
4958 compl_cont_status &= ~CONT_SOL;
4959 compl_length = (IOSIZE - MIN_SPACE);
4960 compl_col = curwin->w_cursor.col - compl_length;
4961 }
4962 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4963 if (compl_length < 1)
4964 compl_cont_status &= CONT_LOCAL;
4965 }
4966 else if (ctrl_x_mode_line_or_eval())
4967 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4968 else
4969 compl_cont_status = 0;
4970}
4971
4972/*
4973 * start insert mode completion
4974 */
4975 static int
4976ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004977{
4978 char_u *line;
4979 int startcol = 0; // column where searched text starts
4980 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004981 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004982 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004983 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004984
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004985 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004986
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004987 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004988 did_si = FALSE;
4989 can_si = FALSE;
4990 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004991 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004992 return FAIL;
4993
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004994 line = ml_get(curwin->w_cursor.lnum);
4995 curs_col = curwin->w_cursor.col;
4996 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004997
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004998 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4999 && compl_cont_mode == ctrl_x_mode)
5000 // this same ctrl-x_mode was interrupted previously. Continue the
5001 // completion.
5002 ins_compl_continue_search(line);
5003 else
5004 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005005
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005006 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005007 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005008 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005009 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005010 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5011 compl_cont_status = 0;
5012 compl_cont_status |= CONT_N_ADDS;
5013 compl_startpos = curwin->w_cursor;
5014 startcol = (int)curs_col;
5015 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005016 }
5017
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005018 // Work out completion pattern and original text -- webb
5019 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5020 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005021 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5022 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005023 // restore did_ai, so that adding comment leader works
5024 did_ai = save_did_ai;
5025 return FAIL;
5026 }
5027 // If "line" was changed while getting completion info get it again.
5028 if (line_invalid)
5029 line = ml_get(curwin->w_cursor.lnum);
5030
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005031 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005032 {
5033 edit_submode_pre = (char_u *)_(" Adding");
5034 if (ctrl_x_mode_line_or_eval())
5035 {
5036 // Insert a new line, keep indentation but ignore 'comments'.
5037 char_u *old = curbuf->b_p_com;
5038
5039 curbuf->b_p_com = (char_u *)"";
5040 compl_startpos.lnum = curwin->w_cursor.lnum;
5041 compl_startpos.col = compl_col;
5042 ins_eol('\r');
5043 curbuf->b_p_com = old;
5044 compl_length = 0;
5045 compl_col = curwin->w_cursor.col;
5046 }
5047 }
5048 else
5049 {
5050 edit_submode_pre = NULL;
5051 compl_startpos.col = compl_col;
5052 }
5053
5054 if (compl_cont_status & CONT_LOCAL)
5055 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5056 else
5057 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5058
5059 // If any of the original typed text has been changed we need to fix
5060 // the redo buffer.
5061 ins_compl_fixRedoBufForLeader(NULL);
5062
5063 // Always add completion for the original text.
5064 vim_free(compl_orig_text);
5065 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5066 if (p_ic)
5067 flags |= CP_ICASE;
5068 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5069 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
5070 {
5071 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005072 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005073 VIM_CLEAR(compl_orig_text);
5074 return FAIL;
5075 }
5076
5077 // showmode might reset the internal line pointers, so it must
5078 // be called before line = ml_get(), or when this address is no
5079 // longer needed. -- Acevedo.
5080 edit_submode_extra = (char_u *)_("-- Searching...");
5081 edit_submode_highl = HLF_COUNT;
5082 showmode();
5083 edit_submode_extra = NULL;
5084 out_flush();
5085
5086 return OK;
5087}
5088
5089/*
5090 * display the completion status message
5091 */
5092 static void
5093ins_compl_show_statusmsg(void)
5094{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005095 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005096 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005097 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005098 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005099 ? (char_u *)_("Hit end of paragraph")
5100 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005101 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005102 }
5103
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005104 if (edit_submode_extra == NULL)
5105 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005106 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005107 {
5108 edit_submode_extra = (char_u *)_("Back at original");
5109 edit_submode_highl = HLF_W;
5110 }
5111 else if (compl_cont_status & CONT_S_IPOS)
5112 {
5113 edit_submode_extra = (char_u *)_("Word from other line");
5114 edit_submode_highl = HLF_COUNT;
5115 }
5116 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5117 {
5118 edit_submode_extra = (char_u *)_("The only match");
5119 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005120 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005121 }
5122 else
5123 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005124#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005125 // Update completion sequence number when needed.
5126 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005127 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005128#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005129 // The match should always have a sequence number now, this is
5130 // just a safety check.
5131 if (compl_curr_match->cp_number != -1)
5132 {
5133 // Space for 10 text chars. + 2x10-digit no.s = 31.
5134 // Translations may need more than twice that.
5135 static char_u match_ref[81];
5136
5137 if (compl_matches > 0)
5138 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005139 _("match %d of %d"),
5140 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005141 else
5142 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005143 _("match %d"),
5144 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005145 edit_submode_extra = match_ref;
5146 edit_submode_highl = HLF_R;
5147 if (dollar_vcol >= 0)
5148 curs_columns(FALSE);
5149 }
5150 }
5151 }
5152
5153 // Show a message about what (completion) mode we're in.
5154 if (!compl_opt_suppress_empty)
5155 {
5156 showmode();
5157 if (!shortmess(SHM_COMPLETIONMENU))
5158 {
5159 if (edit_submode_extra != NULL)
5160 {
5161 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005162 {
5163 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005164 msg_attr((char *)edit_submode_extra,
5165 edit_submode_highl < HLF_COUNT
5166 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005167 msg_hist_off = FALSE;
5168 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005169 }
5170 else
5171 msg_clr_cmdline(); // necessary for "noshowmode"
5172 }
5173 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005174}
5175
5176/*
5177 * Do Insert mode completion.
5178 * Called when character "c" was typed, which has a meaning for completion.
5179 * Returns OK if completion was done, FAIL if something failed (out of mem).
5180 */
5181 int
5182ins_complete(int c, int enable_pum)
5183{
5184 int n;
5185 int save_w_wrow;
5186 int save_w_leftcol;
5187 int insert_match;
5188
5189 compl_direction = ins_compl_key2dir(c);
5190 insert_match = ins_compl_use_match(c);
5191
5192 if (!compl_started)
5193 {
5194 if (ins_compl_start() == FAIL)
5195 return FAIL;
5196 }
5197 else if (insert_match && stop_arrow() == FAIL)
5198 return FAIL;
5199
5200 compl_shown_match = compl_curr_match;
5201 compl_shows_dir = compl_direction;
5202
5203 // Find next match (and following matches).
5204 save_w_wrow = curwin->w_wrow;
5205 save_w_leftcol = curwin->w_leftcol;
5206 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5207
5208 // may undisplay the popup menu
5209 ins_compl_upd_pum();
5210
5211 if (n > 1) // all matches have been found
5212 compl_matches = n;
5213 compl_curr_match = compl_shown_match;
5214 compl_direction = compl_shows_dir;
5215
5216 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5217 // mode.
5218 if (got_int && !global_busy)
5219 {
5220 (void)vgetc();
5221 got_int = FALSE;
5222 }
5223
5224 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005225 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005226 {
5227 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5228 // because we couldn't expand anything at first place, but if we used
5229 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5230 // (such as M in M'exico) if not tried already. -- Acevedo
5231 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005232 || compl_status_adding()
5233 || (ctrl_x_mode_not_default()
5234 && !ctrl_x_mode_path_patterns()
5235 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005236 compl_cont_status &= ~CONT_N_ADDS;
5237 }
5238
5239 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5240 compl_cont_status |= CONT_S_IPOS;
5241 else
5242 compl_cont_status &= ~CONT_S_IPOS;
5243
5244 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005245
5246 // Show the popup menu, unless we got interrupted.
5247 if (enable_pum && !compl_interrupted)
5248 show_pum(save_w_wrow, save_w_leftcol);
5249
5250 compl_was_interrupted = compl_interrupted;
5251 compl_interrupted = FALSE;
5252
5253 return OK;
5254}
5255
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005256/*
5257 * Remove (if needed) and show the popup menu
5258 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005259 static void
5260show_pum(int prev_w_wrow, int prev_w_leftcol)
5261{
5262 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005263 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005264 RedrawingDisabled = 0;
5265
5266 // If the cursor moved or the display scrolled we need to remove the pum
5267 // first.
5268 setcursor();
5269 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5270 ins_compl_del_pum();
5271
5272 ins_compl_show_pum();
5273 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005274
5275 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005276}
5277
5278/*
5279 * Looks in the first "len" chars. of "src" for search-metachars.
5280 * If dest is not NULL the chars. are copied there quoting (with
5281 * a backslash) the metachars, and dest would be NUL terminated.
5282 * Returns the length (needed) of dest
5283 */
5284 static unsigned
5285quote_meta(char_u *dest, char_u *src, int len)
5286{
5287 unsigned m = (unsigned)len + 1; // one extra for the NUL
5288
5289 for ( ; --len >= 0; src++)
5290 {
5291 switch (*src)
5292 {
5293 case '.':
5294 case '*':
5295 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005296 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005297 break;
5298 // FALLTHROUGH
5299 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005300 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005301 break;
5302 // FALLTHROUGH
5303 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005304 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005305 break;
5306 // FALLTHROUGH
5307 case '^': // currently it's not needed.
5308 case '$':
5309 m++;
5310 if (dest != NULL)
5311 *dest++ = '\\';
5312 break;
5313 }
5314 if (dest != NULL)
5315 *dest++ = *src;
5316 // Copy remaining bytes of a multibyte character.
5317 if (has_mbyte)
5318 {
5319 int i, mb_len;
5320
5321 mb_len = (*mb_ptr2len)(src) - 1;
5322 if (mb_len > 0 && len >= mb_len)
5323 for (i = 0; i < mb_len; ++i)
5324 {
5325 --len;
5326 ++src;
5327 if (dest != NULL)
5328 *dest++ = *src;
5329 }
5330 }
5331 }
5332 if (dest != NULL)
5333 *dest = NUL;
5334
5335 return m;
5336}
5337
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005338#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005339 void
5340free_insexpand_stuff(void)
5341{
5342 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005343# ifdef FEAT_EVAL
5344 free_callback(&cfu_cb);
5345 free_callback(&ofu_cb);
5346 free_callback(&tsrfu_cb);
5347# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005348}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005349#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005350
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005351#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005352/*
5353 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5354 * spelled word, if there is one.
5355 */
5356 static void
5357spell_back_to_badword(void)
5358{
5359 pos_T tpos = curwin->w_cursor;
5360
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005361 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005362 if (curwin->w_cursor.col != tpos.col)
5363 start_arrow(&tpos);
5364}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005365#endif