blob: fafa7a2f0d959560d639905eade68340f777b80e [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 {
glepnirdca57fb2024-06-04 22:01:21 +02001301 // Update the maximum fuzzy score and the shown match
1302 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001303 if (compl->cp_score > max_fuzzy_score)
1304 {
1305 did_find_shown_match = TRUE;
1306 max_fuzzy_score = compl->cp_score;
1307 compl_shown_match = compl;
1308 shown_match_ok = TRUE;
1309 }
1310
glepnirdca57fb2024-06-04 22:01:21 +02001311 // If there is no "no select" condition and the max fuzzy
1312 // score is positive, or there is no completion leader or the
1313 // leader length is zero, mark the shown match as valid and
1314 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001315 if (!compl_no_select
1316 && (max_fuzzy_score > 0
1317 || (compl_leader == NULL || lead_len == 0)))
1318 {
1319 shown_match_ok = TRUE;
1320 cur = 0;
1321 }
1322 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001323
1324 if (compl->cp_text[CPT_ABBR] != NULL)
1325 compl_match_array[i].pum_text =
1326 compl->cp_text[CPT_ABBR];
1327 else
1328 compl_match_array[i].pum_text = compl->cp_str;
1329 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1330 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001331 compl_match_array[i].pum_score = compl->cp_score;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001332 if (compl->cp_text[CPT_MENU] != NULL)
1333 compl_match_array[i++].pum_extra =
1334 compl->cp_text[CPT_MENU];
1335 else
1336 compl_match_array[i++].pum_extra = compl->cp_fname;
1337 }
1338
glepnira218cc62024-06-03 19:32:39 +02001339 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001340 {
1341 did_find_shown_match = TRUE;
1342
1343 // When the original text is the shown match don't set
1344 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001345 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001346 shown_match_ok = TRUE;
1347
1348 if (!shown_match_ok && shown_compl != NULL)
1349 {
1350 // The shown match isn't displayed, set it to the
1351 // previously displayed match.
1352 compl_shown_match = shown_compl;
1353 shown_match_ok = TRUE;
1354 }
1355 }
1356 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001357 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001358
glepnira218cc62024-06-03 19:32:39 +02001359 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001360 {
1361 for (i = 0; i < compl_match_arraysize; i++)
1362 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001363 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001364 qsort(compl_match_array, (size_t)compl_match_arraysize,
1365 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
1366 }
glepnira218cc62024-06-03 19:32:39 +02001367
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001368 if (!shown_match_ok) // no displayed match at all
1369 cur = -1;
1370
1371 return cur;
1372}
1373
1374/*
1375 * Show the popup menu for the list of matches.
1376 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1377 */
1378 void
1379ins_compl_show_pum(void)
1380{
1381 int i;
1382 int cur = -1;
1383 colnr_T col;
1384
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001385 if (!pum_wanted() || !pum_enough_matches())
1386 return;
1387
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001388 // Update the screen later, before drawing the popup menu over it.
1389 pum_call_update_screen();
1390
1391 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001392 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001393 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001394 else
1395 {
1396 // popup menu already exists, only need to find the current item.
1397 for (i = 0; i < compl_match_arraysize; ++i)
1398 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1399 || compl_match_array[i].pum_text
1400 == compl_shown_match->cp_text[CPT_ABBR])
1401 {
1402 cur = i;
1403 break;
1404 }
1405 }
1406
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001407 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001408 {
1409#ifdef FEAT_EVAL
1410 if (compl_started && has_completechanged())
1411 trigger_complete_changed_event(cur);
1412#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001413 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001414 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001415
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001416 // In Replace mode when a $ is displayed at the end of the line only
1417 // part of the screen would be updated. We do need to redraw here.
1418 dollar_vcol = -1;
1419
1420 // Compute the screen column of the start of the completed text.
1421 // Use the cursor to get all wrapping and other settings right.
1422 col = curwin->w_cursor.col;
1423 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001424 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001425 pum_display(compl_match_array, compl_match_arraysize, cur);
1426 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001427
glepnircbb46b42024-02-03 18:11:13 +01001428 // After adding leader, set the current match to shown match.
1429 if (compl_started && compl_curr_match != compl_shown_match)
1430 compl_curr_match = compl_shown_match;
1431
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001432#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001433 if (has_completechanged())
1434 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001435#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001436}
1437
1438#define DICT_FIRST (1) // use just first element in "dict"
1439#define DICT_EXACT (2) // "dict" is the exact name of a file
1440
1441/*
glepnir40c1c332024-06-11 19:37:04 +02001442 * Get current completion leader
1443 */
1444 char_u *
1445ins_compl_leader(void)
1446{
1447 return compl_leader;
1448}
1449
1450/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001451 * Add any identifiers that match the given pattern "pat" in the list of
1452 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001453 */
1454 static void
1455ins_compl_dictionaries(
1456 char_u *dict_start,
1457 char_u *pat,
1458 int flags, // DICT_FIRST and/or DICT_EXACT
1459 int thesaurus) // Thesaurus completion
1460{
1461 char_u *dict = dict_start;
1462 char_u *ptr;
1463 char_u *buf;
1464 regmatch_T regmatch;
1465 char_u **files;
1466 int count;
1467 int save_p_scs;
1468 int dir = compl_direction;
1469
1470 if (*dict == NUL)
1471 {
1472#ifdef FEAT_SPELL
1473 // When 'dictionary' is empty and spell checking is enabled use
1474 // "spell".
1475 if (!thesaurus && curwin->w_p_spell)
1476 dict = (char_u *)"spell";
1477 else
1478#endif
1479 return;
1480 }
1481
1482 buf = alloc(LSIZE);
1483 if (buf == NULL)
1484 return;
1485 regmatch.regprog = NULL; // so that we can goto theend
1486
1487 // If 'infercase' is set, don't use 'smartcase' here
1488 save_p_scs = p_scs;
1489 if (curbuf->b_p_inf)
1490 p_scs = FALSE;
1491
1492 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1493 // to only match at the start of a line. Otherwise just match the
1494 // pattern. Also need to double backslashes.
1495 if (ctrl_x_mode_line_or_eval())
1496 {
1497 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1498 size_t len;
1499
1500 if (pat_esc == NULL)
1501 goto theend;
1502 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001503 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001504 if (ptr == NULL)
1505 {
1506 vim_free(pat_esc);
1507 goto theend;
1508 }
1509 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1510 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1511 vim_free(pat_esc);
1512 vim_free(ptr);
1513 }
1514 else
1515 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001516 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001517 if (regmatch.regprog == NULL)
1518 goto theend;
1519 }
1520
1521 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1522 regmatch.rm_ic = ignorecase(pat);
1523 while (*dict != NUL && !got_int && !compl_interrupted)
1524 {
1525 // copy one dictionary file name into buf
1526 if (flags == DICT_EXACT)
1527 {
1528 count = 1;
1529 files = &dict;
1530 }
1531 else
1532 {
1533 // Expand wildcards in the dictionary name, but do not allow
1534 // backticks (for security, the 'dict' option may have been set in
1535 // a modeline).
1536 copy_option_part(&dict, buf, LSIZE, ",");
1537# ifdef FEAT_SPELL
1538 if (!thesaurus && STRCMP(buf, "spell") == 0)
1539 count = -1;
1540 else
1541# endif
1542 if (vim_strchr(buf, '`') != NULL
1543 || expand_wildcards(1, &buf, &count, &files,
1544 EW_FILE|EW_SILENT) != OK)
1545 count = 0;
1546 }
1547
1548# ifdef FEAT_SPELL
1549 if (count == -1)
1550 {
1551 // Complete from active spelling. Skip "\<" in the pattern, we
1552 // don't use it as a RE.
1553 if (pat[0] == '\\' && pat[1] == '<')
1554 ptr = pat + 2;
1555 else
1556 ptr = pat;
1557 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1558 }
1559 else
1560# endif
1561 if (count > 0) // avoid warning for using "files" uninit
1562 {
1563 ins_compl_files(count, files, thesaurus, flags,
1564 &regmatch, buf, &dir);
1565 if (flags != DICT_EXACT)
1566 FreeWild(count, files);
1567 }
1568 if (flags != 0)
1569 break;
1570 }
1571
1572theend:
1573 p_scs = save_p_scs;
1574 vim_regfree(regmatch.regprog);
1575 vim_free(buf);
1576}
1577
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001578/*
1579 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1580 * skipping the word at 'skip_word'. Returns OK on success.
1581 */
1582 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001583thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001584 char_u *fname,
1585 char_u **buf_arg,
1586 int dir,
1587 char_u *skip_word)
1588{
1589 int status = OK;
1590 char_u *ptr;
1591 char_u *wstart;
1592
1593 // Add the other matches on the line
1594 ptr = *buf_arg;
1595 while (!got_int)
1596 {
1597 // Find start of the next word. Skip white
1598 // space and punctuation.
1599 ptr = find_word_start(ptr);
1600 if (*ptr == NUL || *ptr == NL)
1601 break;
1602 wstart = ptr;
1603
1604 // Find end of the word.
1605 if (has_mbyte)
1606 // Japanese words may have characters in
1607 // different classes, only separate words
1608 // with single-byte non-word characters.
1609 while (*ptr != NUL)
1610 {
1611 int l = (*mb_ptr2len)(ptr);
1612
1613 if (l < 2 && !vim_iswordc(*ptr))
1614 break;
1615 ptr += l;
1616 }
1617 else
1618 ptr = find_word_end(ptr);
1619
1620 // Add the word. Skip the regexp match.
1621 if (wstart != skip_word)
1622 {
1623 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1624 fname, dir, FALSE);
1625 if (status == FAIL)
1626 break;
1627 }
1628 }
1629
1630 *buf_arg = ptr;
1631 return status;
1632}
1633
1634/*
1635 * Process "count" dictionary/thesaurus "files" and add the text matching
1636 * "regmatch".
1637 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001638 static void
1639ins_compl_files(
1640 int count,
1641 char_u **files,
1642 int thesaurus,
1643 int flags,
1644 regmatch_T *regmatch,
1645 char_u *buf,
1646 int *dir)
1647{
1648 char_u *ptr;
1649 int i;
1650 FILE *fp;
1651 int add_r;
1652
1653 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1654 {
1655 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001656 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001657 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001658 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001659 vim_snprintf((char *)IObuff, IOSIZE,
1660 _("Scanning dictionary: %s"), (char *)files[i]);
1661 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1662 }
1663
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001664 if (fp == NULL)
1665 continue;
1666
1667 // Read dictionary file line by line.
1668 // Check each line for a match.
1669 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001670 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001671 ptr = buf;
1672 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001673 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001674 ptr = regmatch->startp[0];
1675 if (ctrl_x_mode_line_or_eval())
1676 ptr = find_line_end(ptr);
1677 else
1678 ptr = find_word_end(ptr);
1679 add_r = ins_compl_add_infercase(regmatch->startp[0],
1680 (int)(ptr - regmatch->startp[0]),
1681 p_ic, files[i], *dir, FALSE);
1682 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001683 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001684 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001685 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001686 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001687 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001688 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001689 if (add_r == OK)
1690 // if dir was BACKWARD then honor it just once
1691 *dir = FORWARD;
1692 else if (add_r == FAIL)
1693 break;
1694 // avoid expensive call to vim_regexec() when at end
1695 // of line
1696 if (*ptr == '\n' || got_int)
1697 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001698 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001699 line_breakcheck();
1700 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001701 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001702 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001703 }
1704}
1705
1706/*
1707 * Find the start of the next word.
1708 * Returns a pointer to the first char of the word. Also stops at a NUL.
1709 */
1710 char_u *
1711find_word_start(char_u *ptr)
1712{
1713 if (has_mbyte)
1714 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1715 ptr += (*mb_ptr2len)(ptr);
1716 else
1717 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1718 ++ptr;
1719 return ptr;
1720}
1721
1722/*
1723 * Find the end of the word. Assumes it starts inside a word.
1724 * Returns a pointer to just after the word.
1725 */
1726 char_u *
1727find_word_end(char_u *ptr)
1728{
1729 int start_class;
1730
1731 if (has_mbyte)
1732 {
1733 start_class = mb_get_class(ptr);
1734 if (start_class > 1)
1735 while (*ptr != NUL)
1736 {
1737 ptr += (*mb_ptr2len)(ptr);
1738 if (mb_get_class(ptr) != start_class)
1739 break;
1740 }
1741 }
1742 else
1743 while (vim_iswordc(*ptr))
1744 ++ptr;
1745 return ptr;
1746}
1747
1748/*
1749 * Find the end of the line, omitting CR and NL at the end.
1750 * Returns a pointer to just after the line.
1751 */
1752 static char_u *
1753find_line_end(char_u *ptr)
1754{
1755 char_u *s;
1756
1757 s = ptr + STRLEN(ptr);
1758 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1759 --s;
1760 return s;
1761}
1762
1763/*
1764 * Free the list of completions
1765 */
1766 static void
1767ins_compl_free(void)
1768{
1769 compl_T *match;
1770 int i;
1771
1772 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001773 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001774 VIM_CLEAR(compl_leader);
1775
1776 if (compl_first_match == NULL)
1777 return;
1778
1779 ins_compl_del_pum();
1780 pum_clear();
1781
1782 compl_curr_match = compl_first_match;
1783 do
1784 {
1785 match = compl_curr_match;
1786 compl_curr_match = compl_curr_match->cp_next;
1787 vim_free(match->cp_str);
1788 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001789 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001790 vim_free(match->cp_fname);
1791 for (i = 0; i < CPT_COUNT; ++i)
1792 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001793#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001794 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001795#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001796 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001797 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001798 compl_first_match = compl_curr_match = NULL;
1799 compl_shown_match = NULL;
1800 compl_old_match = NULL;
1801}
1802
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001803/*
1804 * Reset/clear the completion state.
1805 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001806 void
1807ins_compl_clear(void)
1808{
1809 compl_cont_status = 0;
1810 compl_started = FALSE;
1811 compl_matches = 0;
1812 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001813 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001814 VIM_CLEAR(compl_leader);
1815 edit_submode_extra = NULL;
1816 VIM_CLEAR(compl_orig_text);
1817 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001818#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001819 // clear v:completed_item
1820 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001821#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001822}
1823
1824/*
1825 * Return TRUE when Insert completion is active.
1826 */
1827 int
1828ins_compl_active(void)
1829{
1830 return compl_started;
1831}
1832
1833/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001834 * Selected one of the matches. When FALSE the match was edited or using the
1835 * longest common string.
1836 */
1837 int
1838ins_compl_used_match(void)
1839{
1840 return compl_used_match;
1841}
1842
1843/*
1844 * Initialize get longest common string.
1845 */
1846 void
1847ins_compl_init_get_longest(void)
1848{
1849 compl_get_longest = FALSE;
1850}
1851
1852/*
1853 * Returns TRUE when insert completion is interrupted.
1854 */
1855 int
1856ins_compl_interrupted(void)
1857{
1858 return compl_interrupted;
1859}
1860
1861/*
1862 * Returns TRUE if the <Enter> key selects a match in the completion popup
1863 * menu.
1864 */
1865 int
1866ins_compl_enter_selects(void)
1867{
1868 return compl_enter_selects;
1869}
1870
1871/*
1872 * Return the column where the text starts that is being completed
1873 */
1874 colnr_T
1875ins_compl_col(void)
1876{
1877 return compl_col;
1878}
1879
1880/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001881 * Return the length in bytes of the text being completed
1882 */
1883 int
1884ins_compl_len(void)
1885{
1886 return compl_length;
1887}
1888
1889/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001890 * Delete one character before the cursor and show the subset of the matches
1891 * that match the word that is now before the cursor.
1892 * Returns the character to be used, NUL if the work is done and another char
1893 * to be got from the user.
1894 */
1895 int
1896ins_compl_bs(void)
1897{
1898 char_u *line;
1899 char_u *p;
1900
1901 line = ml_get_curline();
1902 p = line + curwin->w_cursor.col;
1903 MB_PTR_BACK(line, p);
1904
1905 // Stop completion when the whole word was deleted. For Omni completion
1906 // allow the word to be deleted, we won't match everything.
1907 // Respect the 'backspace' option.
1908 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001909 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1910 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001911 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1912 - compl_length < 0))
1913 return K_BS;
1914
1915 // Deleted more than what was used to find matches or didn't finish
1916 // finding all matches: need to look for matches all over again.
1917 if (curwin->w_cursor.col <= compl_col + compl_length
1918 || ins_compl_need_restart())
1919 ins_compl_restart();
1920
1921 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001922 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001923 if (compl_leader == NULL)
1924 return K_BS;
1925
1926 ins_compl_new_leader();
1927 if (compl_shown_match != NULL)
1928 // Make sure current match is not a hidden item.
1929 compl_curr_match = compl_shown_match;
1930 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001931}
1932
1933/*
1934 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1935 * be called.
1936 */
1937 static int
1938ins_compl_need_restart(void)
1939{
1940 // Return TRUE if we didn't complete finding matches or when the
1941 // 'completefunc' returned "always" in the "refresh" dictionary item.
1942 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001943 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001944 && compl_opt_refresh_always);
1945}
1946
1947/*
1948 * Called after changing "compl_leader".
1949 * Show the popup menu with a different set of matches.
1950 * May also search for matches again if the previous search was interrupted.
1951 */
1952 static void
1953ins_compl_new_leader(void)
1954{
1955 ins_compl_del_pum();
1956 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001957 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001958 compl_used_match = FALSE;
1959
1960 if (compl_started)
1961 ins_compl_set_original_text(compl_leader);
1962 else
1963 {
1964#ifdef FEAT_SPELL
1965 spell_bad_len = 0; // need to redetect bad word
1966#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001967 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001968 // the popup menu display the changed text before the cursor. Set
1969 // "compl_restarting" to avoid that the first match is inserted.
1970 pum_call_update_screen();
1971#ifdef FEAT_GUI
1972 if (gui.in_use)
1973 {
1974 // Show the cursor after the match, not after the redrawn text.
1975 setcursor();
1976 out_flush_cursor(FALSE, FALSE);
1977 }
1978#endif
1979 compl_restarting = TRUE;
1980 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1981 compl_cont_status = 0;
1982 compl_restarting = FALSE;
1983 }
1984
1985 compl_enter_selects = !compl_used_match;
1986
1987 // Show the popup menu with a different set of matches.
1988 ins_compl_show_pum();
1989
1990 // Don't let Enter select the original text when there is no popup menu.
1991 if (compl_match_array == NULL)
1992 compl_enter_selects = FALSE;
1993}
1994
1995/*
1996 * Return the length of the completion, from the completion start column to
1997 * the cursor column. Making sure it never goes below zero.
1998 */
1999 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002000get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002001{
2002 int off = (int)curwin->w_cursor.col - (int)compl_col;
2003
2004 if (off < 0)
2005 return 0;
2006 return off;
2007}
2008
2009/*
2010 * Append one character to the match leader. May reduce the number of
2011 * matches.
2012 */
2013 void
2014ins_compl_addleader(int c)
2015{
2016 int cc;
2017
2018 if (stop_arrow() == FAIL)
2019 return;
2020 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2021 {
2022 char_u buf[MB_MAXBYTES + 1];
2023
2024 (*mb_char2bytes)(c, buf);
2025 buf[cc] = NUL;
2026 ins_char_bytes(buf, cc);
2027 if (compl_opt_refresh_always)
2028 AppendToRedobuff(buf);
2029 }
2030 else
2031 {
2032 ins_char(c);
2033 if (compl_opt_refresh_always)
2034 AppendCharToRedobuff(c);
2035 }
2036
2037 // If we didn't complete finding matches we must search again.
2038 if (ins_compl_need_restart())
2039 ins_compl_restart();
2040
2041 // When 'always' is set, don't reset compl_leader. While completing,
2042 // cursor doesn't point original position, changing compl_leader would
2043 // break redo.
2044 if (!compl_opt_refresh_always)
2045 {
2046 vim_free(compl_leader);
2047 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002048 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002049 if (compl_leader != NULL)
2050 ins_compl_new_leader();
2051 }
2052}
2053
2054/*
2055 * Setup for finding completions again without leaving CTRL-X mode. Used when
2056 * BS or a key was typed while still searching for matches.
2057 */
2058 static void
2059ins_compl_restart(void)
2060{
2061 ins_compl_free();
2062 compl_started = FALSE;
2063 compl_matches = 0;
2064 compl_cont_status = 0;
2065 compl_cont_mode = 0;
2066}
2067
2068/*
2069 * Set the first match, the original text.
2070 */
2071 static void
2072ins_compl_set_original_text(char_u *str)
2073{
2074 char_u *p;
2075
2076 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002077 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2078 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002079 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002080 {
2081 p = vim_strsave(str);
2082 if (p != NULL)
2083 {
2084 vim_free(compl_first_match->cp_str);
2085 compl_first_match->cp_str = p;
2086 }
2087 }
2088 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002089 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002090 {
2091 p = vim_strsave(str);
2092 if (p != NULL)
2093 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002094 vim_free(compl_first_match->cp_prev->cp_str);
2095 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002096 }
2097 }
2098}
2099
2100/*
2101 * Append one character to the match leader. May reduce the number of
2102 * matches.
2103 */
2104 void
2105ins_compl_addfrommatch(void)
2106{
2107 char_u *p;
2108 int len = (int)curwin->w_cursor.col - (int)compl_col;
2109 int c;
2110 compl_T *cp;
2111
2112 p = compl_shown_match->cp_str;
2113 if ((int)STRLEN(p) <= len) // the match is too short
2114 {
2115 // When still at the original match use the first entry that matches
2116 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002117 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002118 return;
2119
2120 p = NULL;
2121 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002122 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002123 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002124 if (compl_leader == NULL
2125 || ins_compl_equal(cp, compl_leader,
2126 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002127 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002128 p = cp->cp_str;
2129 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002130 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002131 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002132 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002133 return;
2134 }
2135 p += len;
2136 c = PTR2CHAR(p);
2137 ins_compl_addleader(c);
2138}
2139
2140/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002141 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002142 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2143 * compl_cont_mode and compl_cont_status.
2144 * Returns TRUE when the character is not to be inserted.
2145 */
2146 static int
2147set_ctrl_x_mode(int c)
2148{
2149 int retval = FALSE;
2150
2151 switch (c)
2152 {
2153 case Ctrl_E:
2154 case Ctrl_Y:
2155 // scroll the window one line up or down
2156 ctrl_x_mode = CTRL_X_SCROLL;
2157 if (!(State & REPLACE_FLAG))
2158 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2159 else
2160 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2161 edit_submode_pre = NULL;
2162 showmode();
2163 break;
2164 case Ctrl_L:
2165 // complete whole line
2166 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2167 break;
2168 case Ctrl_F:
2169 // complete filenames
2170 ctrl_x_mode = CTRL_X_FILES;
2171 break;
2172 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002173 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002174 ctrl_x_mode = CTRL_X_DICTIONARY;
2175 break;
2176 case Ctrl_R:
2177 // Register insertion without exiting CTRL-X mode
2178 // Simply allow ^R to happen without affecting ^X mode
2179 break;
2180 case Ctrl_T:
2181 // complete words from a thesaurus
2182 ctrl_x_mode = CTRL_X_THESAURUS;
2183 break;
2184#ifdef FEAT_COMPL_FUNC
2185 case Ctrl_U:
2186 // user defined completion
2187 ctrl_x_mode = CTRL_X_FUNCTION;
2188 break;
2189 case Ctrl_O:
2190 // omni completion
2191 ctrl_x_mode = CTRL_X_OMNI;
2192 break;
2193#endif
2194 case 's':
2195 case Ctrl_S:
2196 // complete spelling suggestions
2197 ctrl_x_mode = CTRL_X_SPELL;
2198#ifdef FEAT_SPELL
2199 ++emsg_off; // Avoid getting the E756 error twice.
2200 spell_back_to_badword();
2201 --emsg_off;
2202#endif
2203 break;
2204 case Ctrl_RSB:
2205 // complete tag names
2206 ctrl_x_mode = CTRL_X_TAGS;
2207 break;
2208#ifdef FEAT_FIND_ID
2209 case Ctrl_I:
2210 case K_S_TAB:
2211 // complete keywords from included files
2212 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2213 break;
2214 case Ctrl_D:
2215 // complete definitions from included files
2216 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2217 break;
2218#endif
2219 case Ctrl_V:
2220 case Ctrl_Q:
2221 // complete vim commands
2222 ctrl_x_mode = CTRL_X_CMDLINE;
2223 break;
2224 case Ctrl_Z:
2225 // stop completion
2226 ctrl_x_mode = CTRL_X_NORMAL;
2227 edit_submode = NULL;
2228 showmode();
2229 retval = TRUE;
2230 break;
2231 case Ctrl_P:
2232 case Ctrl_N:
2233 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2234 // just started ^X mode, or there were enough ^X's to cancel
2235 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2236 // do normal expansion when interrupting a different mode (say
2237 // ^X^F^X^P or ^P^X^X^P, see below)
2238 // nothing changes if interrupting mode 0, (eg, the flag
2239 // doesn't change when going to ADDING mode -- Acevedo
2240 if (!(compl_cont_status & CONT_INTRPT))
2241 compl_cont_status |= CONT_LOCAL;
2242 else if (compl_cont_mode != 0)
2243 compl_cont_status &= ~CONT_LOCAL;
2244 // FALLTHROUGH
2245 default:
2246 // If we have typed at least 2 ^X's... for modes != 0, we set
2247 // compl_cont_status = 0 (eg, as if we had just started ^X
2248 // mode).
2249 // For mode 0, we set "compl_cont_mode" to an impossible
2250 // value, in both cases ^X^X can be used to restart the same
2251 // mode (avoiding ADDING mode).
2252 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2253 // 'complete' and local ^P expansions respectively.
2254 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2255 // mode -- Acevedo
2256 if (c == Ctrl_X)
2257 {
2258 if (compl_cont_mode != 0)
2259 compl_cont_status = 0;
2260 else
2261 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2262 }
2263 ctrl_x_mode = CTRL_X_NORMAL;
2264 edit_submode = NULL;
2265 showmode();
2266 break;
2267 }
2268
2269 return retval;
2270}
2271
2272/*
2273 * Stop insert completion mode
2274 */
2275 static int
2276ins_compl_stop(int c, int prev_mode, int retval)
2277{
2278 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002279 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002280
2281 // Get here when we have finished typing a sequence of ^N and
2282 // ^P or other completion characters in CTRL-X mode. Free up
2283 // memory that was used, and make sure we can redo the insert.
2284 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2285 {
2286 // If any of the original typed text has been changed, eg when
2287 // ignorecase is set, we must add back-spaces to the redo
2288 // buffer. We add as few as necessary to delete just the part
2289 // of the original text that has changed.
2290 // When using the longest match, edited the match or used
2291 // CTRL-E then don't use the current match.
2292 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2293 ptr = compl_curr_match->cp_str;
2294 else
2295 ptr = NULL;
2296 ins_compl_fixRedoBufForLeader(ptr);
2297 }
2298
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002299 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002300
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002301 // When completing whole lines: fix indent for 'cindent'.
2302 // Otherwise, break line if it's too long.
2303 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2304 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002305 // re-indent the current line
2306 if (want_cindent)
2307 {
2308 do_c_expr_indent();
2309 want_cindent = FALSE; // don't do it again
2310 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002311 }
2312 else
2313 {
2314 int prev_col = curwin->w_cursor.col;
2315
2316 // put the cursor on the last char, for 'tw' formatting
2317 if (prev_col > 0)
2318 dec_cursor();
2319 // only format when something was inserted
2320 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2321 insertchar(NUL, 0, -1);
2322 if (prev_col > 0
2323 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2324 inc_cursor();
2325 }
2326
2327 // If the popup menu is displayed pressing CTRL-Y means accepting
2328 // the selection without inserting anything. When
2329 // compl_enter_selects is set the Enter key does the same.
2330 if ((c == Ctrl_Y || (compl_enter_selects
2331 && (c == CAR || c == K_KENTER || c == NL)))
2332 && pum_visible())
2333 retval = TRUE;
2334
2335 // CTRL-E means completion is Ended, go back to the typed text.
2336 // but only do this, if the Popup is still visible
2337 if (c == Ctrl_E)
2338 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002339 char_u *p = NULL;
2340
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002341 ins_compl_delete();
2342 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002343 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002344 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002345 p = compl_orig_text;
2346 if (p != NULL)
2347 {
2348 int compl_len = get_compl_len();
2349 int len = (int)STRLEN(p);
2350
2351 if (len > compl_len)
2352 ins_bytes_len(p + compl_len, len - compl_len);
2353 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002354 retval = TRUE;
2355 }
2356
2357 auto_format(FALSE, TRUE);
2358
2359 // Trigger the CompleteDonePre event to give scripts a chance to
2360 // act upon the completion before clearing the info, and restore
2361 // ctrl_x_mode, so that complete_info() can be used.
2362 ctrl_x_mode = prev_mode;
2363 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2364
2365 ins_compl_free();
2366 compl_started = FALSE;
2367 compl_matches = 0;
2368 if (!shortmess(SHM_COMPLETIONMENU))
2369 msg_clr_cmdline(); // necessary for "noshowmode"
2370 ctrl_x_mode = CTRL_X_NORMAL;
2371 compl_enter_selects = FALSE;
2372 if (edit_submode != NULL)
2373 {
2374 edit_submode = NULL;
2375 showmode();
2376 }
2377
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002378 if (c == Ctrl_C && cmdwin_type != 0)
2379 // Avoid the popup menu remains displayed when leaving the
2380 // command line window.
2381 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002382 // Indent now if a key was typed that is in 'cinkeys'.
2383 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2384 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002385 // Trigger the CompleteDone event to give scripts a chance to act
2386 // upon the end of completion.
2387 ins_apply_autocmds(EVENT_COMPLETEDONE);
2388
2389 return retval;
2390}
2391
2392/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002393 * Prepare for Insert mode completion, or stop it.
2394 * Called just after typing a character in Insert mode.
2395 * Returns TRUE when the character is not to be inserted;
2396 */
2397 int
2398ins_compl_prep(int c)
2399{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002400 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002401 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002402
2403 // Forget any previous 'special' messages if this is actually
2404 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2405 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2406 edit_submode_extra = NULL;
2407
zeertzjq440d4cb2023-03-02 17:51:32 +00002408 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002409 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002410 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002411 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002412 return retval;
2413
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002414#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002415 // Ignore mouse events in a popup window
2416 if (is_mouse_key(c))
2417 {
2418 // Ignore drag and release events, the position does not need to be in
2419 // the popup and it may have just closed.
2420 if (c == K_LEFTRELEASE
2421 || c == K_LEFTRELEASE_NM
2422 || c == K_MIDDLERELEASE
2423 || c == K_RIGHTRELEASE
2424 || c == K_X1RELEASE
2425 || c == K_X2RELEASE
2426 || c == K_LEFTDRAG
2427 || c == K_MIDDLEDRAG
2428 || c == K_RIGHTDRAG
2429 || c == K_X1DRAG
2430 || c == K_X2DRAG)
2431 return retval;
2432 if (popup_visible)
2433 {
2434 int row = mouse_row;
2435 int col = mouse_col;
2436 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2437
2438 if (wp != NULL && WIN_IS_POPUP(wp))
2439 return retval;
2440 }
2441 }
2442#endif
2443
zeertzjqdca29d92021-08-31 19:12:51 +02002444 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2445 {
2446 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2447 || !vim_is_ctrl_x_key(c))
2448 {
2449 // Not starting another completion mode.
2450 ctrl_x_mode = CTRL_X_CMDLINE;
2451
2452 // CTRL-X CTRL-Z should stop completion without inserting anything
2453 if (c == Ctrl_Z)
2454 retval = TRUE;
2455 }
2456 else
2457 {
2458 ctrl_x_mode = CTRL_X_CMDLINE;
2459
2460 // Other CTRL-X keys first stop completion, then start another
2461 // completion mode.
2462 ins_compl_prep(' ');
2463 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2464 }
2465 }
2466
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002467 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002468 if (ctrl_x_mode_not_defined_yet()
2469 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002470 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002471 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002472 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002473 }
2474
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002475 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002476 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2477 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002478 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002479 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002480 {
2481 // We're already in CTRL-X mode, do we stay in it?
2482 if (!vim_is_ctrl_x_key(c))
2483 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002484 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002485 ctrl_x_mode = CTRL_X_NORMAL;
2486 else
2487 ctrl_x_mode = CTRL_X_FINISHED;
2488 edit_submode = NULL;
2489 }
2490 showmode();
2491 }
2492
2493 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2494 {
2495 // Show error message from attempted keyword completion (probably
2496 // 'Pattern not found') until another key is hit, then go back to
2497 // showing what mode we are in.
2498 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002499 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002500 && c != Ctrl_R && !ins_compl_pum_key(c))
2501 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002502 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002503 }
2504 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2505 // Trigger the CompleteDone event to give scripts a chance to act
2506 // upon the (possibly failed) completion.
2507 ins_apply_autocmds(EVENT_COMPLETEDONE);
2508
LemonBoy2bf52dd2022-04-09 18:17:34 +01002509 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002510
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002511 // reset continue_* if we left expansion-mode, if we stay they'll be
2512 // (re)set properly in ins_complete()
2513 if (!vim_is_ctrl_x_key(c))
2514 {
2515 compl_cont_status = 0;
2516 compl_cont_mode = 0;
2517 }
2518
2519 return retval;
2520}
2521
2522/*
2523 * Fix the redo buffer for the completion leader replacing some of the typed
2524 * text. This inserts backspaces and appends the changed text.
2525 * "ptr" is the known leader text or NUL.
2526 */
2527 static void
2528ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2529{
2530 int len;
2531 char_u *p;
2532 char_u *ptr = ptr_arg;
2533
2534 if (ptr == NULL)
2535 {
2536 if (compl_leader != NULL)
2537 ptr = compl_leader;
2538 else
2539 return; // nothing to do
2540 }
2541 if (compl_orig_text != NULL)
2542 {
2543 p = compl_orig_text;
2544 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2545 ;
2546 if (len > 0)
2547 len -= (*mb_head_off)(p, p + len);
2548 for (p += len; *p != NUL; MB_PTR_ADV(p))
2549 AppendCharToRedobuff(K_BS);
2550 }
2551 else
2552 len = 0;
2553 if (ptr != NULL)
2554 AppendToRedobuffLit(ptr + len, -1);
2555}
2556
2557/*
2558 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2559 * (depending on flag) starting from buf and looking for a non-scanned
2560 * buffer (other than curbuf). curbuf is special, if it is called with
2561 * buf=curbuf then it has to be the first call for a given flag/expansion.
2562 *
2563 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2564 */
2565 static buf_T *
2566ins_compl_next_buf(buf_T *buf, int flag)
2567{
2568 static win_T *wp = NULL;
2569
2570 if (flag == 'w') // just windows
2571 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002572 if (buf == curbuf || !win_valid(wp))
2573 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002574 wp = curwin;
2575 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2576 && wp->w_buffer->b_scanned)
2577 ;
2578 buf = wp->w_buffer;
2579 }
2580 else
2581 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2582 // (unlisted buffers)
2583 // When completing whole lines skip unloaded buffers.
2584 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2585 && ((flag == 'U'
2586 ? buf->b_p_bl
2587 : (!buf->b_p_bl
2588 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2589 || buf->b_scanned))
2590 ;
2591 return buf;
2592}
2593
2594#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002595
2596# ifdef FEAT_EVAL
2597static callback_T cfu_cb; // 'completefunc' callback function
2598static callback_T ofu_cb; // 'omnifunc' callback function
2599static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2600# endif
2601
2602/*
2603 * Copy a global callback function to a buffer local callback.
2604 */
2605 static void
2606copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2607{
2608 free_callback(bufcb);
2609 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2610 copy_callback(bufcb, globcb);
2611}
2612
2613/*
2614 * Parse the 'completefunc' option value and set the callback function.
2615 * Invoked when the 'completefunc' option is set. The option value can be a
2616 * name of a function (string), or function(<name>) or funcref(<name>) or a
2617 * lambda expression.
2618 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002619 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002620did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002621{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002622 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2623 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002624
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002625 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002626
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002627 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002628}
2629
2630/*
2631 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002632 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002633 */
2634 void
2635set_buflocal_cfu_callback(buf_T *buf UNUSED)
2636{
2637# ifdef FEAT_EVAL
2638 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2639# endif
2640}
2641
2642/*
2643 * Parse the 'omnifunc' option value and set the callback function.
2644 * Invoked when the 'omnifunc' option is set. The option value can be a
2645 * name of a function (string), or function(<name>) or funcref(<name>) or a
2646 * lambda expression.
2647 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002648 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002649did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002650{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002651 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2652 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002653
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002654 set_buflocal_ofu_callback(curbuf);
2655 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002656}
2657
2658/*
2659 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002660 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002661 */
2662 void
2663set_buflocal_ofu_callback(buf_T *buf UNUSED)
2664{
2665# ifdef FEAT_EVAL
2666 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2667# endif
2668}
2669
2670/*
2671 * Parse the 'thesaurusfunc' option value and set the callback function.
2672 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2673 * name of a function (string), or function(<name>) or funcref(<name>) or a
2674 * lambda expression.
2675 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002676 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002677did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002678{
2679 int retval;
2680
2681 if (*curbuf->b_p_tsrfu != NUL)
2682 {
2683 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002684 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2685 &curbuf->b_tsrfu_cb);
2686 }
2687 else
2688 {
2689 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002690 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2691 }
2692
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002693 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002694}
2695
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002696/*
2697 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002698 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002699 */
2700 int
2701set_ref_in_insexpand_funcs(int copyID)
2702{
2703 int abort = FALSE;
2704
2705 abort = set_ref_in_callback(&cfu_cb, copyID);
2706 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2707 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2708
2709 return abort;
2710}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002711
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002712/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002713 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002714 */
2715 static char_u *
2716get_complete_funcname(int type)
2717{
2718 switch (type)
2719 {
2720 case CTRL_X_FUNCTION:
2721 return curbuf->b_p_cfu;
2722 case CTRL_X_OMNI:
2723 return curbuf->b_p_ofu;
2724 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002725 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002726 default:
2727 return (char_u *)"";
2728 }
2729}
2730
2731/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002732 * Get the callback to use for insert mode completion.
2733 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002734 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002735get_insert_callback(int type)
2736{
2737 if (type == CTRL_X_FUNCTION)
2738 return &curbuf->b_cfu_cb;
2739 if (type == CTRL_X_OMNI)
2740 return &curbuf->b_ofu_cb;
2741 // CTRL_X_THESAURUS
2742 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2743}
2744
2745/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002746 * Execute user defined complete function 'completefunc', 'omnifunc' or
2747 * 'thesaurusfunc', and get matches in "matches".
2748 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002749 */
2750 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002751expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002752{
2753 list_T *matchlist = NULL;
2754 dict_T *matchdict = NULL;
2755 typval_T args[3];
2756 char_u *funcname;
2757 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002758 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002759 typval_T rettv;
2760 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002761 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002762
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002763 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002764 if (*funcname == NUL)
2765 return;
2766
2767 // Call 'completefunc' to obtain the list of matches.
2768 args[0].v_type = VAR_NUMBER;
2769 args[0].vval.v_number = 0;
2770 args[1].v_type = VAR_STRING;
2771 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2772 args[2].v_type = VAR_UNKNOWN;
2773
2774 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002775 // Lock the text to avoid weird things from happening. Also disallow
2776 // switching to another window, it should not be needed and may end up in
2777 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002778 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002779
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002780 cb = get_insert_callback(type);
2781 retval = call_callback(cb, 0, &rettv, 2, args);
2782
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002783 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002784 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002785 {
2786 switch (rettv.v_type)
2787 {
2788 case VAR_LIST:
2789 matchlist = rettv.vval.v_list;
2790 break;
2791 case VAR_DICT:
2792 matchdict = rettv.vval.v_dict;
2793 break;
2794 case VAR_SPECIAL:
2795 if (rettv.vval.v_number == VVAL_NONE)
2796 compl_opt_suppress_empty = TRUE;
2797 // FALLTHROUGH
2798 default:
2799 // TODO: Give error message?
2800 clear_tv(&rettv);
2801 break;
2802 }
2803 }
zeertzjqcfe45652022-05-27 17:26:55 +01002804 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002805
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002806 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002807 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002808 validate_cursor();
2809 if (!EQUAL_POS(curwin->w_cursor, pos))
2810 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002811 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002812 goto theend;
2813 }
2814
2815 if (matchlist != NULL)
2816 ins_compl_add_list(matchlist);
2817 else if (matchdict != NULL)
2818 ins_compl_add_dict(matchdict);
2819
2820theend:
2821 // Restore State, it might have been changed.
2822 State = save_State;
2823
2824 if (matchdict != NULL)
2825 dict_unref(matchdict);
2826 if (matchlist != NULL)
2827 list_unref(matchlist);
2828}
2829#endif // FEAT_COMPL_FUNC
2830
2831#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2832/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002833 * Add a match to the list of matches from a typeval_T.
2834 * If the given string is already in the list of completions, then return
2835 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2836 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002837 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002838 */
2839 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002840ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002841{
2842 char_u *word;
2843 int dup = FALSE;
2844 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002845 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002846 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002847 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002848 int status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002849
Bram Moolenaar08928322020-01-04 14:32:48 +01002850 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002851 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2852 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002853 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2854 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2855 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2856 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2857 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
2858 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2859 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2860 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002861 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002862 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2863 dup = dict_get_number(tv->vval.v_dict, "dup");
2864 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2865 empty = dict_get_number(tv->vval.v_dict, "empty");
2866 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2867 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002868 flags |= CP_EQUAL;
2869 }
2870 else
2871 {
2872 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002873 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002874 }
2875 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002876 {
2877 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002878 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002879 }
2880 status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
2881 if (status != OK)
2882 clear_tv(&user_data);
2883 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002884}
2885
2886/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002887 * Add completions from a list.
2888 */
2889 static void
2890ins_compl_add_list(list_T *list)
2891{
2892 listitem_T *li;
2893 int dir = compl_direction;
2894
2895 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002896 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002897 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002898 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002899 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002900 // if dir was BACKWARD then honor it just once
2901 dir = FORWARD;
2902 else if (did_emsg)
2903 break;
2904 }
2905}
2906
2907/*
2908 * Add completions from a dict.
2909 */
2910 static void
2911ins_compl_add_dict(dict_T *dict)
2912{
2913 dictitem_T *di_refresh;
2914 dictitem_T *di_words;
2915
2916 // Check for optional "refresh" item.
2917 compl_opt_refresh_always = FALSE;
2918 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2919 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2920 {
2921 char_u *v = di_refresh->di_tv.vval.v_string;
2922
2923 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2924 compl_opt_refresh_always = TRUE;
2925 }
2926
2927 // Add completions from a "words" list.
2928 di_words = dict_find(dict, (char_u *)"words", 5);
2929 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2930 ins_compl_add_list(di_words->di_tv.vval.v_list);
2931}
2932
2933/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002934 * Start completion for the complete() function.
2935 * "startcol" is where the matched text starts (1 is first column).
2936 * "list" is the list of matches.
2937 */
2938 static void
2939set_completion(colnr_T startcol, list_T *list)
2940{
2941 int save_w_wrow = curwin->w_wrow;
2942 int save_w_leftcol = curwin->w_leftcol;
2943 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002944 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002945 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2946 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2947 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002948
2949 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002950 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002951 ins_compl_prep(' ');
2952 ins_compl_clear();
2953 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002954 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002955
2956 compl_direction = FORWARD;
2957 if (startcol > curwin->w_cursor.col)
2958 startcol = curwin->w_cursor.col;
2959 compl_col = startcol;
2960 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2961 // compl_pattern doesn't need to be set
2962 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2963 if (p_ic)
2964 flags |= CP_ICASE;
2965 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002966 -1, NULL, NULL, NULL, 0,
2967 flags | CP_FAST, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002968 return;
2969
2970 ctrl_x_mode = CTRL_X_EVAL;
2971
2972 ins_compl_add_list(list);
2973 compl_matches = ins_compl_make_cyclic();
2974 compl_started = TRUE;
2975 compl_used_match = TRUE;
2976 compl_cont_status = 0;
2977
2978 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01002979 int no_select = compl_no_select || compl_longest;
2980 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002981 {
2982 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01002983 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002984 // Down/Up has no real effect.
2985 ins_complete(K_UP, FALSE);
2986 }
2987 else
2988 ins_complete(Ctrl_N, FALSE);
2989 compl_enter_selects = compl_no_insert;
2990
2991 // Lazily show the popup menu, unless we got interrupted.
2992 if (!compl_interrupted)
2993 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01002994 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002995 out_flush();
2996}
2997
2998/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002999 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003000 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003001 void
3002f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003003{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003004 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003005
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003006 if (in_vim9script()
3007 && (check_for_number_arg(argvars, 0) == FAIL
3008 || check_for_list_arg(argvars, 1) == FAIL))
3009 return;
3010
Bram Moolenaar24959102022-05-07 20:01:16 +01003011 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003012 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003013 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003014 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003015 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003016
3017 // Check for undo allowed here, because if something was already inserted
3018 // the line was already saved for undo and this check isn't done.
3019 if (!undo_allowed())
3020 return;
3021
Bram Moolenaard83392a2022-09-01 12:22:46 +01003022 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003023 {
3024 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3025 if (startcol > 0)
3026 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003027 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003028}
3029
3030/*
3031 * "complete_add()" function
3032 */
3033 void
3034f_complete_add(typval_T *argvars, typval_T *rettv)
3035{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003036 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003037 return;
3038
Bram Moolenaar440cf092021-04-03 20:13:30 +02003039 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003040}
3041
3042/*
3043 * "complete_check()" function
3044 */
3045 void
3046f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3047{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003048 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003049 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003050
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003051 ins_compl_check_keys(0, TRUE);
3052 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003053
3054 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003055}
3056
3057/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003058 * Return Insert completion mode name string
3059 */
3060 static char_u *
3061ins_compl_mode(void)
3062{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003063 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003064 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3065
3066 return (char_u *)"";
3067}
3068
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003069/*
3070 * Assign the sequence number to all the completion matches which don't have
3071 * one assigned yet.
3072 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003073 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003074ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003075{
3076 int number = 0;
3077 compl_T *match;
3078
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003079 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003080 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003081 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003082 // This should normally succeed already at the first loop
3083 // cycle, so it's fast!
3084 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003085 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003086 if (match->cp_number != -1)
3087 {
3088 number = match->cp_number;
3089 break;
3090 }
3091 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003092 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003093 for (match = match->cp_next;
3094 match != NULL && match->cp_number == -1;
3095 match = match->cp_next)
3096 match->cp_number = ++number;
3097 }
3098 else // BACKWARD
3099 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003100 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003101 // number. This should normally succeed already at the
3102 // first loop cycle, so it's fast!
3103 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003104 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003105 if (match->cp_number != -1)
3106 {
3107 number = match->cp_number;
3108 break;
3109 }
3110 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003111 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003112 for (match = match->cp_prev; match
3113 && match->cp_number == -1;
3114 match = match->cp_prev)
3115 match->cp_number = ++number;
3116 }
3117}
3118
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003119/*
3120 * Get complete information
3121 */
3122 static void
3123get_complete_info(list_T *what_list, dict_T *retdict)
3124{
3125 int ret = OK;
3126 listitem_T *item;
3127#define CI_WHAT_MODE 0x01
3128#define CI_WHAT_PUM_VISIBLE 0x02
3129#define CI_WHAT_ITEMS 0x04
3130#define CI_WHAT_SELECTED 0x08
3131#define CI_WHAT_INSERTED 0x10
3132#define CI_WHAT_ALL 0xff
3133 int what_flag;
3134
3135 if (what_list == NULL)
3136 what_flag = CI_WHAT_ALL;
3137 else
3138 {
3139 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003140 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003141 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003142 {
3143 char_u *what = tv_get_string(&item->li_tv);
3144
3145 if (STRCMP(what, "mode") == 0)
3146 what_flag |= CI_WHAT_MODE;
3147 else if (STRCMP(what, "pum_visible") == 0)
3148 what_flag |= CI_WHAT_PUM_VISIBLE;
3149 else if (STRCMP(what, "items") == 0)
3150 what_flag |= CI_WHAT_ITEMS;
3151 else if (STRCMP(what, "selected") == 0)
3152 what_flag |= CI_WHAT_SELECTED;
3153 else if (STRCMP(what, "inserted") == 0)
3154 what_flag |= CI_WHAT_INSERTED;
3155 }
3156 }
3157
3158 if (ret == OK && (what_flag & CI_WHAT_MODE))
3159 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3160
3161 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3162 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3163
Girish Palya8950bf72024-03-20 20:07:29 +01003164 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003165 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003166 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003167 dict_T *di;
3168 compl_T *match;
3169 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003170
Girish Palya8950bf72024-03-20 20:07:29 +01003171 if (what_flag & CI_WHAT_ITEMS)
3172 {
3173 li = list_alloc();
3174 if (li == NULL)
3175 return;
3176 ret = dict_add_list(retdict, "items", li);
3177 }
3178 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3179 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3180 ins_compl_update_sequence_numbers();
3181 if (ret == OK && compl_first_match != NULL)
3182 {
3183 int list_idx = 0;
3184 match = compl_first_match;
3185 do
3186 {
3187 if (!match_at_original_text(match))
3188 {
3189 if (what_flag & CI_WHAT_ITEMS)
3190 {
3191 di = dict_alloc();
3192 if (di == NULL)
3193 return;
3194 ret = list_append_dict(li, di);
3195 if (ret != OK)
3196 return;
3197 dict_add_string(di, "word", match->cp_str);
3198 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3199 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3200 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3201 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3202 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3203 // Add an empty string for backwards compatibility
3204 dict_add_string(di, "user_data", (char_u *)"");
3205 else
3206 dict_add_tv(di, "user_data", &match->cp_user_data);
3207 }
3208 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3209 selected_idx = list_idx;
3210 list_idx += 1;
3211 }
3212 match = match->cp_next;
3213 }
3214 while (match != NULL && !is_first_match(match));
3215 }
3216 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3217 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003218 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003219
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003220 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3221 {
3222 // TODO
3223 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003224}
3225
3226/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003227 * "complete_info()" function
3228 */
3229 void
3230f_complete_info(typval_T *argvars, typval_T *rettv)
3231{
3232 list_T *what_list = NULL;
3233
Bram Moolenaar93a10962022-06-16 11:42:09 +01003234 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003235 return;
3236
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003237 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3238 return;
3239
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003240 if (argvars[0].v_type != VAR_UNKNOWN)
3241 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003242 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003243 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003244 what_list = argvars[0].vval.v_list;
3245 }
3246 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003247}
3248#endif
3249
3250/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003251 * Returns TRUE when using a user-defined function for thesaurus completion.
3252 */
3253 static int
3254thesaurus_func_complete(int type UNUSED)
3255{
3256#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003257 return type == CTRL_X_THESAURUS
3258 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003259#else
3260 return FALSE;
3261#endif
3262}
3263
3264/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003265 * Return value of process_next_cpt_value()
3266 */
3267enum
3268{
3269 INS_COMPL_CPT_OK = 1,
3270 INS_COMPL_CPT_CONT,
3271 INS_COMPL_CPT_END
3272};
3273
3274/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003275 * state information used for getting the next set of insert completion
3276 * matches.
3277 */
3278typedef struct
3279{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003280 char_u *e_cpt_copy; // copy of 'complete'
3281 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003282 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003283 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003284 pos_T prev_match_pos; // previous match position
3285 int set_match_pos; // save first_match_pos/last_match_pos
3286 pos_T first_match_pos; // first match position
3287 pos_T last_match_pos; // last match position
3288 int found_all; // found all matches of a certain type.
3289 char_u *dict; // dictionary file to search
3290 int dict_f; // "dict" is an exact file name or not
3291} ins_compl_next_state_T;
3292
3293/*
3294 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003295 *
3296 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003297 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003298 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003299 * st->found_all - all matches of this type are found
3300 * st->ins_buf - search for completions in this buffer
3301 * st->first_match_pos - position of the first completion match
3302 * st->last_match_pos - position of the last completion match
3303 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003304 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003305 * st->dict - name of the dictionary or thesaurus file to search
3306 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003307 *
3308 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003309 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3310 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003311 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003312 */
3313 static int
3314process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003315 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003316 int *compl_type_arg,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003317 pos_T *start_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003318{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003319 int compl_type = -1;
3320 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003321
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003322 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003323
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003324 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3325 st->e_cpt++;
3326
3327 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003328 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003329 st->ins_buf = curbuf;
3330 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003331 // Move the cursor back one character so that ^N can match the
3332 // word immediately after the cursor.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003333 if (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003334 {
3335 // Move the cursor to after the last character in the
3336 // buffer, so that word at start of buffer is found
3337 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003338 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003339 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003340 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003341 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003342 compl_type = 0;
3343
3344 // Remember the first match so that the loop stops when we
3345 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003346 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003347 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003348 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003349 && (st->ins_buf = ins_compl_next_buf(
3350 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003351 {
3352 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003353 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003354 {
3355 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003356 st->first_match_pos.col = st->last_match_pos.col = 0;
3357 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3358 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003359 compl_type = 0;
3360 }
3361 else // unloaded buffer, scan like dictionary
3362 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003363 st->found_all = TRUE;
3364 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003365 {
3366 status = INS_COMPL_CPT_CONT;
3367 goto done;
3368 }
3369 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003370 st->dict = st->ins_buf->b_fname;
3371 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003372 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003373 if (!shortmess(SHM_COMPLETIONSCAN))
3374 {
3375 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3376 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3377 st->ins_buf->b_fname == NULL
3378 ? buf_spname(st->ins_buf)
3379 : st->ins_buf->b_sfname == NULL
3380 ? st->ins_buf->b_fname
3381 : st->ins_buf->b_sfname);
3382 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3383 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003384 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003385 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003386 status = INS_COMPL_CPT_END;
3387 else
3388 {
3389 if (ctrl_x_mode_line_or_eval())
3390 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003391 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003392 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003393 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394 compl_type = CTRL_X_DICTIONARY;
3395 else
3396 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003397 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003398 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003399 st->dict = st->e_cpt;
3400 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003401 }
3402 }
3403#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003404 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003405 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003406 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003407 compl_type = CTRL_X_PATH_DEFINES;
3408#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003409 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003410 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003411 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003412 if (!shortmess(SHM_COMPLETIONSCAN))
3413 {
3414 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3415 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3416 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3417 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003418 }
3419 else
3420 compl_type = -1;
3421
3422 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003423 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003424
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003425 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003426 if (compl_type == -1)
3427 status = INS_COMPL_CPT_CONT;
3428 }
3429
3430done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003431 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003432 return status;
3433}
3434
3435#ifdef FEAT_FIND_ID
3436/*
3437 * Get the next set of identifiers or defines matching "compl_pattern" in
3438 * included files.
3439 */
3440 static void
3441get_next_include_file_completion(int compl_type)
3442{
3443 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003444 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003445 (compl_type == CTRL_X_PATH_DEFINES
3446 && !(compl_cont_status & CONT_SOL))
3447 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003448 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003449}
3450#endif
3451
3452/*
3453 * Get the next set of words matching "compl_pattern" in dictionary or
3454 * thesaurus files.
3455 */
3456 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003457get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003458{
3459#ifdef FEAT_COMPL_FUNC
3460 if (thesaurus_func_complete(compl_type))
3461 expand_by_function(compl_type, compl_pattern);
3462 else
3463#endif
3464 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003465 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003466 : (compl_type == CTRL_X_THESAURUS
3467 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3468 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3469 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003470 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003471 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003472}
3473
3474/*
3475 * Get the next set of tag names matching "compl_pattern".
3476 */
3477 static void
3478get_next_tag_completion(void)
3479{
3480 int save_p_ic;
3481 char_u **matches;
3482 int num_matches;
3483
3484 // set p_ic according to p_ic, p_scs and pat for find_tags().
3485 save_p_ic = p_ic;
3486 p_ic = ignorecase(compl_pattern);
3487
3488 // Find up to TAG_MANY matches. Avoids that an enormous number
3489 // of matches is found when compl_pattern is empty
3490 g_tag_at_cursor = TRUE;
3491 if (find_tags(compl_pattern, &num_matches, &matches,
3492 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003493 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003494 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3495 ins_compl_add_matches(num_matches, matches, p_ic);
3496 g_tag_at_cursor = FALSE;
3497 p_ic = save_p_ic;
3498}
3499
3500/*
3501 * Get the next set of filename matching "compl_pattern".
3502 */
3503 static void
3504get_next_filename_completion(void)
3505{
3506 char_u **matches;
3507 int num_matches;
3508
3509 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3510 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3511 return;
3512
3513 // May change home directory back to "~".
3514 tilde_replace(compl_pattern, num_matches, matches);
3515#ifdef BACKSLASH_IN_FILENAME
3516 if (curbuf->b_p_csl[0] != NUL)
3517 {
3518 int i;
3519
3520 for (i = 0; i < num_matches; ++i)
3521 {
3522 char_u *ptr = matches[i];
3523
3524 while (*ptr != NUL)
3525 {
3526 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3527 *ptr = '/';
3528 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3529 *ptr = '\\';
3530 ptr += (*mb_ptr2len)(ptr);
3531 }
3532 }
3533 }
3534#endif
3535 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
3536}
3537
3538/*
3539 * Get the next set of command-line completions matching "compl_pattern".
3540 */
3541 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003542get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003543{
3544 char_u **matches;
3545 int num_matches;
3546
3547 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003548 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003549 ins_compl_add_matches(num_matches, matches, FALSE);
3550}
3551
3552/*
3553 * Get the next set of spell suggestions matching "compl_pattern".
3554 */
3555 static void
3556get_next_spell_completion(linenr_T lnum UNUSED)
3557{
3558#ifdef FEAT_SPELL
3559 char_u **matches;
3560 int num_matches;
3561
3562 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3563 if (num_matches > 0)
3564 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003565 else
3566 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003567#endif
3568}
3569
3570/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003571 * Return the next word or line from buffer "ins_buf" at position
3572 * "cur_match_pos" for completion. The length of the match is set in "len".
3573 */
3574 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003575ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003576 buf_T *ins_buf, // buffer being scanned
3577 pos_T *cur_match_pos, // current match position
3578 int *match_len,
3579 int *cont_s_ipos) // next ^X<> will set initial_pos
3580{
3581 char_u *ptr;
3582 int len;
3583
3584 *match_len = 0;
3585 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3586 cur_match_pos->col;
3587 if (ctrl_x_mode_line_or_eval())
3588 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003589 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003590 {
3591 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3592 return NULL;
3593 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3594 if (!p_paste)
3595 ptr = skipwhite(ptr);
3596 }
3597 len = (int)STRLEN(ptr);
3598 }
3599 else
3600 {
3601 char_u *tmp_ptr = ptr;
3602
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003603 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003604 {
3605 tmp_ptr += compl_length;
3606 // Skip if already inside a word.
3607 if (vim_iswordp(tmp_ptr))
3608 return NULL;
3609 // Find start of next word.
3610 tmp_ptr = find_word_start(tmp_ptr);
3611 }
3612 // Find end of this word.
3613 tmp_ptr = find_word_end(tmp_ptr);
3614 len = (int)(tmp_ptr - ptr);
3615
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003616 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003617 {
3618 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3619 {
3620 // Try next line, if any. the new word will be
3621 // "join" as if the normal command "J" was used.
3622 // IOSIZE is always greater than
3623 // compl_length, so the next STRNCPY always
3624 // works -- Acevedo
3625 STRNCPY(IObuff, ptr, len);
3626 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3627 tmp_ptr = ptr = skipwhite(ptr);
3628 // Find start of next word.
3629 tmp_ptr = find_word_start(tmp_ptr);
3630 // Find end of next word.
3631 tmp_ptr = find_word_end(tmp_ptr);
3632 if (tmp_ptr > ptr)
3633 {
3634 if (*ptr != ')' && IObuff[len - 1] != TAB)
3635 {
3636 if (IObuff[len - 1] != ' ')
3637 IObuff[len++] = ' ';
3638 // IObuf =~ "\k.* ", thus len >= 2
3639 if (p_js
3640 && (IObuff[len - 2] == '.'
3641 || (vim_strchr(p_cpo, CPO_JOINSP)
3642 == NULL
3643 && (IObuff[len - 2] == '?'
3644 || IObuff[len - 2] == '!'))))
3645 IObuff[len++] = ' ';
3646 }
3647 // copy as much as possible of the new word
3648 if (tmp_ptr - ptr >= IOSIZE - len)
3649 tmp_ptr = ptr + IOSIZE - len - 1;
3650 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3651 len += (int)(tmp_ptr - ptr);
3652 *cont_s_ipos = TRUE;
3653 }
3654 IObuff[len] = NUL;
3655 ptr = IObuff;
3656 }
3657 if (len == compl_length)
3658 return NULL;
3659 }
3660 }
3661
3662 *match_len = len;
3663 return ptr;
3664}
3665
3666/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003667 * Get the next set of words matching "compl_pattern" for default completion(s)
3668 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003669 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3670 * position "st->start_pos" in the "compl_direction" direction. If
3671 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3672 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003673 * Returns OK if a new next match is found, otherwise returns FAIL.
3674 */
3675 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003676get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003677{
3678 int found_new_match = FAIL;
3679 int save_p_scs;
3680 int save_p_ws;
3681 int looped_around = FALSE;
3682 char_u *ptr;
3683 int len;
3684
3685 // If 'infercase' is set, don't use 'smartcase' here
3686 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003687 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003688 p_scs = FALSE;
3689
3690 // Buffers other than curbuf are scanned from the beginning or the
3691 // end but never from the middle, thus setting nowrapscan in this
3692 // buffer is a good idea, on the other hand, we always set
3693 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3694 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003695 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003696 p_ws = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003697 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003698 p_ws = TRUE;
3699 looped_around = FALSE;
3700 for (;;)
3701 {
3702 int cont_s_ipos = FALSE;
3703
3704 ++msg_silent; // Don't want messages for wrapscan.
3705
3706 // ctrl_x_mode_line_or_eval() || word-wise search that
3707 // has added a word that was at the beginning of the line
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003708 if (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003709 found_new_match = search_for_exact_line(st->ins_buf,
3710 st->cur_match_pos, compl_direction, compl_pattern);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003711 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003712 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003713 NULL, compl_direction, compl_pattern, compl_patternlen,
3714 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003715 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003716 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003717 {
3718 // set "compl_started" even on fail
3719 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003720 st->first_match_pos = *st->cur_match_pos;
3721 st->last_match_pos = *st->cur_match_pos;
3722 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003723 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003724 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3725 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003726 {
3727 found_new_match = FAIL;
3728 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003729 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003730 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3731 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3732 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003733 {
3734 if (looped_around)
3735 found_new_match = FAIL;
3736 else
3737 looped_around = TRUE;
3738 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003739 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003740 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3741 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3742 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003743 {
3744 if (looped_around)
3745 found_new_match = FAIL;
3746 else
3747 looped_around = TRUE;
3748 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003749 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003750 if (found_new_match == FAIL)
3751 break;
3752
3753 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003754 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003755 && start_pos->lnum == st->cur_match_pos->lnum
3756 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003757 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003758
zeertzjq440d4cb2023-03-02 17:51:32 +00003759 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3760 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003761 if (ptr == NULL)
3762 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003763
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003764 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003765 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003766 0, cont_s_ipos) != NOTDONE)
3767 {
3768 found_new_match = OK;
3769 break;
3770 }
3771 }
3772 p_scs = save_p_scs;
3773 p_ws = save_p_ws;
3774
3775 return found_new_match;
3776}
3777
3778/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003779 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003780 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003781 */
3782 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003783get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003784{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003785 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003786
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003787 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003788 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003789 case -1:
3790 break;
3791#ifdef FEAT_FIND_ID
3792 case CTRL_X_PATH_PATTERNS:
3793 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003794 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003795 break;
3796#endif
3797
3798 case CTRL_X_DICTIONARY:
3799 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003800 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3801 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003802 break;
3803
3804 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003805 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003806 break;
3807
3808 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003809 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003810 break;
3811
3812 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003813 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003814 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003815 break;
3816
3817#ifdef FEAT_COMPL_FUNC
3818 case CTRL_X_FUNCTION:
3819 case CTRL_X_OMNI:
3820 expand_by_function(type, compl_pattern);
3821 break;
3822#endif
3823
3824 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003825 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003826 break;
3827
3828 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003829 found_new_match = get_next_default_completion(st, ini);
3830 if (found_new_match == FAIL && st->ins_buf == curbuf)
3831 st->found_all = TRUE;
3832 }
3833
3834 // check if compl_curr_match has changed, (e.g. other type of
3835 // expansion added something)
3836 if (type != 0 && compl_curr_match != compl_old_match)
3837 found_new_match = OK;
3838
3839 return found_new_match;
3840}
3841
3842/*
3843 * Get the next expansion(s), using "compl_pattern".
3844 * The search starts at position "ini" in curbuf and in the direction
3845 * compl_direction.
3846 * When "compl_started" is FALSE start at that position, otherwise continue
3847 * where we stopped searching before.
3848 * This may return before finding all the matches.
3849 * Return the total number of matches or -1 if still unknown -- Acevedo
3850 */
3851 static int
3852ins_compl_get_exp(pos_T *ini)
3853{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003854 static ins_compl_next_state_T st;
3855 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003856 int i;
3857 int found_new_match;
3858 int type = ctrl_x_mode;
3859
3860 if (!compl_started)
3861 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003862 buf_T *buf;
3863
3864 FOR_ALL_BUFFERS(buf)
3865 buf->b_scanned = 0;
3866 if (!st_cleared)
3867 {
3868 CLEAR_FIELD(st);
3869 st_cleared = TRUE;
3870 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003871 st.found_all = FALSE;
3872 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003873 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003874 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003875 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
3876 ? (char_u *)"." : curbuf->b_p_cpt);
3877 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003878 st.last_match_pos = st.first_match_pos = *ini;
3879 }
3880 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
3881 st.ins_buf = curbuf; // In case the buffer was wiped out.
3882
3883 compl_old_match = compl_curr_match; // remember the last current match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003884 st.cur_match_pos = (compl_dir_forward())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003885 ? &st.last_match_pos : &st.first_match_pos;
3886
3887 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
3888 for (;;)
3889 {
3890 found_new_match = FAIL;
3891 st.set_match_pos = FALSE;
3892
3893 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
3894 // or if found_all says this entry is done. For ^X^L only use the
3895 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003896 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003897 && (!compl_started || st.found_all))
3898 {
3899 int status = process_next_cpt_value(&st, &type, ini);
3900
3901 if (status == INS_COMPL_CPT_END)
3902 break;
3903 if (status == INS_COMPL_CPT_CONT)
3904 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003905 }
3906
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003907 // If complete() was called then compl_pattern has been reset. The
3908 // following won't work then, bail out.
3909 if (compl_pattern == NULL)
3910 break;
3911
3912 // get the next set of completion matches
3913 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003914
3915 // break the loop for specialized modes (use 'complete' just for the
3916 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3917 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003918 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
3919 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003920 {
3921 if (got_int)
3922 break;
3923 // Fill the popup menu as soon as possible.
3924 if (type != -1)
3925 ins_compl_check_keys(0, FALSE);
3926
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003927 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003928 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3929 break;
3930 compl_started = TRUE;
3931 }
3932 else
3933 {
3934 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02003935 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003936 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003937
3938 compl_started = FALSE;
3939 }
3940 }
3941 compl_started = TRUE;
3942
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003943 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003944 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003945 found_new_match = FAIL;
3946
3947 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003948 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003949 && !ctrl_x_mode_line_or_eval()))
3950 i = ins_compl_make_cyclic();
3951
3952 if (compl_old_match != NULL)
3953 {
3954 // If several matches were added (FORWARD) or the search failed and has
3955 // just been made cyclic then we have to move compl_curr_match to the
3956 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003957 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003958 : compl_old_match->cp_prev;
3959 if (compl_curr_match == NULL)
3960 compl_curr_match = compl_old_match;
3961 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01003962 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003963
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003964 return i;
3965}
3966
3967/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003968 * Update "compl_shown_match" to the actually shown match, it may differ when
3969 * "compl_leader" is used to omit some of the matches.
3970 */
3971 static void
3972ins_compl_update_shown_match(void)
3973{
3974 while (!ins_compl_equal(compl_shown_match,
3975 compl_leader, (int)STRLEN(compl_leader))
3976 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003977 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003978 compl_shown_match = compl_shown_match->cp_next;
3979
3980 // If we didn't find it searching forward, and compl_shows_dir is
3981 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003982 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003983 && !ins_compl_equal(compl_shown_match,
3984 compl_leader, (int)STRLEN(compl_leader))
3985 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003986 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003987 {
3988 while (!ins_compl_equal(compl_shown_match,
3989 compl_leader, (int)STRLEN(compl_leader))
3990 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003991 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003992 compl_shown_match = compl_shown_match->cp_prev;
3993 }
3994}
3995
3996/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003997 * Delete the old text being completed.
3998 */
3999 void
4000ins_compl_delete(void)
4001{
4002 int col;
4003
4004 // In insert mode: Delete the typed part.
4005 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004006 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004007 if ((int)curwin->w_cursor.col > col)
4008 {
4009 if (stop_arrow() == FAIL)
4010 return;
4011 backspace_until_column(col);
4012 }
4013
4014 // TODO: is this sufficient for redrawing? Redrawing everything causes
4015 // flicker, thus we can't do that.
4016 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004017#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004018 // clear v:completed_item
4019 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004020#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004021}
4022
4023/*
4024 * Insert the new text being completed.
4025 * "in_compl_func" is TRUE when called from complete_check().
4026 */
4027 void
4028ins_compl_insert(int in_compl_func)
4029{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004030 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004031
4032 // Make sure we don't go over the end of the string, this can happen with
4033 // illegal bytes.
4034 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4035 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004036 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004037 compl_used_match = FALSE;
4038 else
4039 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004040#ifdef FEAT_EVAL
4041 {
4042 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4043
4044 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4045 }
4046#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004047 if (!in_compl_func)
4048 compl_curr_match = compl_shown_match;
4049}
4050
4051/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004052 * show the file name for the completion match (if any). Truncate the file
4053 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004054 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004055 static void
4056ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004057{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004058 char *lead = _("match in file");
4059 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4060 char_u *s;
4061 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004062
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004063 if (space <= 0)
4064 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004065
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004066 // We need the tail that fits. With double-byte encoding going
4067 // back from the end is very slow, thus go from the start and keep
4068 // the text that fits in "space" between "s" and "e".
4069 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004070 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004071 space -= ptr2cells(e);
4072 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004073 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004074 space += ptr2cells(s);
4075 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004076 }
4077 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004078 msg_hist_off = TRUE;
4079 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4080 s > compl_shown_match->cp_fname ? "<" : "", s);
4081 msg((char *)IObuff);
4082 msg_hist_off = FALSE;
4083 redraw_cmdline = FALSE; // don't overwrite!
4084}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004085
glepnirdca57fb2024-06-04 22:01:21 +02004086/*
zeertzjq551d8c32024-06-05 19:53:32 +02004087 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004088 */
glepnira218cc62024-06-03 19:32:39 +02004089 static compl_T *
4090find_comp_when_fuzzy(void)
4091{
4092 int score;
4093 char_u* str;
4094 int target_idx = -1;
4095 int is_forward = compl_shows_dir_forward();
4096 int is_backward = compl_shows_dir_backward();
4097 compl_T *comp = NULL;
4098
4099 if (compl_match_array == NULL ||
4100 (is_forward && compl_selected_item == compl_match_arraysize - 1)
4101 || (is_backward && compl_selected_item == 0))
4102 return compl_first_match;
4103
4104 if (is_forward)
4105 target_idx = compl_selected_item + 1;
4106 else if (is_backward)
4107 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004108 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004109
4110 score = compl_match_array[target_idx].pum_score;
4111 str = compl_match_array[target_idx].pum_text;
4112
4113 comp = compl_first_match;
4114 do {
4115 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4116 return comp;
4117 comp = comp->cp_next;
4118 } while (comp != NULL && !is_first_match(comp));
4119
4120 return NULL;
4121}
4122
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004123/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004124 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004125 * times. The number of matches found is returned in 'num_matches'.
4126 *
4127 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4128 * get more completions. If it is FALSE, then do nothing when there are no more
4129 * completions in the given direction.
4130 *
4131 * If "advance" is TRUE, then completion will move to the first match.
4132 * Otherwise, the original text will be shown.
4133 *
4134 * Returns OK on success and -1 if the number of matches are unknown.
4135 */
4136 static int
4137find_next_completion_match(
4138 int allow_get_expansion,
4139 int todo, // repeat completion this many times
4140 int advance,
4141 int *num_matches)
4142{
4143 int found_end = FALSE;
4144 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004145 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004146 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4147 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004148
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004149 while (--todo >= 0)
4150 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004151 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004152 {
glepnira218cc62024-06-03 19:32:39 +02004153 compl_shown_match = !compl_fuzzy_match ? compl_shown_match->cp_next
4154 : find_comp_when_fuzzy();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004155 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004156 && (is_first_match(compl_shown_match->cp_next)
4157 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004158 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004159 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004160 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004161 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004162 found_end = is_first_match(compl_shown_match);
glepnira218cc62024-06-03 19:32:39 +02004163 compl_shown_match = !compl_fuzzy_match ? compl_shown_match->cp_prev
4164 : find_comp_when_fuzzy();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004165 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004166 }
4167 else
4168 {
4169 if (!allow_get_expansion)
4170 {
4171 if (advance)
4172 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004173 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004174 compl_pending -= todo + 1;
4175 else
4176 compl_pending += todo + 1;
4177 }
4178 return -1;
4179 }
4180
4181 if (!compl_no_select && advance)
4182 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004183 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004184 --compl_pending;
4185 else
4186 ++compl_pending;
4187 }
4188
4189 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004190 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004191
4192 // handle any pending completions
4193 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004194 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004195 {
4196 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4197 {
4198 compl_shown_match = compl_shown_match->cp_next;
4199 --compl_pending;
4200 }
4201 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4202 {
4203 compl_shown_match = compl_shown_match->cp_prev;
4204 ++compl_pending;
4205 }
4206 else
4207 break;
4208 }
4209 found_end = FALSE;
4210 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004211 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004212 && compl_leader != NULL
4213 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004214 compl_leader, (int)STRLEN(compl_leader))
4215 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004216 ++todo;
4217 else
4218 // Remember a matching item.
4219 found_compl = compl_shown_match;
4220
4221 // Stop at the end of the list when we found a usable match.
4222 if (found_end)
4223 {
4224 if (found_compl != NULL)
4225 {
4226 compl_shown_match = found_compl;
4227 break;
4228 }
4229 todo = 1; // use first usable match after wrapping around
4230 }
4231 }
4232
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004233 return OK;
4234}
4235
4236/*
4237 * Fill in the next completion in the current direction.
4238 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4239 * get more completions. If it is FALSE, then we just do nothing when there
4240 * are no more completions in a given direction. The latter case is used when
4241 * we are still in the middle of finding completions, to allow browsing
4242 * through the ones found so far.
4243 * Return the total number of matches, or -1 if still unknown -- webb.
4244 *
4245 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4246 * compl_shown_match here.
4247 *
4248 * Note that this function may be called recursively once only. First with
4249 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4250 * calls this function with "allow_get_expansion" FALSE.
4251 */
4252 static int
4253ins_compl_next(
4254 int allow_get_expansion,
4255 int count, // repeat completion this many times; should
4256 // be at least 1
4257 int insert_match, // Insert the newly selected match
4258 int in_compl_func) // called from complete_check()
4259{
4260 int num_matches = -1;
4261 int todo = count;
4262 int advance;
4263 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004264 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004265 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004266 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4267 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004268
4269 // When user complete function return -1 for findstart which is next
4270 // time of 'always', compl_shown_match become NULL.
4271 if (compl_shown_match == NULL)
4272 return -1;
4273
glepnira218cc62024-06-03 19:32:39 +02004274 if (compl_leader != NULL
4275 && !match_at_original_text(compl_shown_match)
4276 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004277 // Update "compl_shown_match" to the actually shown match
4278 ins_compl_update_shown_match();
4279
4280 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004281 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004282 // Delete old text to be replaced
4283 ins_compl_delete();
4284
4285 // When finding the longest common text we stick at the original text,
4286 // don't let CTRL-N or CTRL-P move to the first match.
4287 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4288
4289 // When restarting the search don't insert the first match either.
4290 if (compl_restarting)
4291 {
4292 advance = FALSE;
4293 compl_restarting = FALSE;
4294 }
4295
4296 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4297 // around.
4298 if (find_next_completion_match(allow_get_expansion, todo, advance,
4299 &num_matches) == -1)
4300 return -1;
4301
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004302 if (curbuf != orig_curbuf)
4303 {
4304 // In case some completion function switched buffer, don't want to
4305 // insert the completion elsewhere.
4306 return -1;
4307 }
4308
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004309 // Insert the text of the new completion, or the compl_leader.
4310 if (compl_no_insert && !started)
4311 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004312 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004313 compl_used_match = FALSE;
4314 }
4315 else if (insert_match)
4316 {
4317 if (!compl_get_longest || compl_used_match)
4318 ins_compl_insert(in_compl_func);
4319 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004320 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004321 }
4322 else
4323 compl_used_match = FALSE;
4324
4325 if (!allow_get_expansion)
4326 {
4327 // may undisplay the popup menu first
4328 ins_compl_upd_pum();
4329
4330 if (pum_enough_matches())
4331 // Will display the popup menu, don't redraw yet to avoid flicker.
4332 pum_call_update_screen();
4333 else
4334 // Not showing the popup menu yet, redraw to show the user what was
4335 // inserted.
4336 update_screen(0);
4337
4338 // display the updated popup menu
4339 ins_compl_show_pum();
4340#ifdef FEAT_GUI
4341 if (gui.in_use)
4342 {
4343 // Show the cursor after the match, not after the redrawn text.
4344 setcursor();
4345 out_flush_cursor(FALSE, FALSE);
4346 }
4347#endif
4348
4349 // Delete old text to be replaced, since we're still searching and
4350 // don't want to match ourselves!
4351 ins_compl_delete();
4352 }
4353
4354 // Enter will select a match when the match wasn't inserted and the popup
4355 // menu is visible.
4356 if (compl_no_insert && !started)
4357 compl_enter_selects = TRUE;
4358 else
4359 compl_enter_selects = !insert_match && compl_match_array != NULL;
4360
4361 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004362 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004363 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004364
4365 return num_matches;
4366}
4367
4368/*
4369 * Call this while finding completions, to check whether the user has hit a key
4370 * that should change the currently displayed completion, or exit completion
4371 * mode. Also, when compl_pending is not zero, show a completion as soon as
4372 * possible. -- webb
4373 * "frequency" specifies out of how many calls we actually check.
4374 * "in_compl_func" is TRUE when called from complete_check(), don't set
4375 * compl_curr_match.
4376 */
4377 void
4378ins_compl_check_keys(int frequency, int in_compl_func)
4379{
4380 static int count = 0;
4381 int c;
4382
4383 // Don't check when reading keys from a script, :normal or feedkeys().
4384 // That would break the test scripts. But do check for keys when called
4385 // from complete_check().
4386 if (!in_compl_func && (using_script() || ex_normal_busy))
4387 return;
4388
4389 // Only do this at regular intervals
4390 if (++count < frequency)
4391 return;
4392 count = 0;
4393
4394 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4395 // can't do its work correctly.
4396 c = vpeekc_any();
4397 if (c != NUL)
4398 {
4399 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4400 {
4401 c = safe_vgetc(); // Eat the character
4402 compl_shows_dir = ins_compl_key2dir(c);
4403 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4404 c != K_UP && c != K_DOWN, in_compl_func);
4405 }
4406 else
4407 {
4408 // Need to get the character to have KeyTyped set. We'll put it
4409 // back with vungetc() below. But skip K_IGNORE.
4410 c = safe_vgetc();
4411 if (c != K_IGNORE)
4412 {
4413 // Don't interrupt completion when the character wasn't typed,
4414 // e.g., when doing @q to replay keys.
4415 if (c != Ctrl_R && KeyTyped)
4416 compl_interrupted = TRUE;
4417
4418 vungetc(c);
4419 }
4420 }
4421 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004422 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004423 {
4424 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4425
4426 compl_pending = 0;
4427 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4428 }
4429}
4430
4431/*
4432 * Decide the direction of Insert mode complete from the key typed.
4433 * Returns BACKWARD or FORWARD.
4434 */
4435 static int
4436ins_compl_key2dir(int c)
4437{
4438 if (c == Ctrl_P || c == Ctrl_L
4439 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4440 return BACKWARD;
4441 return FORWARD;
4442}
4443
4444/*
4445 * Return TRUE for keys that are used for completion only when the popup menu
4446 * is visible.
4447 */
4448 static int
4449ins_compl_pum_key(int c)
4450{
4451 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4452 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4453 || c == K_UP || c == K_DOWN);
4454}
4455
4456/*
4457 * Decide the number of completions to move forward.
4458 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4459 */
4460 static int
4461ins_compl_key2count(int c)
4462{
4463 int h;
4464
4465 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4466 {
4467 h = pum_get_height();
4468 if (h > 3)
4469 h -= 2; // keep some context
4470 return h;
4471 }
4472 return 1;
4473}
4474
4475/*
4476 * Return TRUE if completion with "c" should insert the match, FALSE if only
4477 * to change the currently selected completion.
4478 */
4479 static int
4480ins_compl_use_match(int c)
4481{
4482 switch (c)
4483 {
4484 case K_UP:
4485 case K_DOWN:
4486 case K_PAGEDOWN:
4487 case K_KPAGEDOWN:
4488 case K_S_DOWN:
4489 case K_PAGEUP:
4490 case K_KPAGEUP:
4491 case K_S_UP:
4492 return FALSE;
4493 }
4494 return TRUE;
4495}
4496
4497/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004498 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4499 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004500 * Sets the global variables: compl_col, compl_length, compl_pattern and
4501 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004502 * Uses the global variables: compl_cont_status and ctrl_x_mode
4503 */
4504 static int
4505get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4506{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004507 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004508 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004509 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004510 {
4511 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4512 ;
4513 compl_col += ++startcol;
4514 compl_length = curs_col - startcol;
4515 }
4516 if (p_ic)
4517 compl_pattern = str_foldcase(line + compl_col,
4518 compl_length, NULL, 0);
4519 else
4520 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4521 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004522 {
4523 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004524 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004525 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004526 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004527 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004528 {
4529 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004530 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004531
4532 // we need up to 2 extra chars for the prefix
4533 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004534 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004535 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004536 {
4537 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004538 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004539 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004540 if (!vim_iswordp(line + compl_col)
4541 || (compl_col > 0
4542 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004543 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004544 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004545 prefixlen = 0;
4546 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004547 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004548 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004549 line + compl_col, compl_length);
4550 }
4551 else if (--startcol < 0
4552 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4553 {
4554 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004555 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004556 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004557 {
4558 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004559 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004560 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004561 compl_col += curs_col;
4562 compl_length = 0;
4563 }
4564 else
4565 {
4566 // Search the point of change class of multibyte character
4567 // or not a word single byte character backward.
4568 if (has_mbyte)
4569 {
4570 int base_class;
4571 int head_off;
4572
4573 startcol -= (*mb_head_off)(line, line + startcol);
4574 base_class = mb_get_class(line + startcol);
4575 while (--startcol >= 0)
4576 {
4577 head_off = (*mb_head_off)(line, line + startcol);
4578 if (base_class != mb_get_class(line + startcol
4579 - head_off))
4580 break;
4581 startcol -= head_off;
4582 }
4583 }
4584 else
4585 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4586 ;
4587 compl_col += ++startcol;
4588 compl_length = (int)curs_col - startcol;
4589 if (compl_length == 1)
4590 {
4591 // Only match word with at least two chars -- webb
4592 // there's no need to call quote_meta,
4593 // alloc(7) is enough -- Acevedo
4594 compl_pattern = alloc(7);
4595 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004596 {
4597 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004598 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004599 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004600 STRCPY((char *)compl_pattern, "\\<");
4601 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4602 STRCAT((char *)compl_pattern, "\\k");
4603 }
4604 else
4605 {
4606 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4607 compl_length) + 2);
4608 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004609 {
4610 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004611 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004612 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004613 STRCPY((char *)compl_pattern, "\\<");
4614 (void)quote_meta(compl_pattern + 2, line + compl_col,
4615 compl_length);
4616 }
4617 }
4618
John Marriott8c85a2a2024-05-20 19:18:26 +02004619 compl_patternlen = STRLEN(compl_pattern);
4620
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004621 return OK;
4622}
4623
4624/*
4625 * Get the pattern, column and length for whole line completion or for the
4626 * complete() function.
4627 * Sets the global variables: compl_col, compl_length and compl_pattern.
4628 */
4629 static int
4630get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4631{
4632 compl_col = (colnr_T)getwhitecols(line);
4633 compl_length = (int)curs_col - (int)compl_col;
4634 if (compl_length < 0) // cursor in indent: empty pattern
4635 compl_length = 0;
4636 if (p_ic)
4637 compl_pattern = str_foldcase(line + compl_col, compl_length,
4638 NULL, 0);
4639 else
4640 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4641 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004642 {
4643 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004644 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004645 }
4646
4647 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004648
4649 return OK;
4650}
4651
4652/*
4653 * Get the pattern, column and length for filename completion.
4654 * Sets the global variables: compl_col, compl_length and compl_pattern.
4655 */
4656 static int
4657get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4658{
4659 // Go back to just before the first filename character.
4660 if (startcol > 0)
4661 {
4662 char_u *p = line + startcol;
4663
4664 MB_PTR_BACK(line, p);
4665 while (p > line && vim_isfilec(PTR2CHAR(p)))
4666 MB_PTR_BACK(line, p);
4667 if (p == line && vim_isfilec(PTR2CHAR(p)))
4668 startcol = 0;
4669 else
4670 startcol = (int)(p - line) + 1;
4671 }
4672
4673 compl_col += startcol;
4674 compl_length = (int)curs_col - startcol;
4675 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4676 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004677 {
4678 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004679 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004680 }
4681
4682 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004683
4684 return OK;
4685}
4686
4687/*
4688 * Get the pattern, column and length for command-line completion.
4689 * Sets the global variables: compl_col, compl_length and compl_pattern.
4690 */
4691 static int
4692get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4693{
4694 compl_pattern = vim_strnsave(line, curs_col);
4695 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004696 {
4697 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004698 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004699 }
4700 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004701 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004702 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004703 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4704 || compl_xp.xp_context == EXPAND_NOTHING)
4705 // No completion possible, use an empty pattern to get a
4706 // "pattern not found" message.
4707 compl_col = curs_col;
4708 else
4709 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4710 compl_length = curs_col - compl_col;
4711
4712 return OK;
4713}
4714
4715/*
4716 * Get the pattern, column and length for user defined completion ('omnifunc',
4717 * 'completefunc' and 'thesaurusfunc')
4718 * Sets the global variables: compl_col, compl_length and compl_pattern.
4719 * Uses the global variable: spell_bad_len
4720 */
4721 static int
4722get_userdefined_compl_info(colnr_T curs_col UNUSED)
4723{
4724 int ret = FAIL;
4725
4726#ifdef FEAT_COMPL_FUNC
4727 // Call user defined function 'completefunc' with "a:findstart"
4728 // set to 1 to obtain the length of text to use for completion.
4729 char_u *line;
4730 typval_T args[3];
4731 int col;
4732 char_u *funcname;
4733 pos_T pos;
4734 int save_State = State;
4735 callback_T *cb;
4736
4737 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4738 // length as a string
4739 funcname = get_complete_funcname(ctrl_x_mode);
4740 if (*funcname == NUL)
4741 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004742 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004743 ? "completefunc" : "omnifunc");
4744 return FAIL;
4745 }
4746
4747 args[0].v_type = VAR_NUMBER;
4748 args[0].vval.v_number = 1;
4749 args[1].v_type = VAR_STRING;
4750 args[1].vval.v_string = (char_u *)"";
4751 args[2].v_type = VAR_UNKNOWN;
4752 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004753 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004754 cb = get_insert_callback(ctrl_x_mode);
4755 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004756 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004757
4758 State = save_State;
4759 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004760 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004761 validate_cursor();
4762 if (!EQUAL_POS(curwin->w_cursor, pos))
4763 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004764 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004765 return FAIL;
4766 }
4767
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004768 // Return value -2 means the user complete function wants to cancel the
4769 // complete without an error, do the same if the function did not execute
4770 // successfully.
4771 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004772 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004773 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004774 if (col == -3)
4775 {
4776 ctrl_x_mode = CTRL_X_NORMAL;
4777 edit_submode = NULL;
4778 if (!shortmess(SHM_COMPLETIONMENU))
4779 msg_clr_cmdline();
4780 return FAIL;
4781 }
4782
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004783 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004784 // completion.
4785 compl_opt_refresh_always = FALSE;
4786 compl_opt_suppress_empty = FALSE;
4787
4788 if (col < 0)
4789 col = curs_col;
4790 compl_col = col;
4791 if (compl_col > curs_col)
4792 compl_col = curs_col;
4793
4794 // Setup variables for completion. Need to obtain "line" again,
4795 // it may have become invalid.
4796 line = ml_get(curwin->w_cursor.lnum);
4797 compl_length = curs_col - compl_col;
4798 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4799 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004800 {
4801 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004802 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004803 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004804
John Marriott8c85a2a2024-05-20 19:18:26 +02004805 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004806 ret = OK;
4807#endif
4808
4809 return ret;
4810}
4811
4812/*
4813 * Get the pattern, column and length for spell completion.
4814 * Sets the global variables: compl_col, compl_length and compl_pattern.
4815 * Uses the global variable: spell_bad_len
4816 */
4817 static int
4818get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4819{
4820 int ret = FAIL;
4821#ifdef FEAT_SPELL
4822 char_u *line;
4823
4824 if (spell_bad_len > 0)
4825 compl_col = curs_col - spell_bad_len;
4826 else
4827 compl_col = spell_word_start(startcol);
4828 if (compl_col >= (colnr_T)startcol)
4829 {
4830 compl_length = 0;
4831 compl_col = curs_col;
4832 }
4833 else
4834 {
4835 spell_expand_check_cap(compl_col);
4836 compl_length = (int)curs_col - compl_col;
4837 }
4838 // Need to obtain "line" again, it may have become invalid.
4839 line = ml_get(curwin->w_cursor.lnum);
4840 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4841 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004842 {
4843 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004844 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004845 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004846
John Marriott8c85a2a2024-05-20 19:18:26 +02004847 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004848 ret = OK;
4849#endif
4850
4851 return ret;
4852}
4853
4854/*
4855 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004856 * "startcol" - start column number of the completion pattern/text
4857 * "cur_col" - current cursor column
4858 * On return, "line_invalid" is set to TRUE, if the current line may have
4859 * become invalid and needs to be fetched again.
4860 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004861 */
4862 static int
4863compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
4864{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004865 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004866 || (ctrl_x_mode & CTRL_X_WANT_IDENT
4867 && !thesaurus_func_complete(ctrl_x_mode)))
4868 {
4869 return get_normal_compl_info(line, startcol, curs_col);
4870 }
4871 else if (ctrl_x_mode_line_or_eval())
4872 {
4873 return get_wholeline_compl_info(line, curs_col);
4874 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004875 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004876 {
4877 return get_filename_compl_info(line, startcol, curs_col);
4878 }
4879 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4880 {
4881 return get_cmdline_compl_info(line, curs_col);
4882 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004883 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004884 || thesaurus_func_complete(ctrl_x_mode))
4885 {
4886 if (get_userdefined_compl_info(curs_col) == FAIL)
4887 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004888 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004889 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004890 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004891 {
4892 if (get_spell_compl_info(startcol, curs_col) == FAIL)
4893 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004894 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004895 }
4896 else
4897 {
4898 internal_error("ins_complete()");
4899 return FAIL;
4900 }
4901
4902 return OK;
4903}
4904
4905/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004906 * Continue an interrupted completion mode search in "line".
4907 *
4908 * If this same ctrl_x_mode has been interrupted use the text from
4909 * "compl_startpos" to the cursor as a pattern to add a new word instead of
4910 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
4911 * the same line as the cursor then fix it (the line has been split because it
4912 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
4913 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004914 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004915 static void
4916ins_compl_continue_search(char_u *line)
4917{
4918 // it is a continued search
4919 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004920 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
4921 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004922 {
4923 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4924 {
4925 // line (probably) wrapped, set compl_startpos to the
4926 // first non_blank in the line, if it is not a wordchar
4927 // include it to get a better pattern, but then we don't
4928 // want the "\\<" prefix, check it below
4929 compl_col = (colnr_T)getwhitecols(line);
4930 compl_startpos.col = compl_col;
4931 compl_startpos.lnum = curwin->w_cursor.lnum;
4932 compl_cont_status &= ~CONT_SOL; // clear SOL if present
4933 }
4934 else
4935 {
4936 // S_IPOS was set when we inserted a word that was at the
4937 // beginning of the line, which means that we'll go to SOL
4938 // mode but first we need to redefine compl_startpos
4939 if (compl_cont_status & CONT_S_IPOS)
4940 {
4941 compl_cont_status |= CONT_SOL;
4942 compl_startpos.col = (colnr_T)(skipwhite(
4943 line + compl_length
4944 + compl_startpos.col) - line);
4945 }
4946 compl_col = compl_startpos.col;
4947 }
4948 compl_length = curwin->w_cursor.col - (int)compl_col;
4949 // IObuff is used to add a "word from the next line" would we
4950 // have enough space? just being paranoid
4951#define MIN_SPACE 75
4952 if (compl_length > (IOSIZE - MIN_SPACE))
4953 {
4954 compl_cont_status &= ~CONT_SOL;
4955 compl_length = (IOSIZE - MIN_SPACE);
4956 compl_col = curwin->w_cursor.col - compl_length;
4957 }
4958 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4959 if (compl_length < 1)
4960 compl_cont_status &= CONT_LOCAL;
4961 }
4962 else if (ctrl_x_mode_line_or_eval())
4963 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4964 else
4965 compl_cont_status = 0;
4966}
4967
4968/*
4969 * start insert mode completion
4970 */
4971 static int
4972ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004973{
4974 char_u *line;
4975 int startcol = 0; // column where searched text starts
4976 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004977 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004978 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004979 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004980
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004981 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004982
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004983 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004984 did_si = FALSE;
4985 can_si = FALSE;
4986 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004987 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004988 return FAIL;
4989
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004990 line = ml_get(curwin->w_cursor.lnum);
4991 curs_col = curwin->w_cursor.col;
4992 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004993
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004994 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4995 && compl_cont_mode == ctrl_x_mode)
4996 // this same ctrl-x_mode was interrupted previously. Continue the
4997 // completion.
4998 ins_compl_continue_search(line);
4999 else
5000 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005001
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005002 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005003 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005004 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005005 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005006 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5007 compl_cont_status = 0;
5008 compl_cont_status |= CONT_N_ADDS;
5009 compl_startpos = curwin->w_cursor;
5010 startcol = (int)curs_col;
5011 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005012 }
5013
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005014 // Work out completion pattern and original text -- webb
5015 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5016 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005017 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5018 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005019 // restore did_ai, so that adding comment leader works
5020 did_ai = save_did_ai;
5021 return FAIL;
5022 }
5023 // If "line" was changed while getting completion info get it again.
5024 if (line_invalid)
5025 line = ml_get(curwin->w_cursor.lnum);
5026
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005027 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005028 {
5029 edit_submode_pre = (char_u *)_(" Adding");
5030 if (ctrl_x_mode_line_or_eval())
5031 {
5032 // Insert a new line, keep indentation but ignore 'comments'.
5033 char_u *old = curbuf->b_p_com;
5034
5035 curbuf->b_p_com = (char_u *)"";
5036 compl_startpos.lnum = curwin->w_cursor.lnum;
5037 compl_startpos.col = compl_col;
5038 ins_eol('\r');
5039 curbuf->b_p_com = old;
5040 compl_length = 0;
5041 compl_col = curwin->w_cursor.col;
5042 }
5043 }
5044 else
5045 {
5046 edit_submode_pre = NULL;
5047 compl_startpos.col = compl_col;
5048 }
5049
5050 if (compl_cont_status & CONT_LOCAL)
5051 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5052 else
5053 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5054
5055 // If any of the original typed text has been changed we need to fix
5056 // the redo buffer.
5057 ins_compl_fixRedoBufForLeader(NULL);
5058
5059 // Always add completion for the original text.
5060 vim_free(compl_orig_text);
5061 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5062 if (p_ic)
5063 flags |= CP_ICASE;
5064 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5065 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
5066 {
5067 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005068 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005069 VIM_CLEAR(compl_orig_text);
5070 return FAIL;
5071 }
5072
5073 // showmode might reset the internal line pointers, so it must
5074 // be called before line = ml_get(), or when this address is no
5075 // longer needed. -- Acevedo.
5076 edit_submode_extra = (char_u *)_("-- Searching...");
5077 edit_submode_highl = HLF_COUNT;
5078 showmode();
5079 edit_submode_extra = NULL;
5080 out_flush();
5081
5082 return OK;
5083}
5084
5085/*
5086 * display the completion status message
5087 */
5088 static void
5089ins_compl_show_statusmsg(void)
5090{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005091 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005092 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005093 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005094 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005095 ? (char_u *)_("Hit end of paragraph")
5096 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005097 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005098 }
5099
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005100 if (edit_submode_extra == NULL)
5101 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005102 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005103 {
5104 edit_submode_extra = (char_u *)_("Back at original");
5105 edit_submode_highl = HLF_W;
5106 }
5107 else if (compl_cont_status & CONT_S_IPOS)
5108 {
5109 edit_submode_extra = (char_u *)_("Word from other line");
5110 edit_submode_highl = HLF_COUNT;
5111 }
5112 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5113 {
5114 edit_submode_extra = (char_u *)_("The only match");
5115 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005116 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005117 }
5118 else
5119 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005120#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005121 // Update completion sequence number when needed.
5122 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005123 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005124#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005125 // The match should always have a sequence number now, this is
5126 // just a safety check.
5127 if (compl_curr_match->cp_number != -1)
5128 {
5129 // Space for 10 text chars. + 2x10-digit no.s = 31.
5130 // Translations may need more than twice that.
5131 static char_u match_ref[81];
5132
5133 if (compl_matches > 0)
5134 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005135 _("match %d of %d"),
5136 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005137 else
5138 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005139 _("match %d"),
5140 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005141 edit_submode_extra = match_ref;
5142 edit_submode_highl = HLF_R;
5143 if (dollar_vcol >= 0)
5144 curs_columns(FALSE);
5145 }
5146 }
5147 }
5148
5149 // Show a message about what (completion) mode we're in.
5150 if (!compl_opt_suppress_empty)
5151 {
5152 showmode();
5153 if (!shortmess(SHM_COMPLETIONMENU))
5154 {
5155 if (edit_submode_extra != NULL)
5156 {
5157 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005158 {
5159 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005160 msg_attr((char *)edit_submode_extra,
5161 edit_submode_highl < HLF_COUNT
5162 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005163 msg_hist_off = FALSE;
5164 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005165 }
5166 else
5167 msg_clr_cmdline(); // necessary for "noshowmode"
5168 }
5169 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005170}
5171
5172/*
5173 * Do Insert mode completion.
5174 * Called when character "c" was typed, which has a meaning for completion.
5175 * Returns OK if completion was done, FAIL if something failed (out of mem).
5176 */
5177 int
5178ins_complete(int c, int enable_pum)
5179{
5180 int n;
5181 int save_w_wrow;
5182 int save_w_leftcol;
5183 int insert_match;
5184
5185 compl_direction = ins_compl_key2dir(c);
5186 insert_match = ins_compl_use_match(c);
5187
5188 if (!compl_started)
5189 {
5190 if (ins_compl_start() == FAIL)
5191 return FAIL;
5192 }
5193 else if (insert_match && stop_arrow() == FAIL)
5194 return FAIL;
5195
5196 compl_shown_match = compl_curr_match;
5197 compl_shows_dir = compl_direction;
5198
5199 // Find next match (and following matches).
5200 save_w_wrow = curwin->w_wrow;
5201 save_w_leftcol = curwin->w_leftcol;
5202 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5203
5204 // may undisplay the popup menu
5205 ins_compl_upd_pum();
5206
5207 if (n > 1) // all matches have been found
5208 compl_matches = n;
5209 compl_curr_match = compl_shown_match;
5210 compl_direction = compl_shows_dir;
5211
5212 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5213 // mode.
5214 if (got_int && !global_busy)
5215 {
5216 (void)vgetc();
5217 got_int = FALSE;
5218 }
5219
5220 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005221 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005222 {
5223 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5224 // because we couldn't expand anything at first place, but if we used
5225 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5226 // (such as M in M'exico) if not tried already. -- Acevedo
5227 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005228 || compl_status_adding()
5229 || (ctrl_x_mode_not_default()
5230 && !ctrl_x_mode_path_patterns()
5231 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005232 compl_cont_status &= ~CONT_N_ADDS;
5233 }
5234
5235 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5236 compl_cont_status |= CONT_S_IPOS;
5237 else
5238 compl_cont_status &= ~CONT_S_IPOS;
5239
5240 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005241
5242 // Show the popup menu, unless we got interrupted.
5243 if (enable_pum && !compl_interrupted)
5244 show_pum(save_w_wrow, save_w_leftcol);
5245
5246 compl_was_interrupted = compl_interrupted;
5247 compl_interrupted = FALSE;
5248
5249 return OK;
5250}
5251
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005252/*
5253 * Remove (if needed) and show the popup menu
5254 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005255 static void
5256show_pum(int prev_w_wrow, int prev_w_leftcol)
5257{
5258 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005259 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005260 RedrawingDisabled = 0;
5261
5262 // If the cursor moved or the display scrolled we need to remove the pum
5263 // first.
5264 setcursor();
5265 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5266 ins_compl_del_pum();
5267
5268 ins_compl_show_pum();
5269 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005270
5271 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005272}
5273
5274/*
5275 * Looks in the first "len" chars. of "src" for search-metachars.
5276 * If dest is not NULL the chars. are copied there quoting (with
5277 * a backslash) the metachars, and dest would be NUL terminated.
5278 * Returns the length (needed) of dest
5279 */
5280 static unsigned
5281quote_meta(char_u *dest, char_u *src, int len)
5282{
5283 unsigned m = (unsigned)len + 1; // one extra for the NUL
5284
5285 for ( ; --len >= 0; src++)
5286 {
5287 switch (*src)
5288 {
5289 case '.':
5290 case '*':
5291 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005292 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005293 break;
5294 // FALLTHROUGH
5295 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005296 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005297 break;
5298 // FALLTHROUGH
5299 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005300 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005301 break;
5302 // FALLTHROUGH
5303 case '^': // currently it's not needed.
5304 case '$':
5305 m++;
5306 if (dest != NULL)
5307 *dest++ = '\\';
5308 break;
5309 }
5310 if (dest != NULL)
5311 *dest++ = *src;
5312 // Copy remaining bytes of a multibyte character.
5313 if (has_mbyte)
5314 {
5315 int i, mb_len;
5316
5317 mb_len = (*mb_ptr2len)(src) - 1;
5318 if (mb_len > 0 && len >= mb_len)
5319 for (i = 0; i < mb_len; ++i)
5320 {
5321 --len;
5322 ++src;
5323 if (dest != NULL)
5324 *dest++ = *src;
5325 }
5326 }
5327 }
5328 if (dest != NULL)
5329 *dest = NUL;
5330
5331 return m;
5332}
5333
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005334#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005335 void
5336free_insexpand_stuff(void)
5337{
5338 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005339# ifdef FEAT_EVAL
5340 free_callback(&cfu_cb);
5341 free_callback(&ofu_cb);
5342 free_callback(&tsrfu_cb);
5343# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005344}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005345#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005346
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005347#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005348/*
5349 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5350 * spelled word, if there is one.
5351 */
5352 static void
5353spell_back_to_badword(void)
5354{
5355 pos_T tpos = curwin->w_cursor;
5356
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005357 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005358 if (curwin->w_cursor.col != tpos.col)
5359 start_arrow(&tpos);
5360}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005361#endif