blob: 21b53d1e3e85062aaee5e21a2f45be01098a0a6f [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020061 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010062 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
91 * Array indexes used for cp_text[].
92 */
93#define CPT_ABBR 0 // "abbr"
94#define CPT_MENU 1 // "menu"
95#define CPT_KIND 2 // "kind"
96#define CPT_INFO 3 // "info"
Bram Moolenaar08928322020-01-04 14:32:48 +010097#define CPT_COUNT 4 // Number of entries
Bram Moolenaar7591bb32019-03-30 13:53:47 +010098
99/*
100 * Structure used to store one match for insert completion.
101 */
102typedef struct compl_S compl_T;
103struct compl_S
104{
105 compl_T *cp_next;
106 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200107 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200108 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100109#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100110 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100111#endif
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200112 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113 // cp_flags has CP_FREE_FNAME
114 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200115 int cp_number; // sequence number
glepnira218cc62024-06-03 19:32:39 +0200116 int cp_score; // fuzzy match score
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100117};
118
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200119// values for cp_flags
120# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
121# define CP_FREE_FNAME 2 // cp_fname is allocated
122# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
123# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
124# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200125# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100127/*
128 * All the current matches are stored in a list.
129 * "compl_first_match" points to the start of the list.
130 * "compl_curr_match" points to the currently selected entry.
131 * "compl_shown_match" is different from compl_curr_match during
132 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000133 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100134 */
135static compl_T *compl_first_match = NULL;
136static compl_T *compl_curr_match = NULL;
137static compl_T *compl_shown_match = NULL;
138static compl_T *compl_old_match = NULL;
139
140// After using a cursor key <Enter> selects a match in the popup menu,
141// otherwise it inserts a line break.
142static int compl_enter_selects = FALSE;
143
144// When "compl_leader" is not NULL only matches that start with this string
145// are used.
146static char_u *compl_leader = NULL;
147
148static int compl_get_longest = FALSE; // put longest common string
149 // in compl_leader
150
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100151// Selected one of the matches. When FALSE the match was edited or using the
152// longest common string.
153static int compl_used_match;
154
155// didn't finish finding completions.
156static int compl_was_interrupted = FALSE;
157
158// Set when character typed while looking for matches and it means we should
159// stop looking for matches.
160static int compl_interrupted = FALSE;
161
162static int compl_restarting = FALSE; // don't insert match
163
164// When the first completion is done "compl_started" is set. When it's
165// FALSE the word to be completed must be located.
166static int compl_started = FALSE;
167
168// Which Ctrl-X mode are we in?
169static int ctrl_x_mode = CTRL_X_NORMAL;
170
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000171static int compl_matches = 0; // number of completion matches
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100172static char_u *compl_pattern = NULL;
John Marriott8c85a2a2024-05-20 19:18:26 +0200173static size_t compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100174static int compl_direction = FORWARD;
175static int compl_shows_dir = FORWARD;
176static int compl_pending = 0; // > 1 for postponed CTRL-N
177static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000178// Length in bytes of the text being completed (this is deleted to be replaced
179// by the match.)
180static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100181static colnr_T compl_col = 0; // column where the text starts
182 // that is being completed
183static char_u *compl_orig_text = NULL; // text as it was before
184 // completion started
185static int compl_cont_mode = 0;
186static expand_T compl_xp;
187
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000188// List of flags for method of completion.
189static int compl_cont_status = 0;
190# define CONT_ADDING 1 // "normal" or "adding" expansion
191# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
192 // it's set only iff N_ADDS is set
193# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
194# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
195 // if so, word-wise-expansion will set SOL
196# define CONT_SOL 16 // pattern includes start of line, just for
197 // word-wise expansion, not set for ^X^L
198# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
199 // expansion, (eg use complete=.)
200
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100201static int compl_opt_refresh_always = FALSE;
202static int compl_opt_suppress_empty = FALSE;
203
glepnira218cc62024-06-03 19:32:39 +0200204static int compl_selected_item = -1;
205
Bram Moolenaar08928322020-01-04 14:32:48 +0100206static int ins_compl_add(char_u *str, int len, char_u *fname, char_u **cptext, typval_T *user_data, int cdir, int flags, int adup);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100207static void ins_compl_longest_match(compl_T *match);
208static void ins_compl_del_pum(void);
209static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
210static char_u *find_line_end(char_u *ptr);
211static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100212static int ins_compl_need_restart(void);
213static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000214static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100215static void ins_compl_restart(void);
216static void ins_compl_set_original_text(char_u *str);
217static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
218# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
219static void ins_compl_add_list(list_T *list);
220static void ins_compl_add_dict(dict_T *dict);
221# endif
222static int ins_compl_key2dir(int c);
223static int ins_compl_pum_key(int c);
224static int ins_compl_key2count(int c);
225static void show_pum(int prev_w_wrow, int prev_w_leftcol);
226static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100227
228#ifdef FEAT_SPELL
229static void spell_back_to_badword(void);
230static int spell_bad_len = 0; // length of located bad word
231#endif
232
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100233/*
234 * CTRL-X pressed in Insert mode.
235 */
236 void
237ins_ctrl_x(void)
238{
zeertzjqdca29d92021-08-31 19:12:51 +0200239 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100240 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000241 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100242 if (compl_cont_status & CONT_N_ADDS)
243 compl_cont_status |= CONT_INTRPT;
244 else
245 compl_cont_status = 0;
246 // We're not sure which CTRL-X mode it will be yet
247 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
248 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
249 edit_submode_pre = NULL;
250 showmode();
251 }
zeertzjqdca29d92021-08-31 19:12:51 +0200252 else
253 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
254 // CTRL-V look like CTRL-N
255 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100256
LemonBoy2bf52dd2022-04-09 18:17:34 +0100257 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100258}
259
260/*
261 * Functions to check the current CTRL-X mode.
262 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000263int ctrl_x_mode_none(void)
264 { return ctrl_x_mode == 0; }
265int ctrl_x_mode_normal(void)
266 { return ctrl_x_mode == CTRL_X_NORMAL; }
267int ctrl_x_mode_scroll(void)
268 { return ctrl_x_mode == CTRL_X_SCROLL; }
269int ctrl_x_mode_whole_line(void)
270 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
271int ctrl_x_mode_files(void)
272 { return ctrl_x_mode == CTRL_X_FILES; }
273int ctrl_x_mode_tags(void)
274 { return ctrl_x_mode == CTRL_X_TAGS; }
275int ctrl_x_mode_path_patterns(void)
276 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
277int ctrl_x_mode_path_defines(void)
278 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
279int ctrl_x_mode_dictionary(void)
280 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
281int ctrl_x_mode_thesaurus(void)
282 { return ctrl_x_mode == CTRL_X_THESAURUS; }
283int ctrl_x_mode_cmdline(void)
284 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200285 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000286int ctrl_x_mode_function(void)
287 { return ctrl_x_mode == CTRL_X_FUNCTION; }
288int ctrl_x_mode_omni(void)
289 { return ctrl_x_mode == CTRL_X_OMNI; }
290int ctrl_x_mode_spell(void)
291 { return ctrl_x_mode == CTRL_X_SPELL; }
292static int ctrl_x_mode_eval(void)
293 { return ctrl_x_mode == CTRL_X_EVAL; }
294int ctrl_x_mode_line_or_eval(void)
295 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100296
297/*
298 * Whether other than default completion has been selected.
299 */
300 int
301ctrl_x_mode_not_default(void)
302{
303 return ctrl_x_mode != CTRL_X_NORMAL;
304}
305
306/*
zeertzjqdca29d92021-08-31 19:12:51 +0200307 * Whether CTRL-X was typed without a following character,
308 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100309 */
310 int
311ctrl_x_mode_not_defined_yet(void)
312{
313 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
314}
315
316/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000317 * Return TRUE if currently in "normal" or "adding" insert completion matches
318 * state
319 */
320 int
321compl_status_adding(void)
322{
323 return compl_cont_status & CONT_ADDING;
324}
325
326/*
327 * Return TRUE if the completion pattern includes start of line, just for
328 * word-wise expansion.
329 */
330 int
331compl_status_sol(void)
332{
333 return compl_cont_status & CONT_SOL;
334}
335
336/*
337 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
338 */
339 int
340compl_status_local(void)
341{
342 return compl_cont_status & CONT_LOCAL;
343}
344
345/*
346 * Clear the completion status flags
347 */
348 void
349compl_status_clear(void)
350{
351 compl_cont_status = 0;
352}
353
354/*
355 * Return TRUE if completion is using the forward direction matches
356 */
357 static int
358compl_dir_forward(void)
359{
360 return compl_direction == FORWARD;
361}
362
363/*
364 * Return TRUE if currently showing forward completion matches
365 */
366 static int
367compl_shows_dir_forward(void)
368{
369 return compl_shows_dir == FORWARD;
370}
371
372/*
373 * Return TRUE if currently showing backward completion matches
374 */
375 static int
376compl_shows_dir_backward(void)
377{
378 return compl_shows_dir == BACKWARD;
379}
380
381/*
382 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100383 */
384 int
385has_compl_option(int dict_opt)
386{
387 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200388#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100389 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200390#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100391 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100392 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
393#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100394 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100395#endif
396 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100397 {
398 ctrl_x_mode = CTRL_X_NORMAL;
399 edit_submode = NULL;
400 msg_attr(dict_opt ? _("'dictionary' option is empty")
401 : _("'thesaurus' option is empty"),
402 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100403 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100404 {
405 vim_beep(BO_COMPL);
406 setcursor();
407 out_flush();
408#ifdef FEAT_EVAL
409 if (!get_vim_var_nr(VV_TESTING))
410#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100411 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100412 }
413 return FALSE;
414 }
415 return TRUE;
416}
417
418/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000419 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100420 * This depends on the current mode.
421 */
422 int
423vim_is_ctrl_x_key(int c)
424{
425 // Always allow ^R - let its results then be checked
426 if (c == Ctrl_R)
427 return TRUE;
428
429 // Accept <PageUp> and <PageDown> if the popup menu is visible.
430 if (ins_compl_pum_key(c))
431 return TRUE;
432
433 switch (ctrl_x_mode)
434 {
435 case 0: // Not in any CTRL-X mode
436 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
437 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200438 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100439 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
440 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
441 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
442 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
443 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200444 || c == Ctrl_S || c == Ctrl_K || c == 's'
445 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100446 case CTRL_X_SCROLL:
447 return (c == Ctrl_Y || c == Ctrl_E);
448 case CTRL_X_WHOLE_LINE:
449 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
450 case CTRL_X_FILES:
451 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
452 case CTRL_X_DICTIONARY:
453 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
454 case CTRL_X_THESAURUS:
455 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
456 case CTRL_X_TAGS:
457 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
458#ifdef FEAT_FIND_ID
459 case CTRL_X_PATH_PATTERNS:
460 return (c == Ctrl_P || c == Ctrl_N);
461 case CTRL_X_PATH_DEFINES:
462 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
463#endif
464 case CTRL_X_CMDLINE:
465 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
466 || c == Ctrl_X);
467#ifdef FEAT_COMPL_FUNC
468 case CTRL_X_FUNCTION:
469 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
470 case CTRL_X_OMNI:
471 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
472#endif
473 case CTRL_X_SPELL:
474 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
475 case CTRL_X_EVAL:
476 return (c == Ctrl_P || c == Ctrl_N);
477 }
478 internal_error("vim_is_ctrl_x_key()");
479 return FALSE;
480}
481
482/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000483 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000484 */
485 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000486match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000487{
488 return match->cp_flags & CP_ORIGINAL_TEXT;
489}
490
491/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000492 * Returns TRUE if "match" is the first match in the completion list.
493 */
494 static int
495is_first_match(compl_T *match)
496{
497 return match == compl_first_match;
498}
499
500/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100501 * Return TRUE when character "c" is part of the item currently being
502 * completed. Used to decide whether to abandon complete mode when the menu
503 * is visible.
504 */
505 int
506ins_compl_accept_char(int c)
507{
508 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
509 // When expanding an identifier only accept identifier chars.
510 return vim_isIDc(c);
511
512 switch (ctrl_x_mode)
513 {
514 case CTRL_X_FILES:
515 // When expanding file name only accept file name chars. But not
516 // path separators, so that "proto/<Tab>" expands files in
517 // "proto", not "proto/" as a whole
518 return vim_isfilec(c) && !vim_ispathsep(c);
519
520 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200521 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100522 case CTRL_X_OMNI:
523 // Command line and Omni completion can work with just about any
524 // printable character, but do stop at white space.
525 return vim_isprintc(c) && !VIM_ISWHITE(c);
526
527 case CTRL_X_WHOLE_LINE:
528 // For while line completion a space can be part of the line.
529 return vim_isprintc(c);
530 }
531 return vim_iswordc(c);
532}
533
534/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000535 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100536 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000537 */
538 static char_u *
539ins_compl_infercase_gettext(
540 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100541 int char_len,
542 int compl_char_len,
543 int min_len,
544 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000545{
546 int *wca; // Wide character array.
547 char_u *p;
548 int i, c;
549 int has_lower = FALSE;
550 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100551 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000552
553 IObuff[0] = NUL;
554
555 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100556 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000557 if (wca == NULL)
558 return IObuff;
559
560 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100561 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000562 if (has_mbyte)
563 wca[i] = mb_ptr2char_adv(&p);
564 else
565 wca[i] = *(p++);
566
567 // Rule 1: Were any chars converted to lower?
568 p = compl_orig_text;
569 for (i = 0; i < min_len; ++i)
570 {
571 if (has_mbyte)
572 c = mb_ptr2char_adv(&p);
573 else
574 c = *(p++);
575 if (MB_ISLOWER(c))
576 {
577 has_lower = TRUE;
578 if (MB_ISUPPER(wca[i]))
579 {
580 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100581 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582 wca[i] = MB_TOLOWER(wca[i]);
583 break;
584 }
585 }
586 }
587
588 // Rule 2: No lower case, 2nd consecutive letter converted to
589 // upper case.
590 if (!has_lower)
591 {
592 p = compl_orig_text;
593 for (i = 0; i < min_len; ++i)
594 {
595 if (has_mbyte)
596 c = mb_ptr2char_adv(&p);
597 else
598 c = *(p++);
599 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
600 {
601 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100602 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000603 wca[i] = MB_TOUPPER(wca[i]);
604 break;
605 }
606 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
607 }
608 }
609
610 // Copy the original case of the part we typed.
611 p = compl_orig_text;
612 for (i = 0; i < min_len; ++i)
613 {
614 if (has_mbyte)
615 c = mb_ptr2char_adv(&p);
616 else
617 c = *(p++);
618 if (MB_ISLOWER(c))
619 wca[i] = MB_TOLOWER(wca[i]);
620 else if (MB_ISUPPER(c))
621 wca[i] = MB_TOUPPER(wca[i]);
622 }
623
624 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000625 p = IObuff;
626 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100627 ga_init2(&gap, 1, 500);
628 while (i < char_len)
629 {
630 if (gap.ga_data != NULL)
631 {
632 if (ga_grow(&gap, 10) == FAIL)
633 {
634 ga_clear(&gap);
635 return (char_u *)"[failed]";
636 }
637 p = (char_u *)gap.ga_data + gap.ga_len;
638 if (has_mbyte)
639 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
640 else
641 {
642 *p = wca[i++];
643 ++gap.ga_len;
644 }
645 }
646 else if ((p - IObuff) + 6 >= IOSIZE)
647 {
648 // Multi-byte characters can occupy up to five bytes more than
649 // ASCII characters, and we also need one byte for NUL, so when
650 // getting to six bytes from the edge of IObuff switch to using a
651 // growarray. Add the character in the next round.
652 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100653 {
654 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100655 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100656 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100657 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100658 STRCPY(gap.ga_data, IObuff);
Bram Moolenaarc7bd2f02022-07-15 20:45:20 +0100659 gap.ga_len = (int)STRLEN(IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100660 }
661 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000662 p += (*mb_char2bytes)(wca[i++], p);
663 else
664 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100665 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000666 vim_free(wca);
667
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100668 if (gap.ga_data != NULL)
669 {
670 *tofree = gap.ga_data;
671 return gap.ga_data;
672 }
673
674 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000675 return IObuff;
676}
677
678/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100679 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
680 * case of the originally typed text is used, and the case of the completed
681 * text is inferred, ie this tries to work out what case you probably wanted
682 * the rest of the word to be in -- webb
683 */
684 int
685ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200686 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100687 int len,
688 int icase,
689 char_u *fname,
690 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200691 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100692{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200693 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100694 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100695 int char_len; // count multi-byte characters
696 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100697 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200698 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100699 int res;
700 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100701
702 if (p_ic && curbuf->b_p_inf && len > 0)
703 {
704 // Infer case of completed part.
705
706 // Find actual length of completion.
707 if (has_mbyte)
708 {
709 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100710 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100711 while (*p != NUL)
712 {
713 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100714 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100715 }
716 }
717 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100718 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719
720 // Find actual length of original text.
721 if (has_mbyte)
722 {
723 p = compl_orig_text;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100724 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725 while (*p != NUL)
726 {
727 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100728 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100729 }
730 }
731 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100732 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100734 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100737
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 str = ins_compl_infercase_gettext(str, char_len,
739 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100740 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200741 if (cont_s_ipos)
742 flags |= CP_CONT_S_IPOS;
743 if (icase)
744 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200745
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100746 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);
747 vim_free(tofree);
748 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100749}
750
751/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000752 * Add a match to the list of matches. The arguments are:
753 * str - text of the match to add
754 * len - length of "str". If -1, then the length of "str" is
755 * computed.
756 * fname - file name to associate with this match.
757 * cptext - list of strings to use with this match (for abbr, menu, info
758 * and kind)
759 * user_data - user supplied data (any vim type) for this match
760 * cdir - match direction. If 0, use "compl_direction".
761 * flags_arg - match flags (cp_flags)
762 * adup - accept this match even if it is already present.
763 * If "cdir" is FORWARD, then the match is added after the current match.
764 * Otherwise, it is added before the current match.
765 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 * If the given string is already in the list of completions, then return
767 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
768 * maybe because alloc() returns NULL, then FAIL is returned.
769 */
770 static int
771ins_compl_add(
772 char_u *str,
773 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100774 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100775 char_u **cptext, // extra text for popup menu or NULL
776 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200778 int flags_arg,
Bram Moolenaar08928322020-01-04 14:32:48 +0100779 int adup) // accept duplicate match
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100780{
781 compl_T *match;
782 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200783 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100784
Bram Moolenaarceb06192021-04-04 15:05:22 +0200785 if (flags & CP_FAST)
786 fast_breakcheck();
787 else
788 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100789 if (got_int)
790 return FAIL;
791 if (len < 0)
792 len = (int)STRLEN(str);
793
794 // If the same match is already present, don't add it.
795 if (compl_first_match != NULL && !adup)
796 {
797 match = compl_first_match;
798 do
799 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000800 if (!match_at_original_text(match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100801 && STRNCMP(match->cp_str, str, len) == 0
Bram Moolenaarbaefde12022-07-07 19:59:49 +0100802 && ((int)STRLEN(match->cp_str) <= len
803 || match->cp_str[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100804 return NOTDONE;
805 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000806 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100807 }
808
809 // Remove any popup menu before changing the list of matches.
810 ins_compl_del_pum();
811
812 // Allocate a new match structure.
813 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200814 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100815 if (match == NULL)
816 return FAIL;
817 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200818 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 match->cp_number = 0;
820 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
821 {
822 vim_free(match);
823 return FAIL;
824 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100825
826 // match-fname is:
827 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200828 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829 // - NULL otherwise. --Acevedo
830 if (fname != NULL
831 && compl_curr_match != NULL
832 && compl_curr_match->cp_fname != NULL
833 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
834 match->cp_fname = compl_curr_match->cp_fname;
835 else if (fname != NULL)
836 {
837 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200838 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100839 }
840 else
841 match->cp_fname = NULL;
842 match->cp_flags = flags;
843
844 if (cptext != NULL)
845 {
846 int i;
847
848 for (i = 0; i < CPT_COUNT; ++i)
849 if (cptext[i] != NULL && *cptext[i] != NUL)
850 match->cp_text[i] = vim_strsave(cptext[i]);
851 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100852#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100853 if (user_data != NULL)
854 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100855#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000857 // Link the new match structure after (FORWARD) or before (BACKWARD) the
858 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859 if (compl_first_match == NULL)
860 match->cp_next = match->cp_prev = NULL;
861 else if (dir == FORWARD)
862 {
863 match->cp_next = compl_curr_match->cp_next;
864 match->cp_prev = compl_curr_match;
865 }
866 else // BACKWARD
867 {
868 match->cp_next = compl_curr_match;
869 match->cp_prev = compl_curr_match->cp_prev;
870 }
871 if (match->cp_next)
872 match->cp_next->cp_prev = match;
873 if (match->cp_prev)
874 match->cp_prev->cp_next = match;
875 else // if there's nothing before, it is the first match
876 compl_first_match = match;
877 compl_curr_match = match;
878
879 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200880 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881 ins_compl_longest_match(match);
882
883 return OK;
884}
885
886/*
887 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 */
890 static int
891ins_compl_equal(compl_T *match, char_u *str, int len)
892{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200893 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200894 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200895 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100896 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
897 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
898}
899
900/*
901 * Reduce the longest common string for match "match".
902 */
903 static void
904ins_compl_longest_match(compl_T *match)
905{
906 char_u *p, *s;
907 int c1, c2;
908 int had_match;
909
910 if (compl_leader == NULL)
911 {
912 // First match, use it as a whole.
913 compl_leader = vim_strsave(match->cp_str);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000914 if (compl_leader == NULL)
915 return;
916
917 had_match = (curwin->w_cursor.col > compl_col);
918 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000919 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000920 ins_redraw(FALSE);
921
922 // When the match isn't there (to avoid matching itself) remove it
923 // again after redrawing.
924 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100925 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000927
928 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100929 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000930
931 // Reduce the text if this match differs from compl_leader.
932 p = compl_leader;
933 s = match->cp_str;
934 while (*p != NUL)
935 {
936 if (has_mbyte)
937 {
938 c1 = mb_ptr2char(p);
939 c2 = mb_ptr2char(s);
940 }
941 else
942 {
943 c1 = *p;
944 c2 = *s;
945 }
946 if ((match->cp_flags & CP_ICASE)
947 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
948 break;
949 if (has_mbyte)
950 {
951 MB_PTR_ADV(p);
952 MB_PTR_ADV(s);
953 }
954 else
955 {
956 ++p;
957 ++s;
958 }
959 }
960
961 if (*p != NUL)
962 {
963 // Leader was shortened, need to change the inserted text.
964 *p = NUL;
965 had_match = (curwin->w_cursor.col > compl_col);
966 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000967 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000968 ins_redraw(FALSE);
969
970 // When the match isn't there (to avoid matching itself) remove it
971 // again after redrawing.
972 if (!had_match)
973 ins_compl_delete();
974 }
975
976 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100977}
978
979/*
980 * Add an array of matches to the list of matches.
981 * Frees matches[].
982 */
983 static void
984ins_compl_add_matches(
985 int num_matches,
986 char_u **matches,
987 int icase)
988{
989 int i;
990 int add_r = OK;
991 int dir = compl_direction;
992
993 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100994 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
Bram Moolenaar440cf092021-04-03 20:13:30 +0200995 CP_FAST | (icase ? CP_ICASE : 0), FALSE)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100996 // if dir was BACKWARD then honor it just once
997 dir = FORWARD;
998 FreeWild(num_matches, matches);
999}
1000
1001/*
1002 * Make the completion list cyclic.
1003 * Return the number of matches (excluding the original).
1004 */
1005 static int
1006ins_compl_make_cyclic(void)
1007{
1008 compl_T *match;
1009 int count = 0;
1010
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001011 if (compl_first_match == NULL)
1012 return 0;
1013
1014 // Find the end of the list.
1015 match = compl_first_match;
1016 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001017 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001018 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001019 match = match->cp_next;
1020 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001021 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001022 match->cp_next = compl_first_match;
1023 compl_first_match->cp_prev = match;
1024
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001025 return count;
1026}
1027
1028/*
1029 * Return whether there currently is a shown match.
1030 */
1031 int
1032ins_compl_has_shown_match(void)
1033{
1034 return compl_shown_match == NULL
1035 || compl_shown_match != compl_shown_match->cp_next;
1036}
1037
1038/*
1039 * Return whether the shown match is long enough.
1040 */
1041 int
1042ins_compl_long_shown_match(void)
1043{
1044 return (int)STRLEN(compl_shown_match->cp_str)
1045 > curwin->w_cursor.col - compl_col;
1046}
1047
1048/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001049 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001050 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001051 unsigned int
1052get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001053{
zeertzjq529b9ad2024-06-05 20:27:06 +02001054 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001055}
1056
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001057
1058// "compl_match_array" points the currently displayed list of entries in the
1059// popup menu. It is NULL when there is no popup menu.
1060static pumitem_T *compl_match_array = NULL;
1061static int compl_match_arraysize;
1062
1063/*
1064 * Update the screen and when there is any scrolling remove the popup menu.
1065 */
1066 static void
1067ins_compl_upd_pum(void)
1068{
1069 int h;
1070
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001071 if (compl_match_array == NULL)
1072 return;
1073
1074 h = curwin->w_cline_height;
1075 // Update the screen later, before drawing the popup menu over it.
1076 pum_call_update_screen();
1077 if (h != curwin->w_cline_height)
1078 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001079}
1080
1081/*
1082 * Remove any popup menu.
1083 */
1084 static void
1085ins_compl_del_pum(void)
1086{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001087 if (compl_match_array == NULL)
1088 return;
1089
1090 pum_undisplay();
1091 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001092}
1093
1094/*
1095 * Return TRUE if the popup menu should be displayed.
1096 */
1097 int
1098pum_wanted(void)
1099{
1100 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001101 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001102 return FALSE;
1103
1104 // The display looks bad on a B&W display.
1105 if (t_colors < 8
1106#ifdef FEAT_GUI
1107 && !gui.in_use
1108#endif
1109 )
1110 return FALSE;
1111 return TRUE;
1112}
1113
1114/*
1115 * Return TRUE if there are two or more matches to be shown in the popup menu.
1116 * One if 'completopt' contains "menuone".
1117 */
1118 static int
1119pum_enough_matches(void)
1120{
1121 compl_T *compl;
1122 int i;
1123
1124 // Don't display the popup menu if there are no matches or there is only
1125 // one (ignoring the original text).
1126 compl = compl_first_match;
1127 i = 0;
1128 do
1129 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001130 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001131 break;
1132 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001133 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001134
zeertzjq529b9ad2024-06-05 20:27:06 +02001135 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001136 return (i >= 1);
1137 return (i >= 2);
1138}
1139
Bram Moolenaar3075a452021-11-17 15:51:52 +00001140#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001141/*
1142 * Allocate Dict for the completed item.
1143 * { word, abbr, menu, kind, info }
1144 */
1145 static dict_T *
1146ins_compl_dict_alloc(compl_T *match)
1147{
1148 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1149
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001150 if (dict == NULL)
1151 return NULL;
1152
1153 dict_add_string(dict, "word", match->cp_str);
1154 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1155 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1156 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1157 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1158 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1159 dict_add_string(dict, "user_data", (char_u *)"");
1160 else
1161 dict_add_tv(dict, "user_data", &match->cp_user_data);
1162
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001163 return dict;
1164}
1165
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001166/*
1167 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1168 * completion menu is changed.
1169 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001170 static void
1171trigger_complete_changed_event(int cur)
1172{
1173 dict_T *v_event;
1174 dict_T *item;
1175 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001176 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001177
1178 if (recursive)
1179 return;
1180
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001181 if (cur < 0)
1182 item = dict_alloc();
1183 else
1184 item = ins_compl_dict_alloc(compl_curr_match);
1185 if (item == NULL)
1186 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001187 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001188 dict_add_dict(v_event, "completed_item", item);
1189 pum_set_event_info(v_event);
1190 dict_set_items_ro(v_event);
1191
1192 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001193 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001194 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001195 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001196 recursive = FALSE;
1197
Bram Moolenaar3075a452021-11-17 15:51:52 +00001198 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001199}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001200#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001201
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001202/*
glepnira218cc62024-06-03 19:32:39 +02001203 * pumitem qsort compare func
1204 */
1205 static int
zeertzjq8e567472024-06-14 20:04:42 +02001206ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001207{
1208 const int sa = (*(pumitem_T *)a).pum_score;
1209 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001210 const int ia = (*(pumitem_T *)a).pum_idx;
1211 const int ib = (*(pumitem_T *)b).pum_idx;
1212 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001213}
1214
1215/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001216 * Build a popup menu to show the completion matches.
1217 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1218 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001219 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001220 static int
1221ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001222{
1223 compl_T *compl;
1224 compl_T *shown_compl = NULL;
1225 int did_find_shown_match = FALSE;
1226 int shown_match_ok = FALSE;
1227 int i;
1228 int cur = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001229 int lead_len = 0;
glepnira218cc62024-06-03 19:32:39 +02001230 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001231 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001232 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1233 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001234
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001235 // Need to build the popup menu list.
1236 compl_match_arraysize = 0;
1237 compl = compl_first_match;
1238 if (compl_leader != NULL)
1239 lead_len = (int)STRLEN(compl_leader);
1240
1241 do
1242 {
zeertzjq551d8c32024-06-05 19:53:32 +02001243 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1244 // set the cp_score for later comparisons.
glepnira218cc62024-06-03 19:32:39 +02001245 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1246 compl->cp_score = fuzzy_match_str(compl->cp_str, compl_leader);
1247
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001248 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001249 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001250 || ins_compl_equal(compl, compl_leader, lead_len)
1251 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001252 ++compl_match_arraysize;
1253 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001254 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001255
1256 if (compl_match_arraysize == 0)
1257 return -1;
1258
1259 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1260 if (compl_match_array == NULL)
1261 return -1;
1262
1263 // If the current match is the original text don't find the first
1264 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001265 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001266 shown_match_ok = TRUE;
1267
glepnir53387c52024-05-27 15:11:01 +02001268 if (compl_leader != NULL
1269 && STRCMP(compl_leader, compl_orig_text) == 0
1270 && shown_match_ok == FALSE)
1271 compl_shown_match = compl_no_select ? compl_first_match
1272 : compl_first_match->cp_next;
1273
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001274 i = 0;
1275 compl = compl_first_match;
1276 do
1277 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001278 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001279 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001280 || ins_compl_equal(compl, compl_leader, lead_len)
1281 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001282 {
glepnira218cc62024-06-03 19:32:39 +02001283 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001284 {
1285 if (compl == compl_shown_match || did_find_shown_match)
1286 {
1287 // This item is the shown match or this is the
1288 // first displayed item after the shown match.
1289 compl_shown_match = compl;
1290 did_find_shown_match = TRUE;
1291 shown_match_ok = TRUE;
1292 }
1293 else
1294 // Remember this displayed match for when the
1295 // shown match is just below it.
1296 shown_compl = compl;
1297 cur = i;
1298 }
glepnira218cc62024-06-03 19:32:39 +02001299 else if (compl_fuzzy_match)
1300 {
glepnirf94c9c42024-06-14 21:11:56 +02001301 if (i == 0)
glepnir105f7412024-06-15 15:32:22 +02001302 shown_compl = compl;
glepnirdca57fb2024-06-04 22:01:21 +02001303 // Update the maximum fuzzy score and the shown match
1304 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001305 if (compl->cp_score > max_fuzzy_score)
1306 {
1307 did_find_shown_match = TRUE;
1308 max_fuzzy_score = compl->cp_score;
1309 compl_shown_match = compl;
glepnir65407ce2024-07-06 16:09:19 +02001310 }
1311
1312 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1313 {
1314 cur = i;
glepnira218cc62024-06-03 19:32:39 +02001315 shown_match_ok = TRUE;
1316 }
1317
glepnirdca57fb2024-06-04 22:01:21 +02001318 // If there is no "no select" condition and the max fuzzy
1319 // score is positive, or there is no completion leader or the
1320 // leader length is zero, mark the shown match as valid and
1321 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001322 if (!compl_no_select
1323 && (max_fuzzy_score > 0
1324 || (compl_leader == NULL || lead_len == 0)))
1325 {
glepnirf94c9c42024-06-14 21:11:56 +02001326 if (match_at_original_text(compl_shown_match))
glepnir105f7412024-06-15 15:32:22 +02001327 compl_shown_match = shown_compl;
glepnira218cc62024-06-03 19:32:39 +02001328 }
1329 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001330
1331 if (compl->cp_text[CPT_ABBR] != NULL)
1332 compl_match_array[i].pum_text =
1333 compl->cp_text[CPT_ABBR];
1334 else
1335 compl_match_array[i].pum_text = compl->cp_str;
1336 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1337 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001338 compl_match_array[i].pum_score = compl->cp_score;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001339 if (compl->cp_text[CPT_MENU] != NULL)
1340 compl_match_array[i++].pum_extra =
1341 compl->cp_text[CPT_MENU];
1342 else
1343 compl_match_array[i++].pum_extra = compl->cp_fname;
1344 }
1345
glepnira218cc62024-06-03 19:32:39 +02001346 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001347 {
1348 did_find_shown_match = TRUE;
1349
1350 // When the original text is the shown match don't set
1351 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001352 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001353 shown_match_ok = TRUE;
1354
1355 if (!shown_match_ok && shown_compl != NULL)
1356 {
1357 // The shown match isn't displayed, set it to the
1358 // previously displayed match.
1359 compl_shown_match = shown_compl;
1360 shown_match_ok = TRUE;
1361 }
1362 }
1363 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001364 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001365
glepnira218cc62024-06-03 19:32:39 +02001366 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001367 {
1368 for (i = 0; i < compl_match_arraysize; i++)
1369 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001370 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001371 qsort(compl_match_array, (size_t)compl_match_arraysize,
1372 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001373 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001374 }
glepnira218cc62024-06-03 19:32:39 +02001375
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001376 if (!shown_match_ok) // no displayed match at all
1377 cur = -1;
1378
1379 return cur;
1380}
1381
1382/*
1383 * Show the popup menu for the list of matches.
1384 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1385 */
1386 void
1387ins_compl_show_pum(void)
1388{
1389 int i;
1390 int cur = -1;
1391 colnr_T col;
1392
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001393 if (!pum_wanted() || !pum_enough_matches())
1394 return;
1395
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001396 // Update the screen later, before drawing the popup menu over it.
1397 pum_call_update_screen();
1398
1399 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001400 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001401 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001402 else
1403 {
1404 // popup menu already exists, only need to find the current item.
1405 for (i = 0; i < compl_match_arraysize; ++i)
1406 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1407 || compl_match_array[i].pum_text
1408 == compl_shown_match->cp_text[CPT_ABBR])
1409 {
1410 cur = i;
1411 break;
1412 }
1413 }
1414
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001415 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001416 {
1417#ifdef FEAT_EVAL
1418 if (compl_started && has_completechanged())
1419 trigger_complete_changed_event(cur);
1420#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001421 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001422 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001423
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001424 // In Replace mode when a $ is displayed at the end of the line only
1425 // part of the screen would be updated. We do need to redraw here.
1426 dollar_vcol = -1;
1427
1428 // Compute the screen column of the start of the completed text.
1429 // Use the cursor to get all wrapping and other settings right.
1430 col = curwin->w_cursor.col;
1431 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001432 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001433 pum_display(compl_match_array, compl_match_arraysize, cur);
1434 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001435
glepnircbb46b42024-02-03 18:11:13 +01001436 // After adding leader, set the current match to shown match.
1437 if (compl_started && compl_curr_match != compl_shown_match)
1438 compl_curr_match = compl_shown_match;
1439
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001440#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001441 if (has_completechanged())
1442 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001443#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001444}
1445
1446#define DICT_FIRST (1) // use just first element in "dict"
1447#define DICT_EXACT (2) // "dict" is the exact name of a file
1448
1449/*
glepnir40c1c332024-06-11 19:37:04 +02001450 * Get current completion leader
1451 */
1452 char_u *
1453ins_compl_leader(void)
1454{
glepnirf1891382024-06-17 18:35:25 +02001455 return compl_leader != NULL ? compl_leader : compl_orig_text;
glepnir40c1c332024-06-11 19:37:04 +02001456}
1457
1458/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001459 * Add any identifiers that match the given pattern "pat" in the list of
1460 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001461 */
1462 static void
1463ins_compl_dictionaries(
1464 char_u *dict_start,
1465 char_u *pat,
1466 int flags, // DICT_FIRST and/or DICT_EXACT
1467 int thesaurus) // Thesaurus completion
1468{
1469 char_u *dict = dict_start;
1470 char_u *ptr;
1471 char_u *buf;
1472 regmatch_T regmatch;
1473 char_u **files;
1474 int count;
1475 int save_p_scs;
1476 int dir = compl_direction;
1477
1478 if (*dict == NUL)
1479 {
1480#ifdef FEAT_SPELL
1481 // When 'dictionary' is empty and spell checking is enabled use
1482 // "spell".
1483 if (!thesaurus && curwin->w_p_spell)
1484 dict = (char_u *)"spell";
1485 else
1486#endif
1487 return;
1488 }
1489
1490 buf = alloc(LSIZE);
1491 if (buf == NULL)
1492 return;
1493 regmatch.regprog = NULL; // so that we can goto theend
1494
1495 // If 'infercase' is set, don't use 'smartcase' here
1496 save_p_scs = p_scs;
1497 if (curbuf->b_p_inf)
1498 p_scs = FALSE;
1499
1500 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1501 // to only match at the start of a line. Otherwise just match the
1502 // pattern. Also need to double backslashes.
1503 if (ctrl_x_mode_line_or_eval())
1504 {
1505 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1506 size_t len;
1507
1508 if (pat_esc == NULL)
1509 goto theend;
1510 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001511 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001512 if (ptr == NULL)
1513 {
1514 vim_free(pat_esc);
1515 goto theend;
1516 }
1517 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1518 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1519 vim_free(pat_esc);
1520 vim_free(ptr);
1521 }
1522 else
1523 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001524 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001525 if (regmatch.regprog == NULL)
1526 goto theend;
1527 }
1528
1529 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1530 regmatch.rm_ic = ignorecase(pat);
1531 while (*dict != NUL && !got_int && !compl_interrupted)
1532 {
1533 // copy one dictionary file name into buf
1534 if (flags == DICT_EXACT)
1535 {
1536 count = 1;
1537 files = &dict;
1538 }
1539 else
1540 {
1541 // Expand wildcards in the dictionary name, but do not allow
1542 // backticks (for security, the 'dict' option may have been set in
1543 // a modeline).
1544 copy_option_part(&dict, buf, LSIZE, ",");
1545# ifdef FEAT_SPELL
1546 if (!thesaurus && STRCMP(buf, "spell") == 0)
1547 count = -1;
1548 else
1549# endif
1550 if (vim_strchr(buf, '`') != NULL
1551 || expand_wildcards(1, &buf, &count, &files,
1552 EW_FILE|EW_SILENT) != OK)
1553 count = 0;
1554 }
1555
1556# ifdef FEAT_SPELL
1557 if (count == -1)
1558 {
1559 // Complete from active spelling. Skip "\<" in the pattern, we
1560 // don't use it as a RE.
1561 if (pat[0] == '\\' && pat[1] == '<')
1562 ptr = pat + 2;
1563 else
1564 ptr = pat;
1565 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1566 }
1567 else
1568# endif
1569 if (count > 0) // avoid warning for using "files" uninit
1570 {
1571 ins_compl_files(count, files, thesaurus, flags,
1572 &regmatch, buf, &dir);
1573 if (flags != DICT_EXACT)
1574 FreeWild(count, files);
1575 }
1576 if (flags != 0)
1577 break;
1578 }
1579
1580theend:
1581 p_scs = save_p_scs;
1582 vim_regfree(regmatch.regprog);
1583 vim_free(buf);
1584}
1585
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001586/*
1587 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1588 * skipping the word at 'skip_word'. Returns OK on success.
1589 */
1590 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001591thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001592 char_u *fname,
1593 char_u **buf_arg,
1594 int dir,
1595 char_u *skip_word)
1596{
1597 int status = OK;
1598 char_u *ptr;
1599 char_u *wstart;
1600
1601 // Add the other matches on the line
1602 ptr = *buf_arg;
1603 while (!got_int)
1604 {
1605 // Find start of the next word. Skip white
1606 // space and punctuation.
1607 ptr = find_word_start(ptr);
1608 if (*ptr == NUL || *ptr == NL)
1609 break;
1610 wstart = ptr;
1611
1612 // Find end of the word.
1613 if (has_mbyte)
1614 // Japanese words may have characters in
1615 // different classes, only separate words
1616 // with single-byte non-word characters.
1617 while (*ptr != NUL)
1618 {
1619 int l = (*mb_ptr2len)(ptr);
1620
1621 if (l < 2 && !vim_iswordc(*ptr))
1622 break;
1623 ptr += l;
1624 }
1625 else
1626 ptr = find_word_end(ptr);
1627
1628 // Add the word. Skip the regexp match.
1629 if (wstart != skip_word)
1630 {
1631 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1632 fname, dir, FALSE);
1633 if (status == FAIL)
1634 break;
1635 }
1636 }
1637
1638 *buf_arg = ptr;
1639 return status;
1640}
1641
1642/*
1643 * Process "count" dictionary/thesaurus "files" and add the text matching
1644 * "regmatch".
1645 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001646 static void
1647ins_compl_files(
1648 int count,
1649 char_u **files,
1650 int thesaurus,
1651 int flags,
1652 regmatch_T *regmatch,
1653 char_u *buf,
1654 int *dir)
1655{
1656 char_u *ptr;
1657 int i;
1658 FILE *fp;
1659 int add_r;
1660
1661 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1662 {
1663 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001664 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001665 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001666 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001667 vim_snprintf((char *)IObuff, IOSIZE,
1668 _("Scanning dictionary: %s"), (char *)files[i]);
1669 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1670 }
1671
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001672 if (fp == NULL)
1673 continue;
1674
1675 // Read dictionary file line by line.
1676 // Check each line for a match.
1677 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001678 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001679 ptr = buf;
1680 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001681 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001682 ptr = regmatch->startp[0];
1683 if (ctrl_x_mode_line_or_eval())
1684 ptr = find_line_end(ptr);
1685 else
1686 ptr = find_word_end(ptr);
1687 add_r = ins_compl_add_infercase(regmatch->startp[0],
1688 (int)(ptr - regmatch->startp[0]),
1689 p_ic, files[i], *dir, FALSE);
1690 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001691 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001692 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001693 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001694 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001695 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001696 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001697 if (add_r == OK)
1698 // if dir was BACKWARD then honor it just once
1699 *dir = FORWARD;
1700 else if (add_r == FAIL)
1701 break;
1702 // avoid expensive call to vim_regexec() when at end
1703 // of line
1704 if (*ptr == '\n' || got_int)
1705 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001706 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001707 line_breakcheck();
1708 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001709 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001710 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001711 }
1712}
1713
1714/*
1715 * Find the start of the next word.
1716 * Returns a pointer to the first char of the word. Also stops at a NUL.
1717 */
1718 char_u *
1719find_word_start(char_u *ptr)
1720{
1721 if (has_mbyte)
1722 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1723 ptr += (*mb_ptr2len)(ptr);
1724 else
1725 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1726 ++ptr;
1727 return ptr;
1728}
1729
1730/*
1731 * Find the end of the word. Assumes it starts inside a word.
1732 * Returns a pointer to just after the word.
1733 */
1734 char_u *
1735find_word_end(char_u *ptr)
1736{
1737 int start_class;
1738
1739 if (has_mbyte)
1740 {
1741 start_class = mb_get_class(ptr);
1742 if (start_class > 1)
1743 while (*ptr != NUL)
1744 {
1745 ptr += (*mb_ptr2len)(ptr);
1746 if (mb_get_class(ptr) != start_class)
1747 break;
1748 }
1749 }
1750 else
1751 while (vim_iswordc(*ptr))
1752 ++ptr;
1753 return ptr;
1754}
1755
1756/*
1757 * Find the end of the line, omitting CR and NL at the end.
1758 * Returns a pointer to just after the line.
1759 */
1760 static char_u *
1761find_line_end(char_u *ptr)
1762{
1763 char_u *s;
1764
1765 s = ptr + STRLEN(ptr);
1766 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1767 --s;
1768 return s;
1769}
1770
1771/*
1772 * Free the list of completions
1773 */
1774 static void
1775ins_compl_free(void)
1776{
1777 compl_T *match;
1778 int i;
1779
1780 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001781 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001782 VIM_CLEAR(compl_leader);
1783
1784 if (compl_first_match == NULL)
1785 return;
1786
1787 ins_compl_del_pum();
1788 pum_clear();
1789
1790 compl_curr_match = compl_first_match;
1791 do
1792 {
1793 match = compl_curr_match;
1794 compl_curr_match = compl_curr_match->cp_next;
1795 vim_free(match->cp_str);
1796 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001797 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001798 vim_free(match->cp_fname);
1799 for (i = 0; i < CPT_COUNT; ++i)
1800 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001801#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001802 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001803#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001804 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001805 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001806 compl_first_match = compl_curr_match = NULL;
1807 compl_shown_match = NULL;
1808 compl_old_match = NULL;
1809}
1810
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001811/*
1812 * Reset/clear the completion state.
1813 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001814 void
1815ins_compl_clear(void)
1816{
1817 compl_cont_status = 0;
1818 compl_started = FALSE;
1819 compl_matches = 0;
1820 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001821 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001822 VIM_CLEAR(compl_leader);
1823 edit_submode_extra = NULL;
1824 VIM_CLEAR(compl_orig_text);
1825 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001826#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001827 // clear v:completed_item
1828 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001829#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001830}
1831
1832/*
1833 * Return TRUE when Insert completion is active.
1834 */
1835 int
1836ins_compl_active(void)
1837{
1838 return compl_started;
1839}
1840
1841/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001842 * Selected one of the matches. When FALSE the match was edited or using the
1843 * longest common string.
1844 */
1845 int
1846ins_compl_used_match(void)
1847{
1848 return compl_used_match;
1849}
1850
1851/*
1852 * Initialize get longest common string.
1853 */
1854 void
1855ins_compl_init_get_longest(void)
1856{
1857 compl_get_longest = FALSE;
1858}
1859
1860/*
1861 * Returns TRUE when insert completion is interrupted.
1862 */
1863 int
1864ins_compl_interrupted(void)
1865{
1866 return compl_interrupted;
1867}
1868
1869/*
1870 * Returns TRUE if the <Enter> key selects a match in the completion popup
1871 * menu.
1872 */
1873 int
1874ins_compl_enter_selects(void)
1875{
1876 return compl_enter_selects;
1877}
1878
1879/*
1880 * Return the column where the text starts that is being completed
1881 */
1882 colnr_T
1883ins_compl_col(void)
1884{
1885 return compl_col;
1886}
1887
1888/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001889 * Return the length in bytes of the text being completed
1890 */
1891 int
1892ins_compl_len(void)
1893{
1894 return compl_length;
1895}
1896
1897/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001898 * Delete one character before the cursor and show the subset of the matches
1899 * that match the word that is now before the cursor.
1900 * Returns the character to be used, NUL if the work is done and another char
1901 * to be got from the user.
1902 */
1903 int
1904ins_compl_bs(void)
1905{
1906 char_u *line;
1907 char_u *p;
1908
1909 line = ml_get_curline();
1910 p = line + curwin->w_cursor.col;
1911 MB_PTR_BACK(line, p);
1912
1913 // Stop completion when the whole word was deleted. For Omni completion
1914 // allow the word to be deleted, we won't match everything.
1915 // Respect the 'backspace' option.
1916 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001917 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1918 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001919 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1920 - compl_length < 0))
1921 return K_BS;
1922
1923 // Deleted more than what was used to find matches or didn't finish
1924 // finding all matches: need to look for matches all over again.
1925 if (curwin->w_cursor.col <= compl_col + compl_length
1926 || ins_compl_need_restart())
1927 ins_compl_restart();
1928
1929 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001930 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001931 if (compl_leader == NULL)
1932 return K_BS;
1933
1934 ins_compl_new_leader();
1935 if (compl_shown_match != NULL)
1936 // Make sure current match is not a hidden item.
1937 compl_curr_match = compl_shown_match;
1938 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001939}
1940
1941/*
1942 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1943 * be called.
1944 */
1945 static int
1946ins_compl_need_restart(void)
1947{
1948 // Return TRUE if we didn't complete finding matches or when the
1949 // 'completefunc' returned "always" in the "refresh" dictionary item.
1950 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001951 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001952 && compl_opt_refresh_always);
1953}
1954
1955/*
1956 * Called after changing "compl_leader".
1957 * Show the popup menu with a different set of matches.
1958 * May also search for matches again if the previous search was interrupted.
1959 */
1960 static void
1961ins_compl_new_leader(void)
1962{
1963 ins_compl_del_pum();
1964 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001965 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001966 compl_used_match = FALSE;
1967
1968 if (compl_started)
1969 ins_compl_set_original_text(compl_leader);
1970 else
1971 {
1972#ifdef FEAT_SPELL
1973 spell_bad_len = 0; // need to redetect bad word
1974#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001975 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001976 // the popup menu display the changed text before the cursor. Set
1977 // "compl_restarting" to avoid that the first match is inserted.
1978 pum_call_update_screen();
1979#ifdef FEAT_GUI
1980 if (gui.in_use)
1981 {
1982 // Show the cursor after the match, not after the redrawn text.
1983 setcursor();
1984 out_flush_cursor(FALSE, FALSE);
1985 }
1986#endif
1987 compl_restarting = TRUE;
1988 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1989 compl_cont_status = 0;
1990 compl_restarting = FALSE;
1991 }
1992
1993 compl_enter_selects = !compl_used_match;
1994
1995 // Show the popup menu with a different set of matches.
1996 ins_compl_show_pum();
1997
1998 // Don't let Enter select the original text when there is no popup menu.
1999 if (compl_match_array == NULL)
2000 compl_enter_selects = FALSE;
2001}
2002
2003/*
2004 * Return the length of the completion, from the completion start column to
2005 * the cursor column. Making sure it never goes below zero.
2006 */
2007 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002008get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002009{
2010 int off = (int)curwin->w_cursor.col - (int)compl_col;
2011
2012 if (off < 0)
2013 return 0;
2014 return off;
2015}
2016
2017/*
2018 * Append one character to the match leader. May reduce the number of
2019 * matches.
2020 */
2021 void
2022ins_compl_addleader(int c)
2023{
2024 int cc;
2025
2026 if (stop_arrow() == FAIL)
2027 return;
2028 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2029 {
2030 char_u buf[MB_MAXBYTES + 1];
2031
2032 (*mb_char2bytes)(c, buf);
2033 buf[cc] = NUL;
2034 ins_char_bytes(buf, cc);
2035 if (compl_opt_refresh_always)
2036 AppendToRedobuff(buf);
2037 }
2038 else
2039 {
2040 ins_char(c);
2041 if (compl_opt_refresh_always)
2042 AppendCharToRedobuff(c);
2043 }
2044
2045 // If we didn't complete finding matches we must search again.
2046 if (ins_compl_need_restart())
2047 ins_compl_restart();
2048
2049 // When 'always' is set, don't reset compl_leader. While completing,
2050 // cursor doesn't point original position, changing compl_leader would
2051 // break redo.
2052 if (!compl_opt_refresh_always)
2053 {
2054 vim_free(compl_leader);
2055 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002056 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002057 if (compl_leader != NULL)
2058 ins_compl_new_leader();
2059 }
2060}
2061
2062/*
2063 * Setup for finding completions again without leaving CTRL-X mode. Used when
2064 * BS or a key was typed while still searching for matches.
2065 */
2066 static void
2067ins_compl_restart(void)
2068{
2069 ins_compl_free();
2070 compl_started = FALSE;
2071 compl_matches = 0;
2072 compl_cont_status = 0;
2073 compl_cont_mode = 0;
2074}
2075
2076/*
2077 * Set the first match, the original text.
2078 */
2079 static void
2080ins_compl_set_original_text(char_u *str)
2081{
2082 char_u *p;
2083
2084 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002085 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2086 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002087 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002088 {
2089 p = vim_strsave(str);
2090 if (p != NULL)
2091 {
2092 vim_free(compl_first_match->cp_str);
2093 compl_first_match->cp_str = p;
2094 }
2095 }
2096 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002097 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098 {
2099 p = vim_strsave(str);
2100 if (p != NULL)
2101 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002102 vim_free(compl_first_match->cp_prev->cp_str);
2103 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002104 }
2105 }
2106}
2107
2108/*
2109 * Append one character to the match leader. May reduce the number of
2110 * matches.
2111 */
2112 void
2113ins_compl_addfrommatch(void)
2114{
2115 char_u *p;
2116 int len = (int)curwin->w_cursor.col - (int)compl_col;
2117 int c;
2118 compl_T *cp;
2119
2120 p = compl_shown_match->cp_str;
2121 if ((int)STRLEN(p) <= len) // the match is too short
2122 {
2123 // When still at the original match use the first entry that matches
2124 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002125 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002126 return;
2127
2128 p = NULL;
2129 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002130 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002131 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002132 if (compl_leader == NULL
2133 || ins_compl_equal(cp, compl_leader,
2134 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002135 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002136 p = cp->cp_str;
2137 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002138 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002139 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002140 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002141 return;
2142 }
2143 p += len;
2144 c = PTR2CHAR(p);
2145 ins_compl_addleader(c);
2146}
2147
2148/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002149 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002150 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2151 * compl_cont_mode and compl_cont_status.
2152 * Returns TRUE when the character is not to be inserted.
2153 */
2154 static int
2155set_ctrl_x_mode(int c)
2156{
2157 int retval = FALSE;
2158
2159 switch (c)
2160 {
2161 case Ctrl_E:
2162 case Ctrl_Y:
2163 // scroll the window one line up or down
2164 ctrl_x_mode = CTRL_X_SCROLL;
2165 if (!(State & REPLACE_FLAG))
2166 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2167 else
2168 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2169 edit_submode_pre = NULL;
2170 showmode();
2171 break;
2172 case Ctrl_L:
2173 // complete whole line
2174 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2175 break;
2176 case Ctrl_F:
2177 // complete filenames
2178 ctrl_x_mode = CTRL_X_FILES;
2179 break;
2180 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002181 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002182 ctrl_x_mode = CTRL_X_DICTIONARY;
2183 break;
2184 case Ctrl_R:
2185 // Register insertion without exiting CTRL-X mode
2186 // Simply allow ^R to happen without affecting ^X mode
2187 break;
2188 case Ctrl_T:
2189 // complete words from a thesaurus
2190 ctrl_x_mode = CTRL_X_THESAURUS;
2191 break;
2192#ifdef FEAT_COMPL_FUNC
2193 case Ctrl_U:
2194 // user defined completion
2195 ctrl_x_mode = CTRL_X_FUNCTION;
2196 break;
2197 case Ctrl_O:
2198 // omni completion
2199 ctrl_x_mode = CTRL_X_OMNI;
2200 break;
2201#endif
2202 case 's':
2203 case Ctrl_S:
2204 // complete spelling suggestions
2205 ctrl_x_mode = CTRL_X_SPELL;
2206#ifdef FEAT_SPELL
2207 ++emsg_off; // Avoid getting the E756 error twice.
2208 spell_back_to_badword();
2209 --emsg_off;
2210#endif
2211 break;
2212 case Ctrl_RSB:
2213 // complete tag names
2214 ctrl_x_mode = CTRL_X_TAGS;
2215 break;
2216#ifdef FEAT_FIND_ID
2217 case Ctrl_I:
2218 case K_S_TAB:
2219 // complete keywords from included files
2220 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2221 break;
2222 case Ctrl_D:
2223 // complete definitions from included files
2224 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2225 break;
2226#endif
2227 case Ctrl_V:
2228 case Ctrl_Q:
2229 // complete vim commands
2230 ctrl_x_mode = CTRL_X_CMDLINE;
2231 break;
2232 case Ctrl_Z:
2233 // stop completion
2234 ctrl_x_mode = CTRL_X_NORMAL;
2235 edit_submode = NULL;
2236 showmode();
2237 retval = TRUE;
2238 break;
2239 case Ctrl_P:
2240 case Ctrl_N:
2241 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2242 // just started ^X mode, or there were enough ^X's to cancel
2243 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2244 // do normal expansion when interrupting a different mode (say
2245 // ^X^F^X^P or ^P^X^X^P, see below)
2246 // nothing changes if interrupting mode 0, (eg, the flag
2247 // doesn't change when going to ADDING mode -- Acevedo
2248 if (!(compl_cont_status & CONT_INTRPT))
2249 compl_cont_status |= CONT_LOCAL;
2250 else if (compl_cont_mode != 0)
2251 compl_cont_status &= ~CONT_LOCAL;
2252 // FALLTHROUGH
2253 default:
2254 // If we have typed at least 2 ^X's... for modes != 0, we set
2255 // compl_cont_status = 0 (eg, as if we had just started ^X
2256 // mode).
2257 // For mode 0, we set "compl_cont_mode" to an impossible
2258 // value, in both cases ^X^X can be used to restart the same
2259 // mode (avoiding ADDING mode).
2260 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2261 // 'complete' and local ^P expansions respectively.
2262 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2263 // mode -- Acevedo
2264 if (c == Ctrl_X)
2265 {
2266 if (compl_cont_mode != 0)
2267 compl_cont_status = 0;
2268 else
2269 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2270 }
2271 ctrl_x_mode = CTRL_X_NORMAL;
2272 edit_submode = NULL;
2273 showmode();
2274 break;
2275 }
2276
2277 return retval;
2278}
2279
2280/*
2281 * Stop insert completion mode
2282 */
2283 static int
2284ins_compl_stop(int c, int prev_mode, int retval)
2285{
2286 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002287 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002288
2289 // Get here when we have finished typing a sequence of ^N and
2290 // ^P or other completion characters in CTRL-X mode. Free up
2291 // memory that was used, and make sure we can redo the insert.
2292 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2293 {
2294 // If any of the original typed text has been changed, eg when
2295 // ignorecase is set, we must add back-spaces to the redo
2296 // buffer. We add as few as necessary to delete just the part
2297 // of the original text that has changed.
2298 // When using the longest match, edited the match or used
2299 // CTRL-E then don't use the current match.
2300 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2301 ptr = compl_curr_match->cp_str;
2302 else
2303 ptr = NULL;
2304 ins_compl_fixRedoBufForLeader(ptr);
2305 }
2306
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002307 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002308
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002309 // When completing whole lines: fix indent for 'cindent'.
2310 // Otherwise, break line if it's too long.
2311 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2312 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002313 // re-indent the current line
2314 if (want_cindent)
2315 {
2316 do_c_expr_indent();
2317 want_cindent = FALSE; // don't do it again
2318 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002319 }
2320 else
2321 {
2322 int prev_col = curwin->w_cursor.col;
2323
2324 // put the cursor on the last char, for 'tw' formatting
2325 if (prev_col > 0)
2326 dec_cursor();
2327 // only format when something was inserted
2328 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2329 insertchar(NUL, 0, -1);
2330 if (prev_col > 0
2331 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2332 inc_cursor();
2333 }
2334
2335 // If the popup menu is displayed pressing CTRL-Y means accepting
2336 // the selection without inserting anything. When
2337 // compl_enter_selects is set the Enter key does the same.
2338 if ((c == Ctrl_Y || (compl_enter_selects
2339 && (c == CAR || c == K_KENTER || c == NL)))
2340 && pum_visible())
2341 retval = TRUE;
2342
2343 // CTRL-E means completion is Ended, go back to the typed text.
2344 // but only do this, if the Popup is still visible
2345 if (c == Ctrl_E)
2346 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002347 char_u *p = NULL;
2348
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002349 ins_compl_delete();
2350 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002351 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002352 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002353 p = compl_orig_text;
2354 if (p != NULL)
2355 {
2356 int compl_len = get_compl_len();
2357 int len = (int)STRLEN(p);
2358
2359 if (len > compl_len)
2360 ins_bytes_len(p + compl_len, len - compl_len);
2361 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002362 retval = TRUE;
2363 }
2364
2365 auto_format(FALSE, TRUE);
2366
2367 // Trigger the CompleteDonePre event to give scripts a chance to
2368 // act upon the completion before clearing the info, and restore
2369 // ctrl_x_mode, so that complete_info() can be used.
2370 ctrl_x_mode = prev_mode;
2371 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2372
2373 ins_compl_free();
2374 compl_started = FALSE;
2375 compl_matches = 0;
2376 if (!shortmess(SHM_COMPLETIONMENU))
2377 msg_clr_cmdline(); // necessary for "noshowmode"
2378 ctrl_x_mode = CTRL_X_NORMAL;
2379 compl_enter_selects = FALSE;
2380 if (edit_submode != NULL)
2381 {
2382 edit_submode = NULL;
2383 showmode();
2384 }
2385
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002386 if (c == Ctrl_C && cmdwin_type != 0)
2387 // Avoid the popup menu remains displayed when leaving the
2388 // command line window.
2389 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002390 // Indent now if a key was typed that is in 'cinkeys'.
2391 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2392 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002393 // Trigger the CompleteDone event to give scripts a chance to act
2394 // upon the end of completion.
2395 ins_apply_autocmds(EVENT_COMPLETEDONE);
2396
2397 return retval;
2398}
2399
2400/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002401 * Prepare for Insert mode completion, or stop it.
2402 * Called just after typing a character in Insert mode.
2403 * Returns TRUE when the character is not to be inserted;
2404 */
2405 int
2406ins_compl_prep(int c)
2407{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002408 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002409 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002410
2411 // Forget any previous 'special' messages if this is actually
2412 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2413 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2414 edit_submode_extra = NULL;
2415
zeertzjq440d4cb2023-03-02 17:51:32 +00002416 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002417 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002418 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002419 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002420 return retval;
2421
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002422#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002423 // Ignore mouse events in a popup window
2424 if (is_mouse_key(c))
2425 {
2426 // Ignore drag and release events, the position does not need to be in
2427 // the popup and it may have just closed.
2428 if (c == K_LEFTRELEASE
2429 || c == K_LEFTRELEASE_NM
2430 || c == K_MIDDLERELEASE
2431 || c == K_RIGHTRELEASE
2432 || c == K_X1RELEASE
2433 || c == K_X2RELEASE
2434 || c == K_LEFTDRAG
2435 || c == K_MIDDLEDRAG
2436 || c == K_RIGHTDRAG
2437 || c == K_X1DRAG
2438 || c == K_X2DRAG)
2439 return retval;
2440 if (popup_visible)
2441 {
2442 int row = mouse_row;
2443 int col = mouse_col;
2444 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2445
2446 if (wp != NULL && WIN_IS_POPUP(wp))
2447 return retval;
2448 }
2449 }
2450#endif
2451
zeertzjqdca29d92021-08-31 19:12:51 +02002452 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2453 {
2454 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2455 || !vim_is_ctrl_x_key(c))
2456 {
2457 // Not starting another completion mode.
2458 ctrl_x_mode = CTRL_X_CMDLINE;
2459
2460 // CTRL-X CTRL-Z should stop completion without inserting anything
2461 if (c == Ctrl_Z)
2462 retval = TRUE;
2463 }
2464 else
2465 {
2466 ctrl_x_mode = CTRL_X_CMDLINE;
2467
2468 // Other CTRL-X keys first stop completion, then start another
2469 // completion mode.
2470 ins_compl_prep(' ');
2471 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2472 }
2473 }
2474
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002475 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002476 if (ctrl_x_mode_not_defined_yet()
2477 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002478 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002479 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002480 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002481 }
2482
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002483 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002484 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2485 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002486 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002487 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002488 {
2489 // We're already in CTRL-X mode, do we stay in it?
2490 if (!vim_is_ctrl_x_key(c))
2491 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002492 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002493 ctrl_x_mode = CTRL_X_NORMAL;
2494 else
2495 ctrl_x_mode = CTRL_X_FINISHED;
2496 edit_submode = NULL;
2497 }
2498 showmode();
2499 }
2500
2501 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2502 {
2503 // Show error message from attempted keyword completion (probably
2504 // 'Pattern not found') until another key is hit, then go back to
2505 // showing what mode we are in.
2506 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002507 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002508 && c != Ctrl_R && !ins_compl_pum_key(c))
2509 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002510 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002511 }
2512 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2513 // Trigger the CompleteDone event to give scripts a chance to act
2514 // upon the (possibly failed) completion.
2515 ins_apply_autocmds(EVENT_COMPLETEDONE);
2516
LemonBoy2bf52dd2022-04-09 18:17:34 +01002517 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002518
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002519 // reset continue_* if we left expansion-mode, if we stay they'll be
2520 // (re)set properly in ins_complete()
2521 if (!vim_is_ctrl_x_key(c))
2522 {
2523 compl_cont_status = 0;
2524 compl_cont_mode = 0;
2525 }
2526
2527 return retval;
2528}
2529
2530/*
2531 * Fix the redo buffer for the completion leader replacing some of the typed
2532 * text. This inserts backspaces and appends the changed text.
2533 * "ptr" is the known leader text or NUL.
2534 */
2535 static void
2536ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2537{
2538 int len;
2539 char_u *p;
2540 char_u *ptr = ptr_arg;
2541
2542 if (ptr == NULL)
2543 {
2544 if (compl_leader != NULL)
2545 ptr = compl_leader;
2546 else
2547 return; // nothing to do
2548 }
2549 if (compl_orig_text != NULL)
2550 {
2551 p = compl_orig_text;
2552 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2553 ;
2554 if (len > 0)
2555 len -= (*mb_head_off)(p, p + len);
2556 for (p += len; *p != NUL; MB_PTR_ADV(p))
2557 AppendCharToRedobuff(K_BS);
2558 }
2559 else
2560 len = 0;
2561 if (ptr != NULL)
2562 AppendToRedobuffLit(ptr + len, -1);
2563}
2564
2565/*
2566 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2567 * (depending on flag) starting from buf and looking for a non-scanned
2568 * buffer (other than curbuf). curbuf is special, if it is called with
2569 * buf=curbuf then it has to be the first call for a given flag/expansion.
2570 *
2571 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2572 */
2573 static buf_T *
2574ins_compl_next_buf(buf_T *buf, int flag)
2575{
2576 static win_T *wp = NULL;
2577
2578 if (flag == 'w') // just windows
2579 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002580 if (buf == curbuf || !win_valid(wp))
2581 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002582 wp = curwin;
2583 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2584 && wp->w_buffer->b_scanned)
2585 ;
2586 buf = wp->w_buffer;
2587 }
2588 else
2589 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2590 // (unlisted buffers)
2591 // When completing whole lines skip unloaded buffers.
2592 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2593 && ((flag == 'U'
2594 ? buf->b_p_bl
2595 : (!buf->b_p_bl
2596 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2597 || buf->b_scanned))
2598 ;
2599 return buf;
2600}
2601
2602#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002603
2604# ifdef FEAT_EVAL
2605static callback_T cfu_cb; // 'completefunc' callback function
2606static callback_T ofu_cb; // 'omnifunc' callback function
2607static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2608# endif
2609
2610/*
2611 * Copy a global callback function to a buffer local callback.
2612 */
2613 static void
2614copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2615{
2616 free_callback(bufcb);
2617 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2618 copy_callback(bufcb, globcb);
2619}
2620
2621/*
2622 * Parse the 'completefunc' option value and set the callback function.
2623 * Invoked when the 'completefunc' option is set. The option value can be a
2624 * name of a function (string), or function(<name>) or funcref(<name>) or a
2625 * lambda expression.
2626 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002627 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002628did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002629{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002630 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2631 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002632
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002633 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002634
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002635 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002636}
2637
2638/*
2639 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002640 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002641 */
2642 void
2643set_buflocal_cfu_callback(buf_T *buf UNUSED)
2644{
2645# ifdef FEAT_EVAL
2646 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2647# endif
2648}
2649
2650/*
2651 * Parse the 'omnifunc' option value and set the callback function.
2652 * Invoked when the 'omnifunc' option is set. The option value can be a
2653 * name of a function (string), or function(<name>) or funcref(<name>) or a
2654 * lambda expression.
2655 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002656 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002657did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002658{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002659 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2660 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002661
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002662 set_buflocal_ofu_callback(curbuf);
2663 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002664}
2665
2666/*
2667 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002668 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002669 */
2670 void
2671set_buflocal_ofu_callback(buf_T *buf UNUSED)
2672{
2673# ifdef FEAT_EVAL
2674 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2675# endif
2676}
2677
2678/*
2679 * Parse the 'thesaurusfunc' option value and set the callback function.
2680 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2681 * name of a function (string), or function(<name>) or funcref(<name>) or a
2682 * lambda expression.
2683 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002684 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002685did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002686{
2687 int retval;
2688
2689 if (*curbuf->b_p_tsrfu != NUL)
2690 {
2691 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002692 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2693 &curbuf->b_tsrfu_cb);
2694 }
2695 else
2696 {
2697 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002698 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2699 }
2700
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002701 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002702}
2703
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002704/*
2705 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002706 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002707 */
2708 int
2709set_ref_in_insexpand_funcs(int copyID)
2710{
2711 int abort = FALSE;
2712
2713 abort = set_ref_in_callback(&cfu_cb, copyID);
2714 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2715 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2716
2717 return abort;
2718}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002719
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002720/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002721 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002722 */
2723 static char_u *
2724get_complete_funcname(int type)
2725{
2726 switch (type)
2727 {
2728 case CTRL_X_FUNCTION:
2729 return curbuf->b_p_cfu;
2730 case CTRL_X_OMNI:
2731 return curbuf->b_p_ofu;
2732 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002733 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002734 default:
2735 return (char_u *)"";
2736 }
2737}
2738
2739/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002740 * Get the callback to use for insert mode completion.
2741 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002742 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002743get_insert_callback(int type)
2744{
2745 if (type == CTRL_X_FUNCTION)
2746 return &curbuf->b_cfu_cb;
2747 if (type == CTRL_X_OMNI)
2748 return &curbuf->b_ofu_cb;
2749 // CTRL_X_THESAURUS
2750 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2751}
2752
2753/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002754 * Execute user defined complete function 'completefunc', 'omnifunc' or
2755 * 'thesaurusfunc', and get matches in "matches".
2756 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002757 */
2758 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002759expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002760{
2761 list_T *matchlist = NULL;
2762 dict_T *matchdict = NULL;
2763 typval_T args[3];
2764 char_u *funcname;
2765 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002766 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002767 typval_T rettv;
2768 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002769 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002770
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002771 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002772 if (*funcname == NUL)
2773 return;
2774
2775 // Call 'completefunc' to obtain the list of matches.
2776 args[0].v_type = VAR_NUMBER;
2777 args[0].vval.v_number = 0;
2778 args[1].v_type = VAR_STRING;
2779 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2780 args[2].v_type = VAR_UNKNOWN;
2781
2782 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002783 // Lock the text to avoid weird things from happening. Also disallow
2784 // switching to another window, it should not be needed and may end up in
2785 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002786 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002787
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002788 cb = get_insert_callback(type);
2789 retval = call_callback(cb, 0, &rettv, 2, args);
2790
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002791 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002792 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002793 {
2794 switch (rettv.v_type)
2795 {
2796 case VAR_LIST:
2797 matchlist = rettv.vval.v_list;
2798 break;
2799 case VAR_DICT:
2800 matchdict = rettv.vval.v_dict;
2801 break;
2802 case VAR_SPECIAL:
2803 if (rettv.vval.v_number == VVAL_NONE)
2804 compl_opt_suppress_empty = TRUE;
2805 // FALLTHROUGH
2806 default:
2807 // TODO: Give error message?
2808 clear_tv(&rettv);
2809 break;
2810 }
2811 }
zeertzjqcfe45652022-05-27 17:26:55 +01002812 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002813
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002814 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002815 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002816 validate_cursor();
2817 if (!EQUAL_POS(curwin->w_cursor, pos))
2818 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002819 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002820 goto theend;
2821 }
2822
2823 if (matchlist != NULL)
2824 ins_compl_add_list(matchlist);
2825 else if (matchdict != NULL)
2826 ins_compl_add_dict(matchdict);
2827
2828theend:
2829 // Restore State, it might have been changed.
2830 State = save_State;
2831
2832 if (matchdict != NULL)
2833 dict_unref(matchdict);
2834 if (matchlist != NULL)
2835 list_unref(matchlist);
2836}
2837#endif // FEAT_COMPL_FUNC
2838
2839#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2840/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002841 * Add a match to the list of matches from a typeval_T.
2842 * If the given string is already in the list of completions, then return
2843 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2844 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002845 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002846 */
2847 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002848ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002849{
2850 char_u *word;
2851 int dup = FALSE;
2852 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002853 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002854 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002855 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002856 int status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002857
Bram Moolenaar08928322020-01-04 14:32:48 +01002858 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002859 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2860 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002861 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2862 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2863 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2864 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2865 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
2866 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2867 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2868 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002869 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002870 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2871 dup = dict_get_number(tv->vval.v_dict, "dup");
2872 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2873 empty = dict_get_number(tv->vval.v_dict, "empty");
2874 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2875 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002876 flags |= CP_EQUAL;
2877 }
2878 else
2879 {
2880 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002881 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002882 }
2883 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002884 {
2885 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002886 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002887 }
2888 status = ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
2889 if (status != OK)
2890 clear_tv(&user_data);
2891 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002892}
2893
2894/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002895 * Add completions from a list.
2896 */
2897 static void
2898ins_compl_add_list(list_T *list)
2899{
2900 listitem_T *li;
2901 int dir = compl_direction;
2902
2903 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002904 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002905 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002906 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002907 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002908 // if dir was BACKWARD then honor it just once
2909 dir = FORWARD;
2910 else if (did_emsg)
2911 break;
2912 }
2913}
2914
2915/*
2916 * Add completions from a dict.
2917 */
2918 static void
2919ins_compl_add_dict(dict_T *dict)
2920{
2921 dictitem_T *di_refresh;
2922 dictitem_T *di_words;
2923
2924 // Check for optional "refresh" item.
2925 compl_opt_refresh_always = FALSE;
2926 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2927 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2928 {
2929 char_u *v = di_refresh->di_tv.vval.v_string;
2930
2931 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2932 compl_opt_refresh_always = TRUE;
2933 }
2934
2935 // Add completions from a "words" list.
2936 di_words = dict_find(dict, (char_u *)"words", 5);
2937 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2938 ins_compl_add_list(di_words->di_tv.vval.v_list);
2939}
2940
2941/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002942 * Start completion for the complete() function.
2943 * "startcol" is where the matched text starts (1 is first column).
2944 * "list" is the list of matches.
2945 */
2946 static void
2947set_completion(colnr_T startcol, list_T *list)
2948{
2949 int save_w_wrow = curwin->w_wrow;
2950 int save_w_leftcol = curwin->w_leftcol;
2951 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002952 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002953 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2954 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2955 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002956
2957 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002958 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002959 ins_compl_prep(' ');
2960 ins_compl_clear();
2961 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002962 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002963
2964 compl_direction = FORWARD;
2965 if (startcol > curwin->w_cursor.col)
2966 startcol = curwin->w_cursor.col;
2967 compl_col = startcol;
2968 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2969 // compl_pattern doesn't need to be set
2970 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2971 if (p_ic)
2972 flags |= CP_ICASE;
2973 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002974 -1, NULL, NULL, NULL, 0,
2975 flags | CP_FAST, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002976 return;
2977
2978 ctrl_x_mode = CTRL_X_EVAL;
2979
2980 ins_compl_add_list(list);
2981 compl_matches = ins_compl_make_cyclic();
2982 compl_started = TRUE;
2983 compl_used_match = TRUE;
2984 compl_cont_status = 0;
2985
2986 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01002987 int no_select = compl_no_select || compl_longest;
2988 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002989 {
2990 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01002991 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002992 // Down/Up has no real effect.
2993 ins_complete(K_UP, FALSE);
2994 }
2995 else
2996 ins_complete(Ctrl_N, FALSE);
2997 compl_enter_selects = compl_no_insert;
2998
2999 // Lazily show the popup menu, unless we got interrupted.
3000 if (!compl_interrupted)
3001 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003002 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003003 out_flush();
3004}
3005
3006/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003007 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003008 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003009 void
3010f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003011{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003012 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003013
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003014 if (in_vim9script()
3015 && (check_for_number_arg(argvars, 0) == FAIL
3016 || check_for_list_arg(argvars, 1) == FAIL))
3017 return;
3018
Bram Moolenaar24959102022-05-07 20:01:16 +01003019 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003020 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003021 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003022 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003023 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003024
3025 // Check for undo allowed here, because if something was already inserted
3026 // the line was already saved for undo and this check isn't done.
3027 if (!undo_allowed())
3028 return;
3029
Bram Moolenaard83392a2022-09-01 12:22:46 +01003030 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003031 {
3032 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3033 if (startcol > 0)
3034 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003035 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003036}
3037
3038/*
3039 * "complete_add()" function
3040 */
3041 void
3042f_complete_add(typval_T *argvars, typval_T *rettv)
3043{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003044 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003045 return;
3046
Bram Moolenaar440cf092021-04-03 20:13:30 +02003047 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003048}
3049
3050/*
3051 * "complete_check()" function
3052 */
3053 void
3054f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3055{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003056 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003057 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003058
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003059 ins_compl_check_keys(0, TRUE);
3060 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003061
3062 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003063}
3064
3065/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003066 * Return Insert completion mode name string
3067 */
3068 static char_u *
3069ins_compl_mode(void)
3070{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003071 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003072 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3073
3074 return (char_u *)"";
3075}
3076
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003077/*
3078 * Assign the sequence number to all the completion matches which don't have
3079 * one assigned yet.
3080 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003081 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003082ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003083{
3084 int number = 0;
3085 compl_T *match;
3086
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003087 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003088 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003089 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003090 // This should normally succeed already at the first loop
3091 // cycle, so it's fast!
3092 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003093 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003094 if (match->cp_number != -1)
3095 {
3096 number = match->cp_number;
3097 break;
3098 }
3099 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003100 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003101 for (match = match->cp_next;
3102 match != NULL && match->cp_number == -1;
3103 match = match->cp_next)
3104 match->cp_number = ++number;
3105 }
3106 else // BACKWARD
3107 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003108 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003109 // number. This should normally succeed already at the
3110 // first loop cycle, so it's fast!
3111 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003112 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003113 if (match->cp_number != -1)
3114 {
3115 number = match->cp_number;
3116 break;
3117 }
3118 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003119 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003120 for (match = match->cp_prev; match
3121 && match->cp_number == -1;
3122 match = match->cp_prev)
3123 match->cp_number = ++number;
3124 }
3125}
3126
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003127/*
3128 * Get complete information
3129 */
3130 static void
3131get_complete_info(list_T *what_list, dict_T *retdict)
3132{
3133 int ret = OK;
3134 listitem_T *item;
3135#define CI_WHAT_MODE 0x01
3136#define CI_WHAT_PUM_VISIBLE 0x02
3137#define CI_WHAT_ITEMS 0x04
3138#define CI_WHAT_SELECTED 0x08
3139#define CI_WHAT_INSERTED 0x10
3140#define CI_WHAT_ALL 0xff
3141 int what_flag;
3142
3143 if (what_list == NULL)
3144 what_flag = CI_WHAT_ALL;
3145 else
3146 {
3147 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003148 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003149 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003150 {
3151 char_u *what = tv_get_string(&item->li_tv);
3152
3153 if (STRCMP(what, "mode") == 0)
3154 what_flag |= CI_WHAT_MODE;
3155 else if (STRCMP(what, "pum_visible") == 0)
3156 what_flag |= CI_WHAT_PUM_VISIBLE;
3157 else if (STRCMP(what, "items") == 0)
3158 what_flag |= CI_WHAT_ITEMS;
3159 else if (STRCMP(what, "selected") == 0)
3160 what_flag |= CI_WHAT_SELECTED;
3161 else if (STRCMP(what, "inserted") == 0)
3162 what_flag |= CI_WHAT_INSERTED;
3163 }
3164 }
3165
3166 if (ret == OK && (what_flag & CI_WHAT_MODE))
3167 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3168
3169 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3170 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3171
Girish Palya8950bf72024-03-20 20:07:29 +01003172 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003173 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003174 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003175 dict_T *di;
3176 compl_T *match;
3177 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003178
Girish Palya8950bf72024-03-20 20:07:29 +01003179 if (what_flag & CI_WHAT_ITEMS)
3180 {
3181 li = list_alloc();
3182 if (li == NULL)
3183 return;
3184 ret = dict_add_list(retdict, "items", li);
3185 }
3186 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3187 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3188 ins_compl_update_sequence_numbers();
3189 if (ret == OK && compl_first_match != NULL)
3190 {
3191 int list_idx = 0;
3192 match = compl_first_match;
3193 do
3194 {
3195 if (!match_at_original_text(match))
3196 {
3197 if (what_flag & CI_WHAT_ITEMS)
3198 {
3199 di = dict_alloc();
3200 if (di == NULL)
3201 return;
3202 ret = list_append_dict(li, di);
3203 if (ret != OK)
3204 return;
3205 dict_add_string(di, "word", match->cp_str);
3206 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3207 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3208 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3209 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3210 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3211 // Add an empty string for backwards compatibility
3212 dict_add_string(di, "user_data", (char_u *)"");
3213 else
3214 dict_add_tv(di, "user_data", &match->cp_user_data);
3215 }
3216 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3217 selected_idx = list_idx;
3218 list_idx += 1;
3219 }
3220 match = match->cp_next;
3221 }
3222 while (match != NULL && !is_first_match(match));
3223 }
3224 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3225 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003226 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003227
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003228 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3229 {
3230 // TODO
3231 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003232}
3233
3234/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003235 * "complete_info()" function
3236 */
3237 void
3238f_complete_info(typval_T *argvars, typval_T *rettv)
3239{
3240 list_T *what_list = NULL;
3241
Bram Moolenaar93a10962022-06-16 11:42:09 +01003242 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003243 return;
3244
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003245 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3246 return;
3247
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003248 if (argvars[0].v_type != VAR_UNKNOWN)
3249 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003250 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003251 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003252 what_list = argvars[0].vval.v_list;
3253 }
3254 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003255}
3256#endif
3257
3258/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003259 * Returns TRUE when using a user-defined function for thesaurus completion.
3260 */
3261 static int
3262thesaurus_func_complete(int type UNUSED)
3263{
3264#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003265 return type == CTRL_X_THESAURUS
3266 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003267#else
3268 return FALSE;
3269#endif
3270}
3271
3272/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003273 * Return value of process_next_cpt_value()
3274 */
3275enum
3276{
3277 INS_COMPL_CPT_OK = 1,
3278 INS_COMPL_CPT_CONT,
3279 INS_COMPL_CPT_END
3280};
3281
3282/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003283 * state information used for getting the next set of insert completion
3284 * matches.
3285 */
3286typedef struct
3287{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003288 char_u *e_cpt_copy; // copy of 'complete'
3289 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003290 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003291 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003292 pos_T prev_match_pos; // previous match position
3293 int set_match_pos; // save first_match_pos/last_match_pos
3294 pos_T first_match_pos; // first match position
3295 pos_T last_match_pos; // last match position
3296 int found_all; // found all matches of a certain type.
3297 char_u *dict; // dictionary file to search
3298 int dict_f; // "dict" is an exact file name or not
3299} ins_compl_next_state_T;
3300
3301/*
3302 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003303 *
3304 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003305 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003306 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003307 * st->found_all - all matches of this type are found
3308 * st->ins_buf - search for completions in this buffer
3309 * st->first_match_pos - position of the first completion match
3310 * st->last_match_pos - position of the last completion match
3311 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003312 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003313 * st->dict - name of the dictionary or thesaurus file to search
3314 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003315 *
3316 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003317 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3318 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003319 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003320 */
3321 static int
3322process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003323 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003324 int *compl_type_arg,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003325 pos_T *start_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003326{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003327 int compl_type = -1;
3328 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003329
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003330 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003331
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003332 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3333 st->e_cpt++;
3334
3335 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003336 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003337 st->ins_buf = curbuf;
3338 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003339 // Move the cursor back one character so that ^N can match the
3340 // word immediately after the cursor.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003341 if (ctrl_x_mode_normal() && dec(&st->first_match_pos) < 0)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003342 {
3343 // Move the cursor to after the last character in the
3344 // buffer, so that word at start of buffer is found
3345 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003346 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003347 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003348 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003349 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003350 compl_type = 0;
3351
3352 // Remember the first match so that the loop stops when we
3353 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003354 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003355 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003356 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003357 && (st->ins_buf = ins_compl_next_buf(
3358 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003359 {
3360 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003361 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003362 {
3363 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003364 st->first_match_pos.col = st->last_match_pos.col = 0;
3365 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3366 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003367 compl_type = 0;
3368 }
3369 else // unloaded buffer, scan like dictionary
3370 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003371 st->found_all = TRUE;
3372 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003373 {
3374 status = INS_COMPL_CPT_CONT;
3375 goto done;
3376 }
3377 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003378 st->dict = st->ins_buf->b_fname;
3379 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003380 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003381 if (!shortmess(SHM_COMPLETIONSCAN))
3382 {
3383 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3384 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3385 st->ins_buf->b_fname == NULL
3386 ? buf_spname(st->ins_buf)
3387 : st->ins_buf->b_sfname == NULL
3388 ? st->ins_buf->b_fname
3389 : st->ins_buf->b_sfname);
3390 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3391 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003392 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003393 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394 status = INS_COMPL_CPT_END;
3395 else
3396 {
3397 if (ctrl_x_mode_line_or_eval())
3398 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003399 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003400 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003401 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003402 compl_type = CTRL_X_DICTIONARY;
3403 else
3404 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003405 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003406 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003407 st->dict = st->e_cpt;
3408 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003409 }
3410 }
3411#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003412 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003413 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003414 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003415 compl_type = CTRL_X_PATH_DEFINES;
3416#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003417 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003418 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003419 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003420 if (!shortmess(SHM_COMPLETIONSCAN))
3421 {
3422 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3423 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3424 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3425 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003426 }
3427 else
3428 compl_type = -1;
3429
3430 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003431 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003432
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003433 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003434 if (compl_type == -1)
3435 status = INS_COMPL_CPT_CONT;
3436 }
3437
3438done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003439 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003440 return status;
3441}
3442
3443#ifdef FEAT_FIND_ID
3444/*
3445 * Get the next set of identifiers or defines matching "compl_pattern" in
3446 * included files.
3447 */
3448 static void
3449get_next_include_file_completion(int compl_type)
3450{
3451 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003452 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003453 (compl_type == CTRL_X_PATH_DEFINES
3454 && !(compl_cont_status & CONT_SOL))
3455 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003456 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003457}
3458#endif
3459
3460/*
3461 * Get the next set of words matching "compl_pattern" in dictionary or
3462 * thesaurus files.
3463 */
3464 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003465get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003466{
3467#ifdef FEAT_COMPL_FUNC
3468 if (thesaurus_func_complete(compl_type))
3469 expand_by_function(compl_type, compl_pattern);
3470 else
3471#endif
3472 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003473 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003474 : (compl_type == CTRL_X_THESAURUS
3475 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3476 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3477 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003478 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003479 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003480}
3481
3482/*
3483 * Get the next set of tag names matching "compl_pattern".
3484 */
3485 static void
3486get_next_tag_completion(void)
3487{
3488 int save_p_ic;
3489 char_u **matches;
3490 int num_matches;
3491
3492 // set p_ic according to p_ic, p_scs and pat for find_tags().
3493 save_p_ic = p_ic;
3494 p_ic = ignorecase(compl_pattern);
3495
3496 // Find up to TAG_MANY matches. Avoids that an enormous number
3497 // of matches is found when compl_pattern is empty
3498 g_tag_at_cursor = TRUE;
3499 if (find_tags(compl_pattern, &num_matches, &matches,
3500 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003501 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003502 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3503 ins_compl_add_matches(num_matches, matches, p_ic);
3504 g_tag_at_cursor = FALSE;
3505 p_ic = save_p_ic;
3506}
3507
3508/*
3509 * Get the next set of filename matching "compl_pattern".
3510 */
3511 static void
3512get_next_filename_completion(void)
3513{
3514 char_u **matches;
3515 int num_matches;
3516
3517 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3518 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3519 return;
3520
3521 // May change home directory back to "~".
3522 tilde_replace(compl_pattern, num_matches, matches);
3523#ifdef BACKSLASH_IN_FILENAME
3524 if (curbuf->b_p_csl[0] != NUL)
3525 {
3526 int i;
3527
3528 for (i = 0; i < num_matches; ++i)
3529 {
3530 char_u *ptr = matches[i];
3531
3532 while (*ptr != NUL)
3533 {
3534 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3535 *ptr = '/';
3536 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3537 *ptr = '\\';
3538 ptr += (*mb_ptr2len)(ptr);
3539 }
3540 }
3541 }
3542#endif
3543 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
3544}
3545
3546/*
3547 * Get the next set of command-line completions matching "compl_pattern".
3548 */
3549 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003550get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003551{
3552 char_u **matches;
3553 int num_matches;
3554
3555 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003556 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003557 ins_compl_add_matches(num_matches, matches, FALSE);
3558}
3559
3560/*
3561 * Get the next set of spell suggestions matching "compl_pattern".
3562 */
3563 static void
3564get_next_spell_completion(linenr_T lnum UNUSED)
3565{
3566#ifdef FEAT_SPELL
3567 char_u **matches;
3568 int num_matches;
3569
3570 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3571 if (num_matches > 0)
3572 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003573 else
3574 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003575#endif
3576}
3577
3578/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003579 * Return the next word or line from buffer "ins_buf" at position
3580 * "cur_match_pos" for completion. The length of the match is set in "len".
3581 */
3582 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003583ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003584 buf_T *ins_buf, // buffer being scanned
3585 pos_T *cur_match_pos, // current match position
3586 int *match_len,
3587 int *cont_s_ipos) // next ^X<> will set initial_pos
3588{
3589 char_u *ptr;
3590 int len;
3591
3592 *match_len = 0;
3593 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3594 cur_match_pos->col;
3595 if (ctrl_x_mode_line_or_eval())
3596 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003597 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003598 {
3599 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3600 return NULL;
3601 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3602 if (!p_paste)
3603 ptr = skipwhite(ptr);
3604 }
3605 len = (int)STRLEN(ptr);
3606 }
3607 else
3608 {
3609 char_u *tmp_ptr = ptr;
3610
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003611 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003612 {
3613 tmp_ptr += compl_length;
3614 // Skip if already inside a word.
3615 if (vim_iswordp(tmp_ptr))
3616 return NULL;
3617 // Find start of next word.
3618 tmp_ptr = find_word_start(tmp_ptr);
3619 }
3620 // Find end of this word.
3621 tmp_ptr = find_word_end(tmp_ptr);
3622 len = (int)(tmp_ptr - ptr);
3623
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003624 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003625 {
3626 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3627 {
3628 // Try next line, if any. the new word will be
3629 // "join" as if the normal command "J" was used.
3630 // IOSIZE is always greater than
3631 // compl_length, so the next STRNCPY always
3632 // works -- Acevedo
3633 STRNCPY(IObuff, ptr, len);
3634 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3635 tmp_ptr = ptr = skipwhite(ptr);
3636 // Find start of next word.
3637 tmp_ptr = find_word_start(tmp_ptr);
3638 // Find end of next word.
3639 tmp_ptr = find_word_end(tmp_ptr);
3640 if (tmp_ptr > ptr)
3641 {
3642 if (*ptr != ')' && IObuff[len - 1] != TAB)
3643 {
3644 if (IObuff[len - 1] != ' ')
3645 IObuff[len++] = ' ';
3646 // IObuf =~ "\k.* ", thus len >= 2
3647 if (p_js
3648 && (IObuff[len - 2] == '.'
3649 || (vim_strchr(p_cpo, CPO_JOINSP)
3650 == NULL
3651 && (IObuff[len - 2] == '?'
3652 || IObuff[len - 2] == '!'))))
3653 IObuff[len++] = ' ';
3654 }
3655 // copy as much as possible of the new word
3656 if (tmp_ptr - ptr >= IOSIZE - len)
3657 tmp_ptr = ptr + IOSIZE - len - 1;
3658 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3659 len += (int)(tmp_ptr - ptr);
3660 *cont_s_ipos = TRUE;
3661 }
3662 IObuff[len] = NUL;
3663 ptr = IObuff;
3664 }
3665 if (len == compl_length)
3666 return NULL;
3667 }
3668 }
3669
3670 *match_len = len;
3671 return ptr;
3672}
3673
3674/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003675 * Get the next set of words matching "compl_pattern" for default completion(s)
3676 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003677 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3678 * position "st->start_pos" in the "compl_direction" direction. If
3679 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3680 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003681 * Returns OK if a new next match is found, otherwise returns FAIL.
3682 */
3683 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003684get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003685{
3686 int found_new_match = FAIL;
3687 int save_p_scs;
3688 int save_p_ws;
3689 int looped_around = FALSE;
3690 char_u *ptr;
3691 int len;
3692
3693 // If 'infercase' is set, don't use 'smartcase' here
3694 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003695 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003696 p_scs = FALSE;
3697
3698 // Buffers other than curbuf are scanned from the beginning or the
3699 // end but never from the middle, thus setting nowrapscan in this
3700 // buffer is a good idea, on the other hand, we always set
3701 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3702 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003703 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003704 p_ws = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003705 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003706 p_ws = TRUE;
3707 looped_around = FALSE;
3708 for (;;)
3709 {
3710 int cont_s_ipos = FALSE;
3711
3712 ++msg_silent; // Don't want messages for wrapscan.
3713
3714 // ctrl_x_mode_line_or_eval() || word-wise search that
3715 // has added a word that was at the beginning of the line
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003716 if (ctrl_x_mode_line_or_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003717 found_new_match = search_for_exact_line(st->ins_buf,
3718 st->cur_match_pos, compl_direction, compl_pattern);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003719 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003720 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003721 NULL, compl_direction, compl_pattern, compl_patternlen,
3722 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003723 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003724 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003725 {
3726 // set "compl_started" even on fail
3727 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003728 st->first_match_pos = *st->cur_match_pos;
3729 st->last_match_pos = *st->cur_match_pos;
3730 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003731 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003732 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3733 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003734 {
3735 found_new_match = FAIL;
3736 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003737 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003738 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3739 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3740 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003741 {
3742 if (looped_around)
3743 found_new_match = FAIL;
3744 else
3745 looped_around = TRUE;
3746 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003747 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003748 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3749 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3750 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003751 {
3752 if (looped_around)
3753 found_new_match = FAIL;
3754 else
3755 looped_around = TRUE;
3756 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003757 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003758 if (found_new_match == FAIL)
3759 break;
3760
3761 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003762 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003763 && start_pos->lnum == st->cur_match_pos->lnum
3764 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003765 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003766
zeertzjq440d4cb2023-03-02 17:51:32 +00003767 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3768 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003769 if (ptr == NULL)
3770 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003771
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003772 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003773 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003774 0, cont_s_ipos) != NOTDONE)
3775 {
3776 found_new_match = OK;
3777 break;
3778 }
3779 }
3780 p_scs = save_p_scs;
3781 p_ws = save_p_ws;
3782
3783 return found_new_match;
3784}
3785
3786/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003787 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003788 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003789 */
3790 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003791get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003792{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003793 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003794
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003795 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003796 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003797 case -1:
3798 break;
3799#ifdef FEAT_FIND_ID
3800 case CTRL_X_PATH_PATTERNS:
3801 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003802 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003803 break;
3804#endif
3805
3806 case CTRL_X_DICTIONARY:
3807 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003808 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3809 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003810 break;
3811
3812 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003813 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003814 break;
3815
3816 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003817 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003818 break;
3819
3820 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003821 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003822 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003823 break;
3824
3825#ifdef FEAT_COMPL_FUNC
3826 case CTRL_X_FUNCTION:
3827 case CTRL_X_OMNI:
3828 expand_by_function(type, compl_pattern);
3829 break;
3830#endif
3831
3832 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003833 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003834 break;
3835
3836 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003837 found_new_match = get_next_default_completion(st, ini);
3838 if (found_new_match == FAIL && st->ins_buf == curbuf)
3839 st->found_all = TRUE;
3840 }
3841
3842 // check if compl_curr_match has changed, (e.g. other type of
3843 // expansion added something)
3844 if (type != 0 && compl_curr_match != compl_old_match)
3845 found_new_match = OK;
3846
3847 return found_new_match;
3848}
3849
3850/*
3851 * Get the next expansion(s), using "compl_pattern".
3852 * The search starts at position "ini" in curbuf and in the direction
3853 * compl_direction.
3854 * When "compl_started" is FALSE start at that position, otherwise continue
3855 * where we stopped searching before.
3856 * This may return before finding all the matches.
3857 * Return the total number of matches or -1 if still unknown -- Acevedo
3858 */
3859 static int
3860ins_compl_get_exp(pos_T *ini)
3861{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003862 static ins_compl_next_state_T st;
3863 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003864 int i;
3865 int found_new_match;
3866 int type = ctrl_x_mode;
3867
3868 if (!compl_started)
3869 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003870 buf_T *buf;
3871
3872 FOR_ALL_BUFFERS(buf)
3873 buf->b_scanned = 0;
3874 if (!st_cleared)
3875 {
3876 CLEAR_FIELD(st);
3877 st_cleared = TRUE;
3878 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003879 st.found_all = FALSE;
3880 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003881 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02003882 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003883 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
3884 ? (char_u *)"." : curbuf->b_p_cpt);
3885 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003886 st.last_match_pos = st.first_match_pos = *ini;
3887 }
3888 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
3889 st.ins_buf = curbuf; // In case the buffer was wiped out.
3890
3891 compl_old_match = compl_curr_match; // remember the last current match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003892 st.cur_match_pos = (compl_dir_forward())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003893 ? &st.last_match_pos : &st.first_match_pos;
3894
3895 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
3896 for (;;)
3897 {
3898 found_new_match = FAIL;
3899 st.set_match_pos = FALSE;
3900
3901 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
3902 // or if found_all says this entry is done. For ^X^L only use the
3903 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003904 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003905 && (!compl_started || st.found_all))
3906 {
3907 int status = process_next_cpt_value(&st, &type, ini);
3908
3909 if (status == INS_COMPL_CPT_END)
3910 break;
3911 if (status == INS_COMPL_CPT_CONT)
3912 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003913 }
3914
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003915 // If complete() was called then compl_pattern has been reset. The
3916 // following won't work then, bail out.
3917 if (compl_pattern == NULL)
3918 break;
3919
3920 // get the next set of completion matches
3921 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003922
3923 // break the loop for specialized modes (use 'complete' just for the
3924 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3925 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003926 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
3927 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003928 {
3929 if (got_int)
3930 break;
3931 // Fill the popup menu as soon as possible.
3932 if (type != -1)
3933 ins_compl_check_keys(0, FALSE);
3934
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003935 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003936 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3937 break;
3938 compl_started = TRUE;
3939 }
3940 else
3941 {
3942 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02003943 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003944 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003945
3946 compl_started = FALSE;
3947 }
3948 }
3949 compl_started = TRUE;
3950
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003951 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003952 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003953 found_new_match = FAIL;
3954
3955 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003956 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003957 && !ctrl_x_mode_line_or_eval()))
3958 i = ins_compl_make_cyclic();
3959
3960 if (compl_old_match != NULL)
3961 {
3962 // If several matches were added (FORWARD) or the search failed and has
3963 // just been made cyclic then we have to move compl_curr_match to the
3964 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003965 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003966 : compl_old_match->cp_prev;
3967 if (compl_curr_match == NULL)
3968 compl_curr_match = compl_old_match;
3969 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01003970 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003971
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003972 return i;
3973}
3974
3975/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003976 * Update "compl_shown_match" to the actually shown match, it may differ when
3977 * "compl_leader" is used to omit some of the matches.
3978 */
3979 static void
3980ins_compl_update_shown_match(void)
3981{
3982 while (!ins_compl_equal(compl_shown_match,
3983 compl_leader, (int)STRLEN(compl_leader))
3984 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003985 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003986 compl_shown_match = compl_shown_match->cp_next;
3987
3988 // If we didn't find it searching forward, and compl_shows_dir is
3989 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003990 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003991 && !ins_compl_equal(compl_shown_match,
3992 compl_leader, (int)STRLEN(compl_leader))
3993 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003994 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003995 {
3996 while (!ins_compl_equal(compl_shown_match,
3997 compl_leader, (int)STRLEN(compl_leader))
3998 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003999 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004000 compl_shown_match = compl_shown_match->cp_prev;
4001 }
4002}
4003
4004/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004005 * Delete the old text being completed.
4006 */
4007 void
4008ins_compl_delete(void)
4009{
4010 int col;
4011
4012 // In insert mode: Delete the typed part.
4013 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004014 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004015 if ((int)curwin->w_cursor.col > col)
4016 {
4017 if (stop_arrow() == FAIL)
4018 return;
4019 backspace_until_column(col);
4020 }
4021
4022 // TODO: is this sufficient for redrawing? Redrawing everything causes
4023 // flicker, thus we can't do that.
4024 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004025#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004026 // clear v:completed_item
4027 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004028#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004029}
4030
4031/*
4032 * Insert the new text being completed.
4033 * "in_compl_func" is TRUE when called from complete_check().
4034 */
4035 void
4036ins_compl_insert(int in_compl_func)
4037{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004038 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004039
4040 // Make sure we don't go over the end of the string, this can happen with
4041 // illegal bytes.
4042 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4043 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004044 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004045 compl_used_match = FALSE;
4046 else
4047 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004048#ifdef FEAT_EVAL
4049 {
4050 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4051
4052 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4053 }
4054#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004055 if (!in_compl_func)
4056 compl_curr_match = compl_shown_match;
4057}
4058
4059/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004060 * show the file name for the completion match (if any). Truncate the file
4061 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004062 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004063 static void
4064ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004065{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004066 char *lead = _("match in file");
4067 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4068 char_u *s;
4069 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004070
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004071 if (space <= 0)
4072 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004073
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004074 // We need the tail that fits. With double-byte encoding going
4075 // back from the end is very slow, thus go from the start and keep
4076 // the text that fits in "space" between "s" and "e".
4077 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004078 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004079 space -= ptr2cells(e);
4080 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004081 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004082 space += ptr2cells(s);
4083 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004084 }
4085 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004086 msg_hist_off = TRUE;
4087 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4088 s > compl_shown_match->cp_fname ? "<" : "", s);
4089 msg((char *)IObuff);
4090 msg_hist_off = FALSE;
4091 redraw_cmdline = FALSE; // don't overwrite!
4092}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004093
glepnirdca57fb2024-06-04 22:01:21 +02004094/*
zeertzjq551d8c32024-06-05 19:53:32 +02004095 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004096 */
glepnira218cc62024-06-03 19:32:39 +02004097 static compl_T *
4098find_comp_when_fuzzy(void)
4099{
4100 int score;
4101 char_u* str;
4102 int target_idx = -1;
4103 int is_forward = compl_shows_dir_forward();
4104 int is_backward = compl_shows_dir_backward();
4105 compl_T *comp = NULL;
4106
glepnir43eef882024-06-19 20:20:48 +02004107 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004108 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004109 return compl_first_match != compl_shown_match ? compl_first_match :
4110 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004111
4112 if (is_forward)
4113 target_idx = compl_selected_item + 1;
4114 else if (is_backward)
4115 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004116 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004117
4118 score = compl_match_array[target_idx].pum_score;
4119 str = compl_match_array[target_idx].pum_text;
4120
4121 comp = compl_first_match;
4122 do {
4123 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4124 return comp;
4125 comp = comp->cp_next;
4126 } while (comp != NULL && !is_first_match(comp));
4127
4128 return NULL;
4129}
4130
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004131/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004132 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004133 * times. The number of matches found is returned in 'num_matches'.
4134 *
4135 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4136 * get more completions. If it is FALSE, then do nothing when there are no more
4137 * completions in the given direction.
4138 *
4139 * If "advance" is TRUE, then completion will move to the first match.
4140 * Otherwise, the original text will be shown.
4141 *
4142 * Returns OK on success and -1 if the number of matches are unknown.
4143 */
4144 static int
4145find_next_completion_match(
4146 int allow_get_expansion,
4147 int todo, // repeat completion this many times
4148 int advance,
4149 int *num_matches)
4150{
4151 int found_end = FALSE;
4152 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004153 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004154 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4155 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004156
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004157 while (--todo >= 0)
4158 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004159 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004160 {
glepniraced8c22024-06-15 15:13:05 +02004161 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4162 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004163 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004164 && (is_first_match(compl_shown_match->cp_next)
4165 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004166 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004167 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004168 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004169 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004170 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004171 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4172 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004173 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004174 }
4175 else
4176 {
4177 if (!allow_get_expansion)
4178 {
4179 if (advance)
4180 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004181 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004182 compl_pending -= todo + 1;
4183 else
4184 compl_pending += todo + 1;
4185 }
4186 return -1;
4187 }
4188
4189 if (!compl_no_select && advance)
4190 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004191 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004192 --compl_pending;
4193 else
4194 ++compl_pending;
4195 }
4196
4197 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004198 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004199
4200 // handle any pending completions
4201 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004202 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004203 {
4204 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4205 {
4206 compl_shown_match = compl_shown_match->cp_next;
4207 --compl_pending;
4208 }
4209 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4210 {
4211 compl_shown_match = compl_shown_match->cp_prev;
4212 ++compl_pending;
4213 }
4214 else
4215 break;
4216 }
4217 found_end = FALSE;
4218 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004219 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004220 && compl_leader != NULL
4221 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004222 compl_leader, (int)STRLEN(compl_leader))
4223 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004224 ++todo;
4225 else
4226 // Remember a matching item.
4227 found_compl = compl_shown_match;
4228
4229 // Stop at the end of the list when we found a usable match.
4230 if (found_end)
4231 {
4232 if (found_compl != NULL)
4233 {
4234 compl_shown_match = found_compl;
4235 break;
4236 }
4237 todo = 1; // use first usable match after wrapping around
4238 }
4239 }
4240
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004241 return OK;
4242}
4243
4244/*
4245 * Fill in the next completion in the current direction.
4246 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4247 * get more completions. If it is FALSE, then we just do nothing when there
4248 * are no more completions in a given direction. The latter case is used when
4249 * we are still in the middle of finding completions, to allow browsing
4250 * through the ones found so far.
4251 * Return the total number of matches, or -1 if still unknown -- webb.
4252 *
4253 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4254 * compl_shown_match here.
4255 *
4256 * Note that this function may be called recursively once only. First with
4257 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4258 * calls this function with "allow_get_expansion" FALSE.
4259 */
4260 static int
4261ins_compl_next(
4262 int allow_get_expansion,
4263 int count, // repeat completion this many times; should
4264 // be at least 1
4265 int insert_match, // Insert the newly selected match
4266 int in_compl_func) // called from complete_check()
4267{
4268 int num_matches = -1;
4269 int todo = count;
4270 int advance;
4271 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004272 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004273 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004274 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4275 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004276
4277 // When user complete function return -1 for findstart which is next
4278 // time of 'always', compl_shown_match become NULL.
4279 if (compl_shown_match == NULL)
4280 return -1;
4281
glepnira218cc62024-06-03 19:32:39 +02004282 if (compl_leader != NULL
4283 && !match_at_original_text(compl_shown_match)
4284 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004285 // Update "compl_shown_match" to the actually shown match
4286 ins_compl_update_shown_match();
4287
4288 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004289 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004290 // Delete old text to be replaced
4291 ins_compl_delete();
4292
4293 // When finding the longest common text we stick at the original text,
4294 // don't let CTRL-N or CTRL-P move to the first match.
4295 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4296
4297 // When restarting the search don't insert the first match either.
4298 if (compl_restarting)
4299 {
4300 advance = FALSE;
4301 compl_restarting = FALSE;
4302 }
4303
4304 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4305 // around.
4306 if (find_next_completion_match(allow_get_expansion, todo, advance,
4307 &num_matches) == -1)
4308 return -1;
4309
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004310 if (curbuf != orig_curbuf)
4311 {
4312 // In case some completion function switched buffer, don't want to
4313 // insert the completion elsewhere.
4314 return -1;
4315 }
4316
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004317 // Insert the text of the new completion, or the compl_leader.
4318 if (compl_no_insert && !started)
4319 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004320 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004321 compl_used_match = FALSE;
4322 }
4323 else if (insert_match)
4324 {
4325 if (!compl_get_longest || compl_used_match)
4326 ins_compl_insert(in_compl_func);
4327 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004328 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004329 }
4330 else
4331 compl_used_match = FALSE;
4332
4333 if (!allow_get_expansion)
4334 {
4335 // may undisplay the popup menu first
4336 ins_compl_upd_pum();
4337
4338 if (pum_enough_matches())
4339 // Will display the popup menu, don't redraw yet to avoid flicker.
4340 pum_call_update_screen();
4341 else
4342 // Not showing the popup menu yet, redraw to show the user what was
4343 // inserted.
4344 update_screen(0);
4345
4346 // display the updated popup menu
4347 ins_compl_show_pum();
4348#ifdef FEAT_GUI
4349 if (gui.in_use)
4350 {
4351 // Show the cursor after the match, not after the redrawn text.
4352 setcursor();
4353 out_flush_cursor(FALSE, FALSE);
4354 }
4355#endif
4356
4357 // Delete old text to be replaced, since we're still searching and
4358 // don't want to match ourselves!
4359 ins_compl_delete();
4360 }
4361
4362 // Enter will select a match when the match wasn't inserted and the popup
4363 // menu is visible.
4364 if (compl_no_insert && !started)
4365 compl_enter_selects = TRUE;
4366 else
4367 compl_enter_selects = !insert_match && compl_match_array != NULL;
4368
4369 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004370 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004371 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004372
4373 return num_matches;
4374}
4375
4376/*
4377 * Call this while finding completions, to check whether the user has hit a key
4378 * that should change the currently displayed completion, or exit completion
4379 * mode. Also, when compl_pending is not zero, show a completion as soon as
4380 * possible. -- webb
4381 * "frequency" specifies out of how many calls we actually check.
4382 * "in_compl_func" is TRUE when called from complete_check(), don't set
4383 * compl_curr_match.
4384 */
4385 void
4386ins_compl_check_keys(int frequency, int in_compl_func)
4387{
4388 static int count = 0;
4389 int c;
4390
4391 // Don't check when reading keys from a script, :normal or feedkeys().
4392 // That would break the test scripts. But do check for keys when called
4393 // from complete_check().
4394 if (!in_compl_func && (using_script() || ex_normal_busy))
4395 return;
4396
4397 // Only do this at regular intervals
4398 if (++count < frequency)
4399 return;
4400 count = 0;
4401
4402 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4403 // can't do its work correctly.
4404 c = vpeekc_any();
4405 if (c != NUL)
4406 {
4407 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4408 {
4409 c = safe_vgetc(); // Eat the character
4410 compl_shows_dir = ins_compl_key2dir(c);
4411 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4412 c != K_UP && c != K_DOWN, in_compl_func);
4413 }
4414 else
4415 {
4416 // Need to get the character to have KeyTyped set. We'll put it
4417 // back with vungetc() below. But skip K_IGNORE.
4418 c = safe_vgetc();
4419 if (c != K_IGNORE)
4420 {
4421 // Don't interrupt completion when the character wasn't typed,
4422 // e.g., when doing @q to replay keys.
4423 if (c != Ctrl_R && KeyTyped)
4424 compl_interrupted = TRUE;
4425
4426 vungetc(c);
4427 }
4428 }
4429 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004430 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004431 {
4432 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4433
4434 compl_pending = 0;
4435 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4436 }
4437}
4438
4439/*
4440 * Decide the direction of Insert mode complete from the key typed.
4441 * Returns BACKWARD or FORWARD.
4442 */
4443 static int
4444ins_compl_key2dir(int c)
4445{
4446 if (c == Ctrl_P || c == Ctrl_L
4447 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4448 return BACKWARD;
4449 return FORWARD;
4450}
4451
4452/*
4453 * Return TRUE for keys that are used for completion only when the popup menu
4454 * is visible.
4455 */
4456 static int
4457ins_compl_pum_key(int c)
4458{
4459 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4460 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4461 || c == K_UP || c == K_DOWN);
4462}
4463
4464/*
4465 * Decide the number of completions to move forward.
4466 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4467 */
4468 static int
4469ins_compl_key2count(int c)
4470{
4471 int h;
4472
4473 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4474 {
4475 h = pum_get_height();
4476 if (h > 3)
4477 h -= 2; // keep some context
4478 return h;
4479 }
4480 return 1;
4481}
4482
4483/*
4484 * Return TRUE if completion with "c" should insert the match, FALSE if only
4485 * to change the currently selected completion.
4486 */
4487 static int
4488ins_compl_use_match(int c)
4489{
4490 switch (c)
4491 {
4492 case K_UP:
4493 case K_DOWN:
4494 case K_PAGEDOWN:
4495 case K_KPAGEDOWN:
4496 case K_S_DOWN:
4497 case K_PAGEUP:
4498 case K_KPAGEUP:
4499 case K_S_UP:
4500 return FALSE;
4501 }
4502 return TRUE;
4503}
4504
4505/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004506 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4507 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004508 * Sets the global variables: compl_col, compl_length, compl_pattern and
4509 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004510 * Uses the global variables: compl_cont_status and ctrl_x_mode
4511 */
4512 static int
4513get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4514{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004515 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004516 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004517 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004518 {
4519 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4520 ;
4521 compl_col += ++startcol;
4522 compl_length = curs_col - startcol;
4523 }
4524 if (p_ic)
4525 compl_pattern = str_foldcase(line + compl_col,
4526 compl_length, NULL, 0);
4527 else
4528 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4529 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004530 {
4531 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004532 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004533 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004534 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004535 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004536 {
4537 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004538 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004539
4540 // we need up to 2 extra chars for the prefix
4541 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004542 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004543 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004544 {
4545 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004546 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004547 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004548 if (!vim_iswordp(line + compl_col)
4549 || (compl_col > 0
4550 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004551 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004552 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004553 prefixlen = 0;
4554 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004555 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004556 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004557 line + compl_col, compl_length);
4558 }
4559 else if (--startcol < 0
4560 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4561 {
4562 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004563 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004564 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004565 {
4566 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004567 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004568 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004569 compl_col += curs_col;
4570 compl_length = 0;
4571 }
4572 else
4573 {
4574 // Search the point of change class of multibyte character
4575 // or not a word single byte character backward.
4576 if (has_mbyte)
4577 {
4578 int base_class;
4579 int head_off;
4580
4581 startcol -= (*mb_head_off)(line, line + startcol);
4582 base_class = mb_get_class(line + startcol);
4583 while (--startcol >= 0)
4584 {
4585 head_off = (*mb_head_off)(line, line + startcol);
4586 if (base_class != mb_get_class(line + startcol
4587 - head_off))
4588 break;
4589 startcol -= head_off;
4590 }
4591 }
4592 else
4593 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4594 ;
4595 compl_col += ++startcol;
4596 compl_length = (int)curs_col - startcol;
4597 if (compl_length == 1)
4598 {
4599 // Only match word with at least two chars -- webb
4600 // there's no need to call quote_meta,
4601 // alloc(7) is enough -- Acevedo
4602 compl_pattern = alloc(7);
4603 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004604 {
4605 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004606 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004607 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004608 STRCPY((char *)compl_pattern, "\\<");
4609 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4610 STRCAT((char *)compl_pattern, "\\k");
4611 }
4612 else
4613 {
4614 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4615 compl_length) + 2);
4616 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004617 {
4618 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004619 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004620 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004621 STRCPY((char *)compl_pattern, "\\<");
4622 (void)quote_meta(compl_pattern + 2, line + compl_col,
4623 compl_length);
4624 }
4625 }
4626
John Marriott8c85a2a2024-05-20 19:18:26 +02004627 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004628 return OK;
4629}
4630
4631/*
4632 * Get the pattern, column and length for whole line completion or for the
4633 * complete() function.
4634 * Sets the global variables: compl_col, compl_length and compl_pattern.
4635 */
4636 static int
4637get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4638{
4639 compl_col = (colnr_T)getwhitecols(line);
4640 compl_length = (int)curs_col - (int)compl_col;
4641 if (compl_length < 0) // cursor in indent: empty pattern
4642 compl_length = 0;
4643 if (p_ic)
4644 compl_pattern = str_foldcase(line + compl_col, compl_length,
4645 NULL, 0);
4646 else
4647 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4648 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004649 {
4650 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004651 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004652 }
4653
4654 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004655
4656 return OK;
4657}
4658
4659/*
4660 * Get the pattern, column and length for filename completion.
4661 * Sets the global variables: compl_col, compl_length and compl_pattern.
4662 */
4663 static int
4664get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4665{
4666 // Go back to just before the first filename character.
4667 if (startcol > 0)
4668 {
4669 char_u *p = line + startcol;
4670
4671 MB_PTR_BACK(line, p);
4672 while (p > line && vim_isfilec(PTR2CHAR(p)))
4673 MB_PTR_BACK(line, p);
4674 if (p == line && vim_isfilec(PTR2CHAR(p)))
4675 startcol = 0;
4676 else
4677 startcol = (int)(p - line) + 1;
4678 }
4679
4680 compl_col += startcol;
4681 compl_length = (int)curs_col - startcol;
4682 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4683 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004684 {
4685 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004686 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004687 }
4688
4689 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004690
4691 return OK;
4692}
4693
4694/*
4695 * Get the pattern, column and length for command-line completion.
4696 * Sets the global variables: compl_col, compl_length and compl_pattern.
4697 */
4698 static int
4699get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4700{
4701 compl_pattern = vim_strnsave(line, curs_col);
4702 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004703 {
4704 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004705 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004706 }
4707 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004708 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004709 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004710 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4711 || compl_xp.xp_context == EXPAND_NOTHING)
4712 // No completion possible, use an empty pattern to get a
4713 // "pattern not found" message.
4714 compl_col = curs_col;
4715 else
4716 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4717 compl_length = curs_col - compl_col;
4718
4719 return OK;
4720}
4721
4722/*
4723 * Get the pattern, column and length for user defined completion ('omnifunc',
4724 * 'completefunc' and 'thesaurusfunc')
4725 * Sets the global variables: compl_col, compl_length and compl_pattern.
4726 * Uses the global variable: spell_bad_len
4727 */
4728 static int
4729get_userdefined_compl_info(colnr_T curs_col UNUSED)
4730{
4731 int ret = FAIL;
4732
4733#ifdef FEAT_COMPL_FUNC
4734 // Call user defined function 'completefunc' with "a:findstart"
4735 // set to 1 to obtain the length of text to use for completion.
4736 char_u *line;
4737 typval_T args[3];
4738 int col;
4739 char_u *funcname;
4740 pos_T pos;
4741 int save_State = State;
4742 callback_T *cb;
4743
4744 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4745 // length as a string
4746 funcname = get_complete_funcname(ctrl_x_mode);
4747 if (*funcname == NUL)
4748 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004749 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004750 ? "completefunc" : "omnifunc");
4751 return FAIL;
4752 }
4753
4754 args[0].v_type = VAR_NUMBER;
4755 args[0].vval.v_number = 1;
4756 args[1].v_type = VAR_STRING;
4757 args[1].vval.v_string = (char_u *)"";
4758 args[2].v_type = VAR_UNKNOWN;
4759 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004760 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004761 cb = get_insert_callback(ctrl_x_mode);
4762 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004763 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004764
4765 State = save_State;
4766 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004767 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004768 validate_cursor();
4769 if (!EQUAL_POS(curwin->w_cursor, pos))
4770 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004771 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004772 return FAIL;
4773 }
4774
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004775 // Return value -2 means the user complete function wants to cancel the
4776 // complete without an error, do the same if the function did not execute
4777 // successfully.
4778 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004779 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004780 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004781 if (col == -3)
4782 {
4783 ctrl_x_mode = CTRL_X_NORMAL;
4784 edit_submode = NULL;
4785 if (!shortmess(SHM_COMPLETIONMENU))
4786 msg_clr_cmdline();
4787 return FAIL;
4788 }
4789
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004790 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004791 // completion.
4792 compl_opt_refresh_always = FALSE;
4793 compl_opt_suppress_empty = FALSE;
4794
4795 if (col < 0)
4796 col = curs_col;
4797 compl_col = col;
4798 if (compl_col > curs_col)
4799 compl_col = curs_col;
4800
4801 // Setup variables for completion. Need to obtain "line" again,
4802 // it may have become invalid.
4803 line = ml_get(curwin->w_cursor.lnum);
4804 compl_length = curs_col - compl_col;
4805 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4806 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004807 {
4808 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004809 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004810 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004811
John Marriott8c85a2a2024-05-20 19:18:26 +02004812 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004813 ret = OK;
4814#endif
4815
4816 return ret;
4817}
4818
4819/*
4820 * Get the pattern, column and length for spell completion.
4821 * Sets the global variables: compl_col, compl_length and compl_pattern.
4822 * Uses the global variable: spell_bad_len
4823 */
4824 static int
4825get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4826{
4827 int ret = FAIL;
4828#ifdef FEAT_SPELL
4829 char_u *line;
4830
4831 if (spell_bad_len > 0)
4832 compl_col = curs_col - spell_bad_len;
4833 else
4834 compl_col = spell_word_start(startcol);
4835 if (compl_col >= (colnr_T)startcol)
4836 {
4837 compl_length = 0;
4838 compl_col = curs_col;
4839 }
4840 else
4841 {
4842 spell_expand_check_cap(compl_col);
4843 compl_length = (int)curs_col - compl_col;
4844 }
4845 // Need to obtain "line" again, it may have become invalid.
4846 line = ml_get(curwin->w_cursor.lnum);
4847 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4848 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004849 {
4850 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004851 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004852 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004853
John Marriott8c85a2a2024-05-20 19:18:26 +02004854 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004855 ret = OK;
4856#endif
4857
4858 return ret;
4859}
4860
4861/*
4862 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004863 * "startcol" - start column number of the completion pattern/text
4864 * "cur_col" - current cursor column
4865 * On return, "line_invalid" is set to TRUE, if the current line may have
4866 * become invalid and needs to be fetched again.
4867 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004868 */
4869 static int
4870compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
4871{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004872 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004873 || (ctrl_x_mode & CTRL_X_WANT_IDENT
4874 && !thesaurus_func_complete(ctrl_x_mode)))
4875 {
4876 return get_normal_compl_info(line, startcol, curs_col);
4877 }
4878 else if (ctrl_x_mode_line_or_eval())
4879 {
4880 return get_wholeline_compl_info(line, curs_col);
4881 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004882 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004883 {
4884 return get_filename_compl_info(line, startcol, curs_col);
4885 }
4886 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4887 {
4888 return get_cmdline_compl_info(line, curs_col);
4889 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004890 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004891 || thesaurus_func_complete(ctrl_x_mode))
4892 {
4893 if (get_userdefined_compl_info(curs_col) == FAIL)
4894 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004895 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004896 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004897 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004898 {
4899 if (get_spell_compl_info(startcol, curs_col) == FAIL)
4900 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004901 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004902 }
4903 else
4904 {
4905 internal_error("ins_complete()");
4906 return FAIL;
4907 }
4908
4909 return OK;
4910}
4911
4912/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004913 * Continue an interrupted completion mode search in "line".
4914 *
4915 * If this same ctrl_x_mode has been interrupted use the text from
4916 * "compl_startpos" to the cursor as a pattern to add a new word instead of
4917 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
4918 * the same line as the cursor then fix it (the line has been split because it
4919 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
4920 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004921 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004922 static void
4923ins_compl_continue_search(char_u *line)
4924{
4925 // it is a continued search
4926 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004927 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
4928 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004929 {
4930 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4931 {
4932 // line (probably) wrapped, set compl_startpos to the
4933 // first non_blank in the line, if it is not a wordchar
4934 // include it to get a better pattern, but then we don't
4935 // want the "\\<" prefix, check it below
4936 compl_col = (colnr_T)getwhitecols(line);
4937 compl_startpos.col = compl_col;
4938 compl_startpos.lnum = curwin->w_cursor.lnum;
4939 compl_cont_status &= ~CONT_SOL; // clear SOL if present
4940 }
4941 else
4942 {
4943 // S_IPOS was set when we inserted a word that was at the
4944 // beginning of the line, which means that we'll go to SOL
4945 // mode but first we need to redefine compl_startpos
4946 if (compl_cont_status & CONT_S_IPOS)
4947 {
4948 compl_cont_status |= CONT_SOL;
4949 compl_startpos.col = (colnr_T)(skipwhite(
4950 line + compl_length
4951 + compl_startpos.col) - line);
4952 }
4953 compl_col = compl_startpos.col;
4954 }
4955 compl_length = curwin->w_cursor.col - (int)compl_col;
4956 // IObuff is used to add a "word from the next line" would we
4957 // have enough space? just being paranoid
4958#define MIN_SPACE 75
4959 if (compl_length > (IOSIZE - MIN_SPACE))
4960 {
4961 compl_cont_status &= ~CONT_SOL;
4962 compl_length = (IOSIZE - MIN_SPACE);
4963 compl_col = curwin->w_cursor.col - compl_length;
4964 }
4965 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4966 if (compl_length < 1)
4967 compl_cont_status &= CONT_LOCAL;
4968 }
4969 else if (ctrl_x_mode_line_or_eval())
4970 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4971 else
4972 compl_cont_status = 0;
4973}
4974
4975/*
4976 * start insert mode completion
4977 */
4978 static int
4979ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004980{
4981 char_u *line;
4982 int startcol = 0; // column where searched text starts
4983 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004984 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004985 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004986 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004988 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004989
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004990 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004991 did_si = FALSE;
4992 can_si = FALSE;
4993 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004994 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004995 return FAIL;
4996
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004997 line = ml_get(curwin->w_cursor.lnum);
4998 curs_col = curwin->w_cursor.col;
4999 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005000
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005001 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5002 && compl_cont_mode == ctrl_x_mode)
5003 // this same ctrl-x_mode was interrupted previously. Continue the
5004 // completion.
5005 ins_compl_continue_search(line);
5006 else
5007 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005008
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005009 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005010 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005011 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005012 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005013 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5014 compl_cont_status = 0;
5015 compl_cont_status |= CONT_N_ADDS;
5016 compl_startpos = curwin->w_cursor;
5017 startcol = (int)curs_col;
5018 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005019 }
5020
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005021 // Work out completion pattern and original text -- webb
5022 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5023 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005024 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5025 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005026 // restore did_ai, so that adding comment leader works
5027 did_ai = save_did_ai;
5028 return FAIL;
5029 }
5030 // If "line" was changed while getting completion info get it again.
5031 if (line_invalid)
5032 line = ml_get(curwin->w_cursor.lnum);
5033
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005034 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005035 {
5036 edit_submode_pre = (char_u *)_(" Adding");
5037 if (ctrl_x_mode_line_or_eval())
5038 {
5039 // Insert a new line, keep indentation but ignore 'comments'.
5040 char_u *old = curbuf->b_p_com;
5041
5042 curbuf->b_p_com = (char_u *)"";
5043 compl_startpos.lnum = curwin->w_cursor.lnum;
5044 compl_startpos.col = compl_col;
5045 ins_eol('\r');
5046 curbuf->b_p_com = old;
5047 compl_length = 0;
5048 compl_col = curwin->w_cursor.col;
5049 }
5050 }
5051 else
5052 {
5053 edit_submode_pre = NULL;
5054 compl_startpos.col = compl_col;
5055 }
5056
5057 if (compl_cont_status & CONT_LOCAL)
5058 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5059 else
5060 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5061
5062 // If any of the original typed text has been changed we need to fix
5063 // the redo buffer.
5064 ins_compl_fixRedoBufForLeader(NULL);
5065
5066 // Always add completion for the original text.
5067 vim_free(compl_orig_text);
5068 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5069 if (p_ic)
5070 flags |= CP_ICASE;
5071 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
5072 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
5073 {
5074 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005075 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005076 VIM_CLEAR(compl_orig_text);
5077 return FAIL;
5078 }
5079
5080 // showmode might reset the internal line pointers, so it must
5081 // be called before line = ml_get(), or when this address is no
5082 // longer needed. -- Acevedo.
5083 edit_submode_extra = (char_u *)_("-- Searching...");
5084 edit_submode_highl = HLF_COUNT;
5085 showmode();
5086 edit_submode_extra = NULL;
5087 out_flush();
5088
5089 return OK;
5090}
5091
5092/*
5093 * display the completion status message
5094 */
5095 static void
5096ins_compl_show_statusmsg(void)
5097{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005098 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005099 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005100 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005101 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005102 ? (char_u *)_("Hit end of paragraph")
5103 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005104 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005105 }
5106
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005107 if (edit_submode_extra == NULL)
5108 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005109 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005110 {
5111 edit_submode_extra = (char_u *)_("Back at original");
5112 edit_submode_highl = HLF_W;
5113 }
5114 else if (compl_cont_status & CONT_S_IPOS)
5115 {
5116 edit_submode_extra = (char_u *)_("Word from other line");
5117 edit_submode_highl = HLF_COUNT;
5118 }
5119 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5120 {
5121 edit_submode_extra = (char_u *)_("The only match");
5122 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005123 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005124 }
5125 else
5126 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005127#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005128 // Update completion sequence number when needed.
5129 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005130 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005131#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005132 // The match should always have a sequence number now, this is
5133 // just a safety check.
5134 if (compl_curr_match->cp_number != -1)
5135 {
5136 // Space for 10 text chars. + 2x10-digit no.s = 31.
5137 // Translations may need more than twice that.
5138 static char_u match_ref[81];
5139
5140 if (compl_matches > 0)
5141 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005142 _("match %d of %d"),
5143 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005144 else
5145 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005146 _("match %d"),
5147 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005148 edit_submode_extra = match_ref;
5149 edit_submode_highl = HLF_R;
5150 if (dollar_vcol >= 0)
5151 curs_columns(FALSE);
5152 }
5153 }
5154 }
5155
5156 // Show a message about what (completion) mode we're in.
5157 if (!compl_opt_suppress_empty)
5158 {
5159 showmode();
5160 if (!shortmess(SHM_COMPLETIONMENU))
5161 {
5162 if (edit_submode_extra != NULL)
5163 {
5164 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005165 {
5166 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005167 msg_attr((char *)edit_submode_extra,
5168 edit_submode_highl < HLF_COUNT
5169 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005170 msg_hist_off = FALSE;
5171 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005172 }
5173 else
5174 msg_clr_cmdline(); // necessary for "noshowmode"
5175 }
5176 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005177}
5178
5179/*
5180 * Do Insert mode completion.
5181 * Called when character "c" was typed, which has a meaning for completion.
5182 * Returns OK if completion was done, FAIL if something failed (out of mem).
5183 */
5184 int
5185ins_complete(int c, int enable_pum)
5186{
5187 int n;
5188 int save_w_wrow;
5189 int save_w_leftcol;
5190 int insert_match;
5191
5192 compl_direction = ins_compl_key2dir(c);
5193 insert_match = ins_compl_use_match(c);
5194
5195 if (!compl_started)
5196 {
5197 if (ins_compl_start() == FAIL)
5198 return FAIL;
5199 }
5200 else if (insert_match && stop_arrow() == FAIL)
5201 return FAIL;
5202
5203 compl_shown_match = compl_curr_match;
5204 compl_shows_dir = compl_direction;
5205
5206 // Find next match (and following matches).
5207 save_w_wrow = curwin->w_wrow;
5208 save_w_leftcol = curwin->w_leftcol;
5209 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5210
5211 // may undisplay the popup menu
5212 ins_compl_upd_pum();
5213
5214 if (n > 1) // all matches have been found
5215 compl_matches = n;
5216 compl_curr_match = compl_shown_match;
5217 compl_direction = compl_shows_dir;
5218
5219 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5220 // mode.
5221 if (got_int && !global_busy)
5222 {
5223 (void)vgetc();
5224 got_int = FALSE;
5225 }
5226
5227 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005228 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005229 {
5230 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5231 // because we couldn't expand anything at first place, but if we used
5232 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5233 // (such as M in M'exico) if not tried already. -- Acevedo
5234 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005235 || compl_status_adding()
5236 || (ctrl_x_mode_not_default()
5237 && !ctrl_x_mode_path_patterns()
5238 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005239 compl_cont_status &= ~CONT_N_ADDS;
5240 }
5241
5242 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5243 compl_cont_status |= CONT_S_IPOS;
5244 else
5245 compl_cont_status &= ~CONT_S_IPOS;
5246
5247 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005248
5249 // Show the popup menu, unless we got interrupted.
5250 if (enable_pum && !compl_interrupted)
5251 show_pum(save_w_wrow, save_w_leftcol);
5252
5253 compl_was_interrupted = compl_interrupted;
5254 compl_interrupted = FALSE;
5255
5256 return OK;
5257}
5258
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005259/*
5260 * Remove (if needed) and show the popup menu
5261 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005262 static void
5263show_pum(int prev_w_wrow, int prev_w_leftcol)
5264{
5265 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005266 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005267 RedrawingDisabled = 0;
5268
5269 // If the cursor moved or the display scrolled we need to remove the pum
5270 // first.
5271 setcursor();
5272 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5273 ins_compl_del_pum();
5274
5275 ins_compl_show_pum();
5276 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005277
5278 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005279}
5280
5281/*
5282 * Looks in the first "len" chars. of "src" for search-metachars.
5283 * If dest is not NULL the chars. are copied there quoting (with
5284 * a backslash) the metachars, and dest would be NUL terminated.
5285 * Returns the length (needed) of dest
5286 */
5287 static unsigned
5288quote_meta(char_u *dest, char_u *src, int len)
5289{
5290 unsigned m = (unsigned)len + 1; // one extra for the NUL
5291
5292 for ( ; --len >= 0; src++)
5293 {
5294 switch (*src)
5295 {
5296 case '.':
5297 case '*':
5298 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005299 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005300 break;
5301 // FALLTHROUGH
5302 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005303 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005304 break;
5305 // FALLTHROUGH
5306 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005307 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005308 break;
5309 // FALLTHROUGH
5310 case '^': // currently it's not needed.
5311 case '$':
5312 m++;
5313 if (dest != NULL)
5314 *dest++ = '\\';
5315 break;
5316 }
5317 if (dest != NULL)
5318 *dest++ = *src;
5319 // Copy remaining bytes of a multibyte character.
5320 if (has_mbyte)
5321 {
5322 int i, mb_len;
5323
5324 mb_len = (*mb_ptr2len)(src) - 1;
5325 if (mb_len > 0 && len >= mb_len)
5326 for (i = 0; i < mb_len; ++i)
5327 {
5328 --len;
5329 ++src;
5330 if (dest != NULL)
5331 *dest++ = *src;
5332 }
5333 }
5334 }
5335 if (dest != NULL)
5336 *dest = NUL;
5337
5338 return m;
5339}
5340
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005341#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005342 void
5343free_insexpand_stuff(void)
5344{
5345 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005346# ifdef FEAT_EVAL
5347 free_callback(&cfu_cb);
5348 free_callback(&ofu_cb);
5349 free_callback(&tsrfu_cb);
5350# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005351}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005352#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005353
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005354#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005355/*
5356 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5357 * spelled word, if there is one.
5358 */
5359 static void
5360spell_back_to_badword(void)
5361{
5362 pos_T tpos = curwin->w_cursor;
5363
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005364 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005365 if (curwin->w_cursor.col != tpos.col)
5366 start_arrow(&tpos);
5367}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005368#endif