blob: af818d4ad396536b9031fac415f1bcf3044b199c [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
zeertzjq41008522024-07-27 13:21:49 +0200117 int cp_user_hlattr; // highlight attribute to combine with
glepnir38f99a12024-08-23 18:31:06 +0200118 int cp_user_kind_hlattr; // highlight attribute for kind
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100119};
120
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200121// values for cp_flags
122# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
123# define CP_FREE_FNAME 2 // cp_fname is allocated
124# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
125# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
126# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200127# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100128
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100129/*
130 * All the current matches are stored in a list.
131 * "compl_first_match" points to the start of the list.
132 * "compl_curr_match" points to the currently selected entry.
133 * "compl_shown_match" is different from compl_curr_match during
134 * ins_compl_get_exp().
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000135 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100136 */
137static compl_T *compl_first_match = NULL;
138static compl_T *compl_curr_match = NULL;
139static compl_T *compl_shown_match = NULL;
140static compl_T *compl_old_match = NULL;
141
142// After using a cursor key <Enter> selects a match in the popup menu,
143// otherwise it inserts a line break.
144static int compl_enter_selects = FALSE;
145
146// When "compl_leader" is not NULL only matches that start with this string
147// are used.
148static char_u *compl_leader = NULL;
149
150static int compl_get_longest = FALSE; // put longest common string
151 // in compl_leader
152
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100153// Selected one of the matches. When FALSE the match was edited or using the
154// longest common string.
155static int compl_used_match;
156
157// didn't finish finding completions.
158static int compl_was_interrupted = FALSE;
159
160// Set when character typed while looking for matches and it means we should
161// stop looking for matches.
162static int compl_interrupted = FALSE;
163
164static int compl_restarting = FALSE; // don't insert match
165
166// When the first completion is done "compl_started" is set. When it's
167// FALSE the word to be completed must be located.
168static int compl_started = FALSE;
169
170// Which Ctrl-X mode are we in?
171static int ctrl_x_mode = CTRL_X_NORMAL;
172
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000173static int compl_matches = 0; // number of completion matches
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100174static char_u *compl_pattern = NULL;
John Marriott8c85a2a2024-05-20 19:18:26 +0200175static size_t compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100176static int compl_direction = FORWARD;
177static int compl_shows_dir = FORWARD;
178static int compl_pending = 0; // > 1 for postponed CTRL-N
179static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000180// Length in bytes of the text being completed (this is deleted to be replaced
181// by the match.)
182static int compl_length = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100183static colnr_T compl_col = 0; // column where the text starts
184 // that is being completed
185static char_u *compl_orig_text = NULL; // text as it was before
186 // completion started
187static int compl_cont_mode = 0;
188static expand_T compl_xp;
189
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000190// List of flags for method of completion.
191static int compl_cont_status = 0;
192# define CONT_ADDING 1 // "normal" or "adding" expansion
193# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
194 // it's set only iff N_ADDS is set
195# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
196# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
197 // if so, word-wise-expansion will set SOL
198# define CONT_SOL 16 // pattern includes start of line, just for
199 // word-wise expansion, not set for ^X^L
200# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
201 // expansion, (eg use complete=.)
202
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100203static int compl_opt_refresh_always = FALSE;
204static int compl_opt_suppress_empty = FALSE;
205
glepnira218cc62024-06-03 19:32:39 +0200206static int compl_selected_item = -1;
207
glepnir8159fb12024-07-17 20:32:54 +0200208static int *compl_fuzzy_scores;
209
glepnir38f99a12024-08-23 18:31:06 +0200210static 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, int user_hlattr, int user_kind_hlattr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100211static void ins_compl_longest_match(compl_T *match);
212static void ins_compl_del_pum(void);
213static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
214static char_u *find_line_end(char_u *ptr);
215static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100216static int ins_compl_need_restart(void);
217static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000218static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100219static void ins_compl_restart(void);
220static void ins_compl_set_original_text(char_u *str);
221static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
222# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
223static void ins_compl_add_list(list_T *list);
224static void ins_compl_add_dict(dict_T *dict);
225# endif
226static int ins_compl_key2dir(int c);
227static int ins_compl_pum_key(int c);
228static int ins_compl_key2count(int c);
229static void show_pum(int prev_w_wrow, int prev_w_leftcol);
230static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100231
232#ifdef FEAT_SPELL
233static void spell_back_to_badword(void);
234static int spell_bad_len = 0; // length of located bad word
235#endif
236
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100237/*
238 * CTRL-X pressed in Insert mode.
239 */
240 void
241ins_ctrl_x(void)
242{
zeertzjqdca29d92021-08-31 19:12:51 +0200243 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100244 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000245 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100246 if (compl_cont_status & CONT_N_ADDS)
247 compl_cont_status |= CONT_INTRPT;
248 else
249 compl_cont_status = 0;
250 // We're not sure which CTRL-X mode it will be yet
251 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
252 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
253 edit_submode_pre = NULL;
254 showmode();
255 }
zeertzjqdca29d92021-08-31 19:12:51 +0200256 else
257 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
258 // CTRL-V look like CTRL-N
259 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100260
LemonBoy2bf52dd2022-04-09 18:17:34 +0100261 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100262}
263
264/*
265 * Functions to check the current CTRL-X mode.
266 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000267int ctrl_x_mode_none(void)
268 { return ctrl_x_mode == 0; }
269int ctrl_x_mode_normal(void)
270 { return ctrl_x_mode == CTRL_X_NORMAL; }
271int ctrl_x_mode_scroll(void)
272 { return ctrl_x_mode == CTRL_X_SCROLL; }
273int ctrl_x_mode_whole_line(void)
274 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
275int ctrl_x_mode_files(void)
276 { return ctrl_x_mode == CTRL_X_FILES; }
277int ctrl_x_mode_tags(void)
278 { return ctrl_x_mode == CTRL_X_TAGS; }
279int ctrl_x_mode_path_patterns(void)
280 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
281int ctrl_x_mode_path_defines(void)
282 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
283int ctrl_x_mode_dictionary(void)
284 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
285int ctrl_x_mode_thesaurus(void)
286 { return ctrl_x_mode == CTRL_X_THESAURUS; }
287int ctrl_x_mode_cmdline(void)
288 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200289 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000290int ctrl_x_mode_function(void)
291 { return ctrl_x_mode == CTRL_X_FUNCTION; }
292int ctrl_x_mode_omni(void)
293 { return ctrl_x_mode == CTRL_X_OMNI; }
294int ctrl_x_mode_spell(void)
295 { return ctrl_x_mode == CTRL_X_SPELL; }
296static int ctrl_x_mode_eval(void)
297 { return ctrl_x_mode == CTRL_X_EVAL; }
298int ctrl_x_mode_line_or_eval(void)
299 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100300
301/*
302 * Whether other than default completion has been selected.
303 */
304 int
305ctrl_x_mode_not_default(void)
306{
307 return ctrl_x_mode != CTRL_X_NORMAL;
308}
309
310/*
zeertzjqdca29d92021-08-31 19:12:51 +0200311 * Whether CTRL-X was typed without a following character,
312 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100313 */
314 int
315ctrl_x_mode_not_defined_yet(void)
316{
317 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
318}
319
320/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000321 * Return TRUE if currently in "normal" or "adding" insert completion matches
322 * state
323 */
324 int
325compl_status_adding(void)
326{
327 return compl_cont_status & CONT_ADDING;
328}
329
330/*
331 * Return TRUE if the completion pattern includes start of line, just for
332 * word-wise expansion.
333 */
334 int
335compl_status_sol(void)
336{
337 return compl_cont_status & CONT_SOL;
338}
339
340/*
341 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
342 */
343 int
344compl_status_local(void)
345{
346 return compl_cont_status & CONT_LOCAL;
347}
348
349/*
350 * Clear the completion status flags
351 */
352 void
353compl_status_clear(void)
354{
355 compl_cont_status = 0;
356}
357
358/*
359 * Return TRUE if completion is using the forward direction matches
360 */
361 static int
362compl_dir_forward(void)
363{
364 return compl_direction == FORWARD;
365}
366
367/*
368 * Return TRUE if currently showing forward completion matches
369 */
370 static int
371compl_shows_dir_forward(void)
372{
373 return compl_shows_dir == FORWARD;
374}
375
376/*
377 * Return TRUE if currently showing backward completion matches
378 */
379 static int
380compl_shows_dir_backward(void)
381{
382 return compl_shows_dir == BACKWARD;
383}
384
385/*
386 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100387 */
388 int
389has_compl_option(int dict_opt)
390{
391 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200392#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100393 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200394#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100395 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100396 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
397#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100398 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100399#endif
400 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100401 {
402 ctrl_x_mode = CTRL_X_NORMAL;
403 edit_submode = NULL;
404 msg_attr(dict_opt ? _("'dictionary' option is empty")
405 : _("'thesaurus' option is empty"),
406 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100407 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100408 {
409 vim_beep(BO_COMPL);
410 setcursor();
411 out_flush();
412#ifdef FEAT_EVAL
413 if (!get_vim_var_nr(VV_TESTING))
414#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100415 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100416 }
417 return FALSE;
418 }
419 return TRUE;
420}
421
422/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000423 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100424 * This depends on the current mode.
425 */
426 int
427vim_is_ctrl_x_key(int c)
428{
429 // Always allow ^R - let its results then be checked
430 if (c == Ctrl_R)
431 return TRUE;
432
433 // Accept <PageUp> and <PageDown> if the popup menu is visible.
434 if (ins_compl_pum_key(c))
435 return TRUE;
436
437 switch (ctrl_x_mode)
438 {
439 case 0: // Not in any CTRL-X mode
440 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
441 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200442 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100443 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
444 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
445 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
446 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
447 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200448 || c == Ctrl_S || c == Ctrl_K || c == 's'
449 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100450 case CTRL_X_SCROLL:
451 return (c == Ctrl_Y || c == Ctrl_E);
452 case CTRL_X_WHOLE_LINE:
453 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
454 case CTRL_X_FILES:
455 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
456 case CTRL_X_DICTIONARY:
457 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
458 case CTRL_X_THESAURUS:
459 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
460 case CTRL_X_TAGS:
461 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
462#ifdef FEAT_FIND_ID
463 case CTRL_X_PATH_PATTERNS:
464 return (c == Ctrl_P || c == Ctrl_N);
465 case CTRL_X_PATH_DEFINES:
466 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
467#endif
468 case CTRL_X_CMDLINE:
469 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
470 || c == Ctrl_X);
471#ifdef FEAT_COMPL_FUNC
472 case CTRL_X_FUNCTION:
473 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
474 case CTRL_X_OMNI:
475 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
476#endif
477 case CTRL_X_SPELL:
478 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
479 case CTRL_X_EVAL:
480 return (c == Ctrl_P || c == Ctrl_N);
481 }
482 internal_error("vim_is_ctrl_x_key()");
483 return FALSE;
484}
485
486/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000487 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000488 */
489 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000490match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000491{
492 return match->cp_flags & CP_ORIGINAL_TEXT;
493}
494
495/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000496 * Returns TRUE if "match" is the first match in the completion list.
497 */
498 static int
499is_first_match(compl_T *match)
500{
501 return match == compl_first_match;
502}
503
504/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100505 * Return TRUE when character "c" is part of the item currently being
506 * completed. Used to decide whether to abandon complete mode when the menu
507 * is visible.
508 */
509 int
510ins_compl_accept_char(int c)
511{
512 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
513 // When expanding an identifier only accept identifier chars.
514 return vim_isIDc(c);
515
516 switch (ctrl_x_mode)
517 {
518 case CTRL_X_FILES:
519 // When expanding file name only accept file name chars. But not
520 // path separators, so that "proto/<Tab>" expands files in
521 // "proto", not "proto/" as a whole
522 return vim_isfilec(c) && !vim_ispathsep(c);
523
524 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200525 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100526 case CTRL_X_OMNI:
527 // Command line and Omni completion can work with just about any
528 // printable character, but do stop at white space.
529 return vim_isprintc(c) && !VIM_ISWHITE(c);
530
531 case CTRL_X_WHOLE_LINE:
532 // For while line completion a space can be part of the line.
533 return vim_isprintc(c);
534 }
535 return vim_iswordc(c);
536}
537
538/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000539 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100540 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000541 */
542 static char_u *
543ins_compl_infercase_gettext(
544 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100545 int char_len,
546 int compl_char_len,
547 int min_len,
548 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000549{
550 int *wca; // Wide character array.
551 char_u *p;
552 int i, c;
553 int has_lower = FALSE;
554 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100555 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000556
557 IObuff[0] = NUL;
558
559 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100560 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000561 if (wca == NULL)
562 return IObuff;
563
564 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100565 for (i = 0; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000566 if (has_mbyte)
567 wca[i] = mb_ptr2char_adv(&p);
568 else
569 wca[i] = *(p++);
570
571 // Rule 1: Were any chars converted to lower?
572 p = compl_orig_text;
573 for (i = 0; i < min_len; ++i)
574 {
575 if (has_mbyte)
576 c = mb_ptr2char_adv(&p);
577 else
578 c = *(p++);
579 if (MB_ISLOWER(c))
580 {
581 has_lower = TRUE;
582 if (MB_ISUPPER(wca[i]))
583 {
584 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100585 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000586 wca[i] = MB_TOLOWER(wca[i]);
587 break;
588 }
589 }
590 }
591
592 // Rule 2: No lower case, 2nd consecutive letter converted to
593 // upper case.
594 if (!has_lower)
595 {
596 p = compl_orig_text;
597 for (i = 0; i < min_len; ++i)
598 {
599 if (has_mbyte)
600 c = mb_ptr2char_adv(&p);
601 else
602 c = *(p++);
603 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
604 {
605 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100606 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000607 wca[i] = MB_TOUPPER(wca[i]);
608 break;
609 }
610 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
611 }
612 }
613
614 // Copy the original case of the part we typed.
615 p = compl_orig_text;
616 for (i = 0; i < min_len; ++i)
617 {
618 if (has_mbyte)
619 c = mb_ptr2char_adv(&p);
620 else
621 c = *(p++);
622 if (MB_ISLOWER(c))
623 wca[i] = MB_TOLOWER(wca[i]);
624 else if (MB_ISUPPER(c))
625 wca[i] = MB_TOUPPER(wca[i]);
626 }
627
628 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000629 p = IObuff;
630 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100631 ga_init2(&gap, 1, 500);
632 while (i < char_len)
633 {
634 if (gap.ga_data != NULL)
635 {
636 if (ga_grow(&gap, 10) == FAIL)
637 {
638 ga_clear(&gap);
639 return (char_u *)"[failed]";
640 }
641 p = (char_u *)gap.ga_data + gap.ga_len;
642 if (has_mbyte)
643 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
644 else
645 {
646 *p = wca[i++];
647 ++gap.ga_len;
648 }
649 }
650 else if ((p - IObuff) + 6 >= IOSIZE)
651 {
652 // Multi-byte characters can occupy up to five bytes more than
653 // ASCII characters, and we also need one byte for NUL, so when
654 // getting to six bytes from the edge of IObuff switch to using a
655 // growarray. Add the character in the next round.
656 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100657 {
658 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100659 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100660 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100661 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100662 STRCPY(gap.ga_data, IObuff);
Bram Moolenaarc7bd2f02022-07-15 20:45:20 +0100663 gap.ga_len = (int)STRLEN(IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100664 }
665 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000666 p += (*mb_char2bytes)(wca[i++], p);
667 else
668 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100669 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000670 vim_free(wca);
671
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100672 if (gap.ga_data != NULL)
673 {
674 *tofree = gap.ga_data;
675 return gap.ga_data;
676 }
677
678 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000679 return IObuff;
680}
681
682/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100683 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
684 * case of the originally typed text is used, and the case of the completed
685 * text is inferred, ie this tries to work out what case you probably wanted
686 * the rest of the word to be in -- webb
687 */
688 int
689ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200690 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100691 int len,
692 int icase,
693 char_u *fname,
694 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200695 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100696{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200697 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100698 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100699 int char_len; // count multi-byte characters
700 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100701 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200702 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100703 int res;
704 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100705
706 if (p_ic && curbuf->b_p_inf && len > 0)
707 {
708 // Infer case of completed part.
709
710 // Find actual length of completion.
711 if (has_mbyte)
712 {
713 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100714 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100715 while (*p != NUL)
716 {
717 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100718 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100719 }
720 }
721 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100722 char_len = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100723
724 // Find actual length of original text.
725 if (has_mbyte)
726 {
727 p = compl_orig_text;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100728 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100729 while (*p != NUL)
730 {
731 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100732 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100733 }
734 }
735 else
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100736 compl_char_len = compl_length;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100737
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100739 // thesaurus, only use the minimum when comparing.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 min_len = char_len < compl_char_len ? char_len : compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100741
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100742 str = ins_compl_infercase_gettext(str, char_len,
743 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100744 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200745 if (cont_s_ipos)
746 flags |= CP_CONT_S_IPOS;
747 if (icase)
748 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200749
glepnir38f99a12024-08-23 18:31:06 +0200750 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, -1, -1);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100751 vim_free(tofree);
752 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100753}
754
755/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000756 * Add a match to the list of matches. The arguments are:
757 * str - text of the match to add
758 * len - length of "str". If -1, then the length of "str" is
759 * computed.
760 * fname - file name to associate with this match.
761 * cptext - list of strings to use with this match (for abbr, menu, info
762 * and kind)
763 * user_data - user supplied data (any vim type) for this match
764 * cdir - match direction. If 0, use "compl_direction".
765 * flags_arg - match flags (cp_flags)
766 * adup - accept this match even if it is already present.
767 * If "cdir" is FORWARD, then the match is added after the current match.
768 * Otherwise, it is added before the current match.
769 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100770 * If the given string is already in the list of completions, then return
771 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
772 * maybe because alloc() returns NULL, then FAIL is returned.
773 */
774 static int
775ins_compl_add(
776 char_u *str,
777 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100778 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100779 char_u **cptext, // extra text for popup menu or NULL
780 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100781 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200782 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200783 int adup, // accept duplicate match
glepnir38f99a12024-08-23 18:31:06 +0200784 int user_hlattr,
785 int user_kind_hlattr)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100786{
787 compl_T *match;
788 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200789 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100790
Bram Moolenaarceb06192021-04-04 15:05:22 +0200791 if (flags & CP_FAST)
792 fast_breakcheck();
793 else
794 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100795 if (got_int)
796 return FAIL;
797 if (len < 0)
798 len = (int)STRLEN(str);
799
800 // If the same match is already present, don't add it.
801 if (compl_first_match != NULL && !adup)
802 {
803 match = compl_first_match;
804 do
805 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000806 if (!match_at_original_text(match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100807 && STRNCMP(match->cp_str, str, len) == 0
Bram Moolenaarbaefde12022-07-07 19:59:49 +0100808 && ((int)STRLEN(match->cp_str) <= len
809 || match->cp_str[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100810 return NOTDONE;
811 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000812 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100813 }
814
815 // Remove any popup menu before changing the list of matches.
816 ins_compl_del_pum();
817
818 // Allocate a new match structure.
819 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200820 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100821 if (match == NULL)
822 return FAIL;
823 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200824 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100825 match->cp_number = 0;
826 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
827 {
828 vim_free(match);
829 return FAIL;
830 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100831
832 // match-fname is:
833 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200834 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100835 // - NULL otherwise. --Acevedo
836 if (fname != NULL
837 && compl_curr_match != NULL
838 && compl_curr_match->cp_fname != NULL
839 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
840 match->cp_fname = compl_curr_match->cp_fname;
841 else if (fname != NULL)
842 {
843 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200844 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100845 }
846 else
847 match->cp_fname = NULL;
848 match->cp_flags = flags;
zeertzjq41008522024-07-27 13:21:49 +0200849 match->cp_user_hlattr = user_hlattr;
glepnir38f99a12024-08-23 18:31:06 +0200850 match->cp_user_kind_hlattr = user_kind_hlattr;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100851
852 if (cptext != NULL)
853 {
854 int i;
855
856 for (i = 0; i < CPT_COUNT; ++i)
857 if (cptext[i] != NULL && *cptext[i] != NUL)
858 match->cp_text[i] = vim_strsave(cptext[i]);
859 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100860#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100861 if (user_data != NULL)
862 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100863#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100864
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000865 // Link the new match structure after (FORWARD) or before (BACKWARD) the
866 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100867 if (compl_first_match == NULL)
868 match->cp_next = match->cp_prev = NULL;
869 else if (dir == FORWARD)
870 {
871 match->cp_next = compl_curr_match->cp_next;
872 match->cp_prev = compl_curr_match;
873 }
874 else // BACKWARD
875 {
876 match->cp_next = compl_curr_match;
877 match->cp_prev = compl_curr_match->cp_prev;
878 }
879 if (match->cp_next)
880 match->cp_next->cp_prev = match;
881 if (match->cp_prev)
882 match->cp_prev->cp_next = match;
883 else // if there's nothing before, it is the first match
884 compl_first_match = match;
885 compl_curr_match = match;
886
887 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200888 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100889 ins_compl_longest_match(match);
890
891 return OK;
892}
893
894/*
895 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200896 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100897 */
898 static int
899ins_compl_equal(compl_T *match, char_u *str, int len)
900{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200901 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200902 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200903 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100904 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
905 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
906}
907
908/*
909 * Reduce the longest common string for match "match".
910 */
911 static void
912ins_compl_longest_match(compl_T *match)
913{
914 char_u *p, *s;
915 int c1, c2;
916 int had_match;
917
918 if (compl_leader == NULL)
919 {
920 // First match, use it as a whole.
921 compl_leader = vim_strsave(match->cp_str);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000922 if (compl_leader == NULL)
923 return;
924
925 had_match = (curwin->w_cursor.col > compl_col);
926 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000927 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000928 ins_redraw(FALSE);
929
930 // When the match isn't there (to avoid matching itself) remove it
931 // again after redrawing.
932 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100933 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100934 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000935
936 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100937 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000938
939 // Reduce the text if this match differs from compl_leader.
940 p = compl_leader;
941 s = match->cp_str;
942 while (*p != NUL)
943 {
944 if (has_mbyte)
945 {
946 c1 = mb_ptr2char(p);
947 c2 = mb_ptr2char(s);
948 }
949 else
950 {
951 c1 = *p;
952 c2 = *s;
953 }
954 if ((match->cp_flags & CP_ICASE)
955 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
956 break;
957 if (has_mbyte)
958 {
959 MB_PTR_ADV(p);
960 MB_PTR_ADV(s);
961 }
962 else
963 {
964 ++p;
965 ++s;
966 }
967 }
968
969 if (*p != NUL)
970 {
971 // Leader was shortened, need to change the inserted text.
972 *p = NUL;
973 had_match = (curwin->w_cursor.col > compl_col);
974 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000975 ins_bytes(compl_leader + get_compl_len());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000976 ins_redraw(FALSE);
977
978 // When the match isn't there (to avoid matching itself) remove it
979 // again after redrawing.
980 if (!had_match)
981 ins_compl_delete();
982 }
983
984 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100985}
986
987/*
988 * Add an array of matches to the list of matches.
989 * Frees matches[].
990 */
991 static void
992ins_compl_add_matches(
993 int num_matches,
994 char_u **matches,
995 int icase)
996{
997 int i;
998 int add_r = OK;
999 int dir = compl_direction;
1000
1001 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +01001002 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnir38f99a12024-08-23 18:31:06 +02001003 CP_FAST | (icase ? CP_ICASE : 0), FALSE, -1, -1)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001004 // if dir was BACKWARD then honor it just once
1005 dir = FORWARD;
1006 FreeWild(num_matches, matches);
1007}
1008
1009/*
1010 * Make the completion list cyclic.
1011 * Return the number of matches (excluding the original).
1012 */
1013 static int
1014ins_compl_make_cyclic(void)
1015{
1016 compl_T *match;
1017 int count = 0;
1018
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001019 if (compl_first_match == NULL)
1020 return 0;
1021
1022 // Find the end of the list.
1023 match = compl_first_match;
1024 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001025 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001026 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001027 match = match->cp_next;
1028 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001029 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001030 match->cp_next = compl_first_match;
1031 compl_first_match->cp_prev = match;
1032
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001033 return count;
1034}
1035
1036/*
1037 * Return whether there currently is a shown match.
1038 */
1039 int
1040ins_compl_has_shown_match(void)
1041{
1042 return compl_shown_match == NULL
1043 || compl_shown_match != compl_shown_match->cp_next;
1044}
1045
1046/*
1047 * Return whether the shown match is long enough.
1048 */
1049 int
1050ins_compl_long_shown_match(void)
1051{
1052 return (int)STRLEN(compl_shown_match->cp_str)
1053 > curwin->w_cursor.col - compl_col;
1054}
1055
1056/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001057 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001058 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001059 unsigned int
1060get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001061{
zeertzjq529b9ad2024-06-05 20:27:06 +02001062 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001063}
1064
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001065
1066// "compl_match_array" points the currently displayed list of entries in the
1067// popup menu. It is NULL when there is no popup menu.
1068static pumitem_T *compl_match_array = NULL;
1069static int compl_match_arraysize;
1070
1071/*
1072 * Update the screen and when there is any scrolling remove the popup menu.
1073 */
1074 static void
1075ins_compl_upd_pum(void)
1076{
1077 int h;
1078
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001079 if (compl_match_array == NULL)
1080 return;
1081
1082 h = curwin->w_cline_height;
1083 // Update the screen later, before drawing the popup menu over it.
1084 pum_call_update_screen();
1085 if (h != curwin->w_cline_height)
1086 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001087}
1088
1089/*
1090 * Remove any popup menu.
1091 */
1092 static void
1093ins_compl_del_pum(void)
1094{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001095 if (compl_match_array == NULL)
1096 return;
1097
1098 pum_undisplay();
1099 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001100}
1101
1102/*
1103 * Return TRUE if the popup menu should be displayed.
1104 */
1105 int
1106pum_wanted(void)
1107{
1108 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001109 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001110 return FALSE;
1111
1112 // The display looks bad on a B&W display.
1113 if (t_colors < 8
1114#ifdef FEAT_GUI
1115 && !gui.in_use
1116#endif
1117 )
1118 return FALSE;
1119 return TRUE;
1120}
1121
1122/*
1123 * Return TRUE if there are two or more matches to be shown in the popup menu.
1124 * One if 'completopt' contains "menuone".
1125 */
1126 static int
1127pum_enough_matches(void)
1128{
1129 compl_T *compl;
1130 int i;
1131
1132 // Don't display the popup menu if there are no matches or there is only
1133 // one (ignoring the original text).
1134 compl = compl_first_match;
1135 i = 0;
1136 do
1137 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001138 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001139 break;
1140 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001141 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001142
zeertzjq529b9ad2024-06-05 20:27:06 +02001143 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001144 return (i >= 1);
1145 return (i >= 2);
1146}
1147
Bram Moolenaar3075a452021-11-17 15:51:52 +00001148#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001149/*
1150 * Allocate Dict for the completed item.
1151 * { word, abbr, menu, kind, info }
1152 */
1153 static dict_T *
1154ins_compl_dict_alloc(compl_T *match)
1155{
1156 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1157
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 if (dict == NULL)
1159 return NULL;
1160
1161 dict_add_string(dict, "word", match->cp_str);
1162 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1163 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1164 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1165 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1166 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1167 dict_add_string(dict, "user_data", (char_u *)"");
1168 else
1169 dict_add_tv(dict, "user_data", &match->cp_user_data);
1170
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001171 return dict;
1172}
1173
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001174/*
1175 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1176 * completion menu is changed.
1177 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001178 static void
1179trigger_complete_changed_event(int cur)
1180{
1181 dict_T *v_event;
1182 dict_T *item;
1183 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001184 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001185
1186 if (recursive)
1187 return;
1188
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001189 if (cur < 0)
1190 item = dict_alloc();
1191 else
1192 item = ins_compl_dict_alloc(compl_curr_match);
1193 if (item == NULL)
1194 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001195 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001196 dict_add_dict(v_event, "completed_item", item);
1197 pum_set_event_info(v_event);
1198 dict_set_items_ro(v_event);
1199
1200 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001201 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001202 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001203 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001204 recursive = FALSE;
1205
Bram Moolenaar3075a452021-11-17 15:51:52 +00001206 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001207}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001208#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001209
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001210/*
glepnira218cc62024-06-03 19:32:39 +02001211 * pumitem qsort compare func
1212 */
1213 static int
zeertzjq8e567472024-06-14 20:04:42 +02001214ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001215{
1216 const int sa = (*(pumitem_T *)a).pum_score;
1217 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001218 const int ia = (*(pumitem_T *)a).pum_idx;
1219 const int ib = (*(pumitem_T *)b).pum_idx;
1220 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001221}
1222
1223/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001224 * Build a popup menu to show the completion matches.
1225 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1226 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001228 static int
1229ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001230{
1231 compl_T *compl;
1232 compl_T *shown_compl = NULL;
1233 int did_find_shown_match = FALSE;
1234 int shown_match_ok = FALSE;
1235 int i;
1236 int cur = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001237 int lead_len = 0;
glepnira218cc62024-06-03 19:32:39 +02001238 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001239 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001240 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
1241 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001242
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001243 // Need to build the popup menu list.
1244 compl_match_arraysize = 0;
1245 compl = compl_first_match;
1246 if (compl_leader != NULL)
1247 lead_len = (int)STRLEN(compl_leader);
1248
1249 do
1250 {
zeertzjq551d8c32024-06-05 19:53:32 +02001251 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1252 // set the cp_score for later comparisons.
glepnira218cc62024-06-03 19:32:39 +02001253 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
1254 compl->cp_score = fuzzy_match_str(compl->cp_str, compl_leader);
1255
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001256 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001257 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001258 || ins_compl_equal(compl, compl_leader, lead_len)
1259 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001260 ++compl_match_arraysize;
1261 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001262 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001263
1264 if (compl_match_arraysize == 0)
1265 return -1;
1266
1267 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1268 if (compl_match_array == NULL)
1269 return -1;
1270
1271 // If the current match is the original text don't find the first
1272 // match after it, don't highlight anything.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001273 if (match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001274 shown_match_ok = TRUE;
1275
glepnir53387c52024-05-27 15:11:01 +02001276 if (compl_leader != NULL
1277 && STRCMP(compl_leader, compl_orig_text) == 0
1278 && shown_match_ok == FALSE)
1279 compl_shown_match = compl_no_select ? compl_first_match
1280 : compl_first_match->cp_next;
1281
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001282 i = 0;
1283 compl = compl_first_match;
1284 do
1285 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001286 if (!match_at_original_text(compl)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001287 && (compl_leader == NULL
glepnira218cc62024-06-03 19:32:39 +02001288 || ins_compl_equal(compl, compl_leader, lead_len)
1289 || (compl_fuzzy_match && compl->cp_score > 0)))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001290 {
glepnira218cc62024-06-03 19:32:39 +02001291 if (!shown_match_ok && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001292 {
1293 if (compl == compl_shown_match || did_find_shown_match)
1294 {
1295 // This item is the shown match or this is the
1296 // first displayed item after the shown match.
1297 compl_shown_match = compl;
1298 did_find_shown_match = TRUE;
1299 shown_match_ok = TRUE;
1300 }
1301 else
1302 // Remember this displayed match for when the
1303 // shown match is just below it.
1304 shown_compl = compl;
1305 cur = i;
1306 }
glepnira218cc62024-06-03 19:32:39 +02001307 else if (compl_fuzzy_match)
1308 {
glepnirf94c9c42024-06-14 21:11:56 +02001309 if (i == 0)
glepnir105f7412024-06-15 15:32:22 +02001310 shown_compl = compl;
glepnirdca57fb2024-06-04 22:01:21 +02001311 // Update the maximum fuzzy score and the shown match
1312 // if the current item's score is higher
glepnira218cc62024-06-03 19:32:39 +02001313 if (compl->cp_score > max_fuzzy_score)
1314 {
1315 did_find_shown_match = TRUE;
1316 max_fuzzy_score = compl->cp_score;
glepnir753794b2024-08-20 19:58:44 +02001317 if (!compl_no_select)
1318 compl_shown_match = compl;
glepnir65407ce2024-07-06 16:09:19 +02001319 }
1320
1321 if (!shown_match_ok && compl == compl_shown_match && !compl_no_select)
1322 {
1323 cur = i;
glepnira218cc62024-06-03 19:32:39 +02001324 shown_match_ok = TRUE;
1325 }
1326
glepnirdca57fb2024-06-04 22:01:21 +02001327 // If there is no "no select" condition and the max fuzzy
1328 // score is positive, or there is no completion leader or the
1329 // leader length is zero, mark the shown match as valid and
1330 // reset the current index.
glepnira218cc62024-06-03 19:32:39 +02001331 if (!compl_no_select
1332 && (max_fuzzy_score > 0
1333 || (compl_leader == NULL || lead_len == 0)))
1334 {
glepnirf94c9c42024-06-14 21:11:56 +02001335 if (match_at_original_text(compl_shown_match))
glepnir105f7412024-06-15 15:32:22 +02001336 compl_shown_match = shown_compl;
glepnira218cc62024-06-03 19:32:39 +02001337 }
1338 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001339
1340 if (compl->cp_text[CPT_ABBR] != NULL)
1341 compl_match_array[i].pum_text =
1342 compl->cp_text[CPT_ABBR];
1343 else
1344 compl_match_array[i].pum_text = compl->cp_str;
1345 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1346 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
glepnira218cc62024-06-03 19:32:39 +02001347 compl_match_array[i].pum_score = compl->cp_score;
zeertzjq41008522024-07-27 13:21:49 +02001348 compl_match_array[i].pum_user_hlattr = compl->cp_user_hlattr;
glepnir38f99a12024-08-23 18:31:06 +02001349 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001350 if (compl->cp_text[CPT_MENU] != NULL)
1351 compl_match_array[i++].pum_extra =
1352 compl->cp_text[CPT_MENU];
1353 else
1354 compl_match_array[i++].pum_extra = compl->cp_fname;
1355 }
1356
glepnira218cc62024-06-03 19:32:39 +02001357 if (compl == compl_shown_match && !compl_fuzzy_match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001358 {
1359 did_find_shown_match = TRUE;
1360
1361 // When the original text is the shown match don't set
1362 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001363 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001364 shown_match_ok = TRUE;
1365
1366 if (!shown_match_ok && shown_compl != NULL)
1367 {
1368 // The shown match isn't displayed, set it to the
1369 // previously displayed match.
1370 compl_shown_match = shown_compl;
1371 shown_match_ok = TRUE;
1372 }
1373 }
1374 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001375 } while (compl != NULL && !is_first_match(compl));
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001376
glepnira218cc62024-06-03 19:32:39 +02001377 if (compl_fuzzy_match && compl_leader != NULL && lead_len > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001378 {
1379 for (i = 0; i < compl_match_arraysize; i++)
1380 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001381 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001382 qsort(compl_match_array, (size_t)compl_match_arraysize,
1383 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001384 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001385 }
glepnira218cc62024-06-03 19:32:39 +02001386
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001387 if (!shown_match_ok) // no displayed match at all
1388 cur = -1;
1389
1390 return cur;
1391}
1392
1393/*
1394 * Show the popup menu for the list of matches.
1395 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1396 */
1397 void
1398ins_compl_show_pum(void)
1399{
1400 int i;
1401 int cur = -1;
1402 colnr_T col;
1403
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001404 if (!pum_wanted() || !pum_enough_matches())
1405 return;
1406
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001407 // Update the screen later, before drawing the popup menu over it.
1408 pum_call_update_screen();
1409
1410 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001411 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001412 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001413 else
1414 {
1415 // popup menu already exists, only need to find the current item.
1416 for (i = 0; i < compl_match_arraysize; ++i)
1417 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1418 || compl_match_array[i].pum_text
1419 == compl_shown_match->cp_text[CPT_ABBR])
1420 {
1421 cur = i;
1422 break;
1423 }
1424 }
1425
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001426 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001427 {
1428#ifdef FEAT_EVAL
1429 if (compl_started && has_completechanged())
1430 trigger_complete_changed_event(cur);
1431#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001432 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001433 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001434
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001435 // In Replace mode when a $ is displayed at the end of the line only
1436 // part of the screen would be updated. We do need to redraw here.
1437 dollar_vcol = -1;
1438
1439 // Compute the screen column of the start of the completed text.
1440 // Use the cursor to get all wrapping and other settings right.
1441 col = curwin->w_cursor.col;
1442 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001443 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001444 pum_display(compl_match_array, compl_match_arraysize, cur);
1445 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001446
glepnircbb46b42024-02-03 18:11:13 +01001447 // After adding leader, set the current match to shown match.
1448 if (compl_started && compl_curr_match != compl_shown_match)
1449 compl_curr_match = compl_shown_match;
1450
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001451#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001452 if (has_completechanged())
1453 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001454#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001455}
1456
1457#define DICT_FIRST (1) // use just first element in "dict"
1458#define DICT_EXACT (2) // "dict" is the exact name of a file
1459
1460/*
glepnir40c1c332024-06-11 19:37:04 +02001461 * Get current completion leader
1462 */
1463 char_u *
1464ins_compl_leader(void)
1465{
glepnirf1891382024-06-17 18:35:25 +02001466 return compl_leader != NULL ? compl_leader : compl_orig_text;
glepnir40c1c332024-06-11 19:37:04 +02001467}
1468
1469/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001470 * Add any identifiers that match the given pattern "pat" in the list of
1471 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001472 */
1473 static void
1474ins_compl_dictionaries(
1475 char_u *dict_start,
1476 char_u *pat,
1477 int flags, // DICT_FIRST and/or DICT_EXACT
1478 int thesaurus) // Thesaurus completion
1479{
1480 char_u *dict = dict_start;
1481 char_u *ptr;
1482 char_u *buf;
1483 regmatch_T regmatch;
1484 char_u **files;
1485 int count;
1486 int save_p_scs;
1487 int dir = compl_direction;
1488
1489 if (*dict == NUL)
1490 {
1491#ifdef FEAT_SPELL
1492 // When 'dictionary' is empty and spell checking is enabled use
1493 // "spell".
1494 if (!thesaurus && curwin->w_p_spell)
1495 dict = (char_u *)"spell";
1496 else
1497#endif
1498 return;
1499 }
1500
1501 buf = alloc(LSIZE);
1502 if (buf == NULL)
1503 return;
1504 regmatch.regprog = NULL; // so that we can goto theend
1505
1506 // If 'infercase' is set, don't use 'smartcase' here
1507 save_p_scs = p_scs;
1508 if (curbuf->b_p_inf)
1509 p_scs = FALSE;
1510
1511 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1512 // to only match at the start of a line. Otherwise just match the
1513 // pattern. Also need to double backslashes.
1514 if (ctrl_x_mode_line_or_eval())
1515 {
1516 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1517 size_t len;
1518
1519 if (pat_esc == NULL)
1520 goto theend;
1521 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001522 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001523 if (ptr == NULL)
1524 {
1525 vim_free(pat_esc);
1526 goto theend;
1527 }
1528 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1529 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1530 vim_free(pat_esc);
1531 vim_free(ptr);
1532 }
1533 else
1534 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001535 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001536 if (regmatch.regprog == NULL)
1537 goto theend;
1538 }
1539
1540 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1541 regmatch.rm_ic = ignorecase(pat);
1542 while (*dict != NUL && !got_int && !compl_interrupted)
1543 {
1544 // copy one dictionary file name into buf
1545 if (flags == DICT_EXACT)
1546 {
1547 count = 1;
1548 files = &dict;
1549 }
1550 else
1551 {
1552 // Expand wildcards in the dictionary name, but do not allow
1553 // backticks (for security, the 'dict' option may have been set in
1554 // a modeline).
1555 copy_option_part(&dict, buf, LSIZE, ",");
1556# ifdef FEAT_SPELL
1557 if (!thesaurus && STRCMP(buf, "spell") == 0)
1558 count = -1;
1559 else
1560# endif
1561 if (vim_strchr(buf, '`') != NULL
1562 || expand_wildcards(1, &buf, &count, &files,
1563 EW_FILE|EW_SILENT) != OK)
1564 count = 0;
1565 }
1566
1567# ifdef FEAT_SPELL
1568 if (count == -1)
1569 {
1570 // Complete from active spelling. Skip "\<" in the pattern, we
1571 // don't use it as a RE.
1572 if (pat[0] == '\\' && pat[1] == '<')
1573 ptr = pat + 2;
1574 else
1575 ptr = pat;
1576 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1577 }
1578 else
1579# endif
1580 if (count > 0) // avoid warning for using "files" uninit
1581 {
1582 ins_compl_files(count, files, thesaurus, flags,
1583 &regmatch, buf, &dir);
1584 if (flags != DICT_EXACT)
1585 FreeWild(count, files);
1586 }
1587 if (flags != 0)
1588 break;
1589 }
1590
1591theend:
1592 p_scs = save_p_scs;
1593 vim_regfree(regmatch.regprog);
1594 vim_free(buf);
1595}
1596
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001597/*
1598 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1599 * skipping the word at 'skip_word'. Returns OK on success.
1600 */
1601 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001602thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001603 char_u *fname,
1604 char_u **buf_arg,
1605 int dir,
1606 char_u *skip_word)
1607{
1608 int status = OK;
1609 char_u *ptr;
1610 char_u *wstart;
1611
1612 // Add the other matches on the line
1613 ptr = *buf_arg;
1614 while (!got_int)
1615 {
1616 // Find start of the next word. Skip white
1617 // space and punctuation.
1618 ptr = find_word_start(ptr);
1619 if (*ptr == NUL || *ptr == NL)
1620 break;
1621 wstart = ptr;
1622
1623 // Find end of the word.
1624 if (has_mbyte)
1625 // Japanese words may have characters in
1626 // different classes, only separate words
1627 // with single-byte non-word characters.
1628 while (*ptr != NUL)
1629 {
1630 int l = (*mb_ptr2len)(ptr);
1631
1632 if (l < 2 && !vim_iswordc(*ptr))
1633 break;
1634 ptr += l;
1635 }
1636 else
1637 ptr = find_word_end(ptr);
1638
1639 // Add the word. Skip the regexp match.
1640 if (wstart != skip_word)
1641 {
1642 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
1643 fname, dir, FALSE);
1644 if (status == FAIL)
1645 break;
1646 }
1647 }
1648
1649 *buf_arg = ptr;
1650 return status;
1651}
1652
1653/*
1654 * Process "count" dictionary/thesaurus "files" and add the text matching
1655 * "regmatch".
1656 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001657 static void
1658ins_compl_files(
1659 int count,
1660 char_u **files,
1661 int thesaurus,
1662 int flags,
1663 regmatch_T *regmatch,
1664 char_u *buf,
1665 int *dir)
1666{
1667 char_u *ptr;
1668 int i;
1669 FILE *fp;
1670 int add_r;
1671
1672 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1673 {
1674 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001675 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001676 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001677 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001678 vim_snprintf((char *)IObuff, IOSIZE,
1679 _("Scanning dictionary: %s"), (char *)files[i]);
1680 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1681 }
1682
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001683 if (fp == NULL)
1684 continue;
1685
1686 // Read dictionary file line by line.
1687 // Check each line for a match.
1688 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001689 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001690 ptr = buf;
1691 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001692 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001693 ptr = regmatch->startp[0];
1694 if (ctrl_x_mode_line_or_eval())
1695 ptr = find_line_end(ptr);
1696 else
1697 ptr = find_word_end(ptr);
1698 add_r = ins_compl_add_infercase(regmatch->startp[0],
1699 (int)(ptr - regmatch->startp[0]),
1700 p_ic, files[i], *dir, FALSE);
1701 if (thesaurus)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001702 {
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001703 // For a thesaurus, add all the words in the line
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001704 ptr = buf;
zeertzjq5fb3aab2022-08-24 16:48:23 +01001705 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001706 regmatch->startp[0]);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001707 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001708 if (add_r == OK)
1709 // if dir was BACKWARD then honor it just once
1710 *dir = FORWARD;
1711 else if (add_r == FAIL)
1712 break;
1713 // avoid expensive call to vim_regexec() when at end
1714 // of line
1715 if (*ptr == '\n' || got_int)
1716 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001717 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001718 line_breakcheck();
1719 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001720 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001721 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001722 }
1723}
1724
1725/*
1726 * Find the start of the next word.
1727 * Returns a pointer to the first char of the word. Also stops at a NUL.
1728 */
1729 char_u *
1730find_word_start(char_u *ptr)
1731{
1732 if (has_mbyte)
1733 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1734 ptr += (*mb_ptr2len)(ptr);
1735 else
1736 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1737 ++ptr;
1738 return ptr;
1739}
1740
1741/*
1742 * Find the end of the word. Assumes it starts inside a word.
1743 * Returns a pointer to just after the word.
1744 */
1745 char_u *
1746find_word_end(char_u *ptr)
1747{
1748 int start_class;
1749
1750 if (has_mbyte)
1751 {
1752 start_class = mb_get_class(ptr);
1753 if (start_class > 1)
1754 while (*ptr != NUL)
1755 {
1756 ptr += (*mb_ptr2len)(ptr);
1757 if (mb_get_class(ptr) != start_class)
1758 break;
1759 }
1760 }
1761 else
1762 while (vim_iswordc(*ptr))
1763 ++ptr;
1764 return ptr;
1765}
1766
1767/*
1768 * Find the end of the line, omitting CR and NL at the end.
1769 * Returns a pointer to just after the line.
1770 */
1771 static char_u *
1772find_line_end(char_u *ptr)
1773{
1774 char_u *s;
1775
1776 s = ptr + STRLEN(ptr);
1777 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1778 --s;
1779 return s;
1780}
1781
1782/*
1783 * Free the list of completions
1784 */
1785 static void
1786ins_compl_free(void)
1787{
1788 compl_T *match;
1789 int i;
1790
1791 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001792 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001793 VIM_CLEAR(compl_leader);
1794
1795 if (compl_first_match == NULL)
1796 return;
1797
1798 ins_compl_del_pum();
1799 pum_clear();
1800
1801 compl_curr_match = compl_first_match;
1802 do
1803 {
1804 match = compl_curr_match;
1805 compl_curr_match = compl_curr_match->cp_next;
1806 vim_free(match->cp_str);
1807 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001808 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001809 vim_free(match->cp_fname);
1810 for (i = 0; i < CPT_COUNT; ++i)
1811 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001812#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001813 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001814#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001815 vim_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001816 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001817 compl_first_match = compl_curr_match = NULL;
1818 compl_shown_match = NULL;
1819 compl_old_match = NULL;
1820}
1821
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001822/*
1823 * Reset/clear the completion state.
1824 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001825 void
1826ins_compl_clear(void)
1827{
1828 compl_cont_status = 0;
1829 compl_started = FALSE;
1830 compl_matches = 0;
1831 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02001832 compl_patternlen = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001833 VIM_CLEAR(compl_leader);
1834 edit_submode_extra = NULL;
1835 VIM_CLEAR(compl_orig_text);
1836 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001837#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001838 // clear v:completed_item
1839 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001840#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001841}
1842
1843/*
1844 * Return TRUE when Insert completion is active.
1845 */
1846 int
1847ins_compl_active(void)
1848{
1849 return compl_started;
1850}
1851
1852/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001853 * Selected one of the matches. When FALSE the match was edited or using the
1854 * longest common string.
1855 */
1856 int
1857ins_compl_used_match(void)
1858{
1859 return compl_used_match;
1860}
1861
1862/*
1863 * Initialize get longest common string.
1864 */
1865 void
1866ins_compl_init_get_longest(void)
1867{
1868 compl_get_longest = FALSE;
1869}
1870
1871/*
1872 * Returns TRUE when insert completion is interrupted.
1873 */
1874 int
1875ins_compl_interrupted(void)
1876{
1877 return compl_interrupted;
1878}
1879
1880/*
1881 * Returns TRUE if the <Enter> key selects a match in the completion popup
1882 * menu.
1883 */
1884 int
1885ins_compl_enter_selects(void)
1886{
1887 return compl_enter_selects;
1888}
1889
1890/*
1891 * Return the column where the text starts that is being completed
1892 */
1893 colnr_T
1894ins_compl_col(void)
1895{
1896 return compl_col;
1897}
1898
1899/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001900 * Return the length in bytes of the text being completed
1901 */
1902 int
1903ins_compl_len(void)
1904{
1905 return compl_length;
1906}
1907
1908/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001909 * Delete one character before the cursor and show the subset of the matches
1910 * that match the word that is now before the cursor.
1911 * Returns the character to be used, NUL if the work is done and another char
1912 * to be got from the user.
1913 */
1914 int
1915ins_compl_bs(void)
1916{
1917 char_u *line;
1918 char_u *p;
1919
1920 line = ml_get_curline();
1921 p = line + curwin->w_cursor.col;
1922 MB_PTR_BACK(line, p);
1923
1924 // Stop completion when the whole word was deleted. For Omni completion
1925 // allow the word to be deleted, we won't match everything.
1926 // Respect the 'backspace' option.
1927 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001928 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
1929 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001930 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1931 - compl_length < 0))
1932 return K_BS;
1933
1934 // Deleted more than what was used to find matches or didn't finish
1935 // finding all matches: need to look for matches all over again.
1936 if (curwin->w_cursor.col <= compl_col + compl_length
1937 || ins_compl_need_restart())
1938 ins_compl_restart();
1939
1940 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001941 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001942 if (compl_leader == NULL)
1943 return K_BS;
1944
1945 ins_compl_new_leader();
1946 if (compl_shown_match != NULL)
1947 // Make sure current match is not a hidden item.
1948 compl_curr_match = compl_shown_match;
1949 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001950}
1951
1952/*
1953 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1954 * be called.
1955 */
1956 static int
1957ins_compl_need_restart(void)
1958{
1959 // Return TRUE if we didn't complete finding matches or when the
1960 // 'completefunc' returned "always" in the "refresh" dictionary item.
1961 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001962 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001963 && compl_opt_refresh_always);
1964}
1965
1966/*
1967 * Called after changing "compl_leader".
1968 * Show the popup menu with a different set of matches.
1969 * May also search for matches again if the previous search was interrupted.
1970 */
1971 static void
1972ins_compl_new_leader(void)
1973{
1974 ins_compl_del_pum();
1975 ins_compl_delete();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001976 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001977 compl_used_match = FALSE;
1978
1979 if (compl_started)
1980 ins_compl_set_original_text(compl_leader);
1981 else
1982 {
1983#ifdef FEAT_SPELL
1984 spell_bad_len = 0; // need to redetect bad word
1985#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001986 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001987 // the popup menu display the changed text before the cursor. Set
1988 // "compl_restarting" to avoid that the first match is inserted.
1989 pum_call_update_screen();
1990#ifdef FEAT_GUI
1991 if (gui.in_use)
1992 {
1993 // Show the cursor after the match, not after the redrawn text.
1994 setcursor();
1995 out_flush_cursor(FALSE, FALSE);
1996 }
1997#endif
1998 compl_restarting = TRUE;
1999 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2000 compl_cont_status = 0;
2001 compl_restarting = FALSE;
2002 }
2003
2004 compl_enter_selects = !compl_used_match;
2005
2006 // Show the popup menu with a different set of matches.
2007 ins_compl_show_pum();
2008
2009 // Don't let Enter select the original text when there is no popup menu.
2010 if (compl_match_array == NULL)
2011 compl_enter_selects = FALSE;
2012}
2013
2014/*
2015 * Return the length of the completion, from the completion start column to
2016 * the cursor column. Making sure it never goes below zero.
2017 */
2018 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002019get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002020{
2021 int off = (int)curwin->w_cursor.col - (int)compl_col;
2022
2023 if (off < 0)
2024 return 0;
2025 return off;
2026}
2027
2028/*
2029 * Append one character to the match leader. May reduce the number of
2030 * matches.
2031 */
2032 void
2033ins_compl_addleader(int c)
2034{
2035 int cc;
2036
2037 if (stop_arrow() == FAIL)
2038 return;
2039 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2040 {
2041 char_u buf[MB_MAXBYTES + 1];
2042
2043 (*mb_char2bytes)(c, buf);
2044 buf[cc] = NUL;
2045 ins_char_bytes(buf, cc);
2046 if (compl_opt_refresh_always)
2047 AppendToRedobuff(buf);
2048 }
2049 else
2050 {
2051 ins_char(c);
2052 if (compl_opt_refresh_always)
2053 AppendCharToRedobuff(c);
2054 }
2055
2056 // If we didn't complete finding matches we must search again.
2057 if (ins_compl_need_restart())
2058 ins_compl_restart();
2059
2060 // When 'always' is set, don't reset compl_leader. While completing,
2061 // cursor doesn't point original position, changing compl_leader would
2062 // break redo.
2063 if (!compl_opt_refresh_always)
2064 {
2065 vim_free(compl_leader);
2066 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002067 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002068 if (compl_leader != NULL)
2069 ins_compl_new_leader();
2070 }
2071}
2072
2073/*
2074 * Setup for finding completions again without leaving CTRL-X mode. Used when
2075 * BS or a key was typed while still searching for matches.
2076 */
2077 static void
2078ins_compl_restart(void)
2079{
2080 ins_compl_free();
2081 compl_started = FALSE;
2082 compl_matches = 0;
2083 compl_cont_status = 0;
2084 compl_cont_mode = 0;
2085}
2086
2087/*
2088 * Set the first match, the original text.
2089 */
2090 static void
2091ins_compl_set_original_text(char_u *str)
2092{
2093 char_u *p;
2094
2095 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002096 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2097 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002098 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002099 {
2100 p = vim_strsave(str);
2101 if (p != NULL)
2102 {
2103 vim_free(compl_first_match->cp_str);
2104 compl_first_match->cp_str = p;
2105 }
2106 }
2107 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002108 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002109 {
2110 p = vim_strsave(str);
2111 if (p != NULL)
2112 {
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01002113 vim_free(compl_first_match->cp_prev->cp_str);
2114 compl_first_match->cp_prev->cp_str = p;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002115 }
2116 }
2117}
2118
2119/*
2120 * Append one character to the match leader. May reduce the number of
2121 * matches.
2122 */
2123 void
2124ins_compl_addfrommatch(void)
2125{
2126 char_u *p;
2127 int len = (int)curwin->w_cursor.col - (int)compl_col;
2128 int c;
2129 compl_T *cp;
2130
2131 p = compl_shown_match->cp_str;
2132 if ((int)STRLEN(p) <= len) // the match is too short
2133 {
2134 // When still at the original match use the first entry that matches
2135 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002136 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002137 return;
2138
2139 p = NULL;
2140 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002141 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002142 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002143 if (compl_leader == NULL
2144 || ins_compl_equal(cp, compl_leader,
2145 (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002146 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002147 p = cp->cp_str;
2148 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002149 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002150 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002151 if (p == NULL || (int)STRLEN(p) <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002152 return;
2153 }
2154 p += len;
2155 c = PTR2CHAR(p);
2156 ins_compl_addleader(c);
2157}
2158
2159/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002160 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002161 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2162 * compl_cont_mode and compl_cont_status.
2163 * Returns TRUE when the character is not to be inserted.
2164 */
2165 static int
2166set_ctrl_x_mode(int c)
2167{
2168 int retval = FALSE;
2169
2170 switch (c)
2171 {
2172 case Ctrl_E:
2173 case Ctrl_Y:
2174 // scroll the window one line up or down
2175 ctrl_x_mode = CTRL_X_SCROLL;
2176 if (!(State & REPLACE_FLAG))
2177 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2178 else
2179 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2180 edit_submode_pre = NULL;
2181 showmode();
2182 break;
2183 case Ctrl_L:
2184 // complete whole line
2185 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2186 break;
2187 case Ctrl_F:
2188 // complete filenames
2189 ctrl_x_mode = CTRL_X_FILES;
2190 break;
2191 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002192 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002193 ctrl_x_mode = CTRL_X_DICTIONARY;
2194 break;
2195 case Ctrl_R:
2196 // Register insertion without exiting CTRL-X mode
2197 // Simply allow ^R to happen without affecting ^X mode
2198 break;
2199 case Ctrl_T:
2200 // complete words from a thesaurus
2201 ctrl_x_mode = CTRL_X_THESAURUS;
2202 break;
2203#ifdef FEAT_COMPL_FUNC
2204 case Ctrl_U:
2205 // user defined completion
2206 ctrl_x_mode = CTRL_X_FUNCTION;
2207 break;
2208 case Ctrl_O:
2209 // omni completion
2210 ctrl_x_mode = CTRL_X_OMNI;
2211 break;
2212#endif
2213 case 's':
2214 case Ctrl_S:
2215 // complete spelling suggestions
2216 ctrl_x_mode = CTRL_X_SPELL;
2217#ifdef FEAT_SPELL
2218 ++emsg_off; // Avoid getting the E756 error twice.
2219 spell_back_to_badword();
2220 --emsg_off;
2221#endif
2222 break;
2223 case Ctrl_RSB:
2224 // complete tag names
2225 ctrl_x_mode = CTRL_X_TAGS;
2226 break;
2227#ifdef FEAT_FIND_ID
2228 case Ctrl_I:
2229 case K_S_TAB:
2230 // complete keywords from included files
2231 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2232 break;
2233 case Ctrl_D:
2234 // complete definitions from included files
2235 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2236 break;
2237#endif
2238 case Ctrl_V:
2239 case Ctrl_Q:
2240 // complete vim commands
2241 ctrl_x_mode = CTRL_X_CMDLINE;
2242 break;
2243 case Ctrl_Z:
2244 // stop completion
2245 ctrl_x_mode = CTRL_X_NORMAL;
2246 edit_submode = NULL;
2247 showmode();
2248 retval = TRUE;
2249 break;
2250 case Ctrl_P:
2251 case Ctrl_N:
2252 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2253 // just started ^X mode, or there were enough ^X's to cancel
2254 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2255 // do normal expansion when interrupting a different mode (say
2256 // ^X^F^X^P or ^P^X^X^P, see below)
2257 // nothing changes if interrupting mode 0, (eg, the flag
2258 // doesn't change when going to ADDING mode -- Acevedo
2259 if (!(compl_cont_status & CONT_INTRPT))
2260 compl_cont_status |= CONT_LOCAL;
2261 else if (compl_cont_mode != 0)
2262 compl_cont_status &= ~CONT_LOCAL;
2263 // FALLTHROUGH
2264 default:
2265 // If we have typed at least 2 ^X's... for modes != 0, we set
2266 // compl_cont_status = 0 (eg, as if we had just started ^X
2267 // mode).
2268 // For mode 0, we set "compl_cont_mode" to an impossible
2269 // value, in both cases ^X^X can be used to restart the same
2270 // mode (avoiding ADDING mode).
2271 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2272 // 'complete' and local ^P expansions respectively.
2273 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2274 // mode -- Acevedo
2275 if (c == Ctrl_X)
2276 {
2277 if (compl_cont_mode != 0)
2278 compl_cont_status = 0;
2279 else
2280 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2281 }
2282 ctrl_x_mode = CTRL_X_NORMAL;
2283 edit_submode = NULL;
2284 showmode();
2285 break;
2286 }
2287
2288 return retval;
2289}
2290
2291/*
2292 * Stop insert completion mode
2293 */
2294 static int
2295ins_compl_stop(int c, int prev_mode, int retval)
2296{
2297 char_u *ptr;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002298 int want_cindent;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002299
2300 // Get here when we have finished typing a sequence of ^N and
2301 // ^P or other completion characters in CTRL-X mode. Free up
2302 // memory that was used, and make sure we can redo the insert.
2303 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
2304 {
2305 // If any of the original typed text has been changed, eg when
2306 // ignorecase is set, we must add back-spaces to the redo
2307 // buffer. We add as few as necessary to delete just the part
2308 // of the original text that has changed.
2309 // When using the longest match, edited the match or used
2310 // CTRL-E then don't use the current match.
2311 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2312 ptr = compl_curr_match->cp_str;
2313 else
2314 ptr = NULL;
2315 ins_compl_fixRedoBufForLeader(ptr);
2316 }
2317
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002318 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002319
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002320 // When completing whole lines: fix indent for 'cindent'.
2321 // Otherwise, break line if it's too long.
2322 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2323 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002324 // re-indent the current line
2325 if (want_cindent)
2326 {
2327 do_c_expr_indent();
2328 want_cindent = FALSE; // don't do it again
2329 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002330 }
2331 else
2332 {
2333 int prev_col = curwin->w_cursor.col;
2334
2335 // put the cursor on the last char, for 'tw' formatting
2336 if (prev_col > 0)
2337 dec_cursor();
2338 // only format when something was inserted
2339 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2340 insertchar(NUL, 0, -1);
2341 if (prev_col > 0
2342 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2343 inc_cursor();
2344 }
2345
2346 // If the popup menu is displayed pressing CTRL-Y means accepting
2347 // the selection without inserting anything. When
2348 // compl_enter_selects is set the Enter key does the same.
2349 if ((c == Ctrl_Y || (compl_enter_selects
2350 && (c == CAR || c == K_KENTER || c == NL)))
2351 && pum_visible())
2352 retval = TRUE;
2353
2354 // CTRL-E means completion is Ended, go back to the typed text.
2355 // but only do this, if the Popup is still visible
2356 if (c == Ctrl_E)
2357 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002358 char_u *p = NULL;
2359
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002360 ins_compl_delete();
2361 if (compl_leader != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002362 p = compl_leader;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002363 else if (compl_first_match != NULL)
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002364 p = compl_orig_text;
2365 if (p != NULL)
2366 {
2367 int compl_len = get_compl_len();
2368 int len = (int)STRLEN(p);
2369
2370 if (len > compl_len)
2371 ins_bytes_len(p + compl_len, len - compl_len);
2372 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002373 retval = TRUE;
2374 }
2375
2376 auto_format(FALSE, TRUE);
2377
2378 // Trigger the CompleteDonePre event to give scripts a chance to
2379 // act upon the completion before clearing the info, and restore
2380 // ctrl_x_mode, so that complete_info() can be used.
2381 ctrl_x_mode = prev_mode;
2382 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2383
2384 ins_compl_free();
2385 compl_started = FALSE;
2386 compl_matches = 0;
2387 if (!shortmess(SHM_COMPLETIONMENU))
2388 msg_clr_cmdline(); // necessary for "noshowmode"
2389 ctrl_x_mode = CTRL_X_NORMAL;
2390 compl_enter_selects = FALSE;
2391 if (edit_submode != NULL)
2392 {
2393 edit_submode = NULL;
2394 showmode();
2395 }
2396
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002397 if (c == Ctrl_C && cmdwin_type != 0)
2398 // Avoid the popup menu remains displayed when leaving the
2399 // command line window.
2400 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002401 // Indent now if a key was typed that is in 'cinkeys'.
2402 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2403 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002404 // Trigger the CompleteDone event to give scripts a chance to act
2405 // upon the end of completion.
2406 ins_apply_autocmds(EVENT_COMPLETEDONE);
2407
2408 return retval;
2409}
2410
2411/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002412 * Prepare for Insert mode completion, or stop it.
2413 * Called just after typing a character in Insert mode.
2414 * Returns TRUE when the character is not to be inserted;
2415 */
2416 int
2417ins_compl_prep(int c)
2418{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002419 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002420 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002421
2422 // Forget any previous 'special' messages if this is actually
2423 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2424 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2425 edit_submode_extra = NULL;
2426
zeertzjq440d4cb2023-03-02 17:51:32 +00002427 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002428 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002429 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002430 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002431 return retval;
2432
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002433#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002434 // Ignore mouse events in a popup window
2435 if (is_mouse_key(c))
2436 {
2437 // Ignore drag and release events, the position does not need to be in
2438 // the popup and it may have just closed.
2439 if (c == K_LEFTRELEASE
2440 || c == K_LEFTRELEASE_NM
2441 || c == K_MIDDLERELEASE
2442 || c == K_RIGHTRELEASE
2443 || c == K_X1RELEASE
2444 || c == K_X2RELEASE
2445 || c == K_LEFTDRAG
2446 || c == K_MIDDLEDRAG
2447 || c == K_RIGHTDRAG
2448 || c == K_X1DRAG
2449 || c == K_X2DRAG)
2450 return retval;
2451 if (popup_visible)
2452 {
2453 int row = mouse_row;
2454 int col = mouse_col;
2455 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2456
2457 if (wp != NULL && WIN_IS_POPUP(wp))
2458 return retval;
2459 }
2460 }
2461#endif
2462
zeertzjqdca29d92021-08-31 19:12:51 +02002463 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2464 {
2465 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2466 || !vim_is_ctrl_x_key(c))
2467 {
2468 // Not starting another completion mode.
2469 ctrl_x_mode = CTRL_X_CMDLINE;
2470
2471 // CTRL-X CTRL-Z should stop completion without inserting anything
2472 if (c == Ctrl_Z)
2473 retval = TRUE;
2474 }
2475 else
2476 {
2477 ctrl_x_mode = CTRL_X_CMDLINE;
2478
2479 // Other CTRL-X keys first stop completion, then start another
2480 // completion mode.
2481 ins_compl_prep(' ');
2482 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2483 }
2484 }
2485
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002486 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002487 if (ctrl_x_mode_not_defined_yet()
2488 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002489 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002490 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002491 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002492 }
2493
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002494 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002495 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2496 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002497 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002498 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002499 {
2500 // We're already in CTRL-X mode, do we stay in it?
2501 if (!vim_is_ctrl_x_key(c))
2502 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002503 if (ctrl_x_mode_scroll())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002504 ctrl_x_mode = CTRL_X_NORMAL;
2505 else
2506 ctrl_x_mode = CTRL_X_FINISHED;
2507 edit_submode = NULL;
2508 }
2509 showmode();
2510 }
2511
2512 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2513 {
2514 // Show error message from attempted keyword completion (probably
2515 // 'Pattern not found') until another key is hit, then go back to
2516 // showing what mode we are in.
2517 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002518 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002519 && c != Ctrl_R && !ins_compl_pum_key(c))
2520 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002521 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002522 }
2523 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2524 // Trigger the CompleteDone event to give scripts a chance to act
2525 // upon the (possibly failed) completion.
2526 ins_apply_autocmds(EVENT_COMPLETEDONE);
2527
LemonBoy2bf52dd2022-04-09 18:17:34 +01002528 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002529
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002530 // reset continue_* if we left expansion-mode, if we stay they'll be
2531 // (re)set properly in ins_complete()
2532 if (!vim_is_ctrl_x_key(c))
2533 {
2534 compl_cont_status = 0;
2535 compl_cont_mode = 0;
2536 }
2537
2538 return retval;
2539}
2540
2541/*
2542 * Fix the redo buffer for the completion leader replacing some of the typed
2543 * text. This inserts backspaces and appends the changed text.
2544 * "ptr" is the known leader text or NUL.
2545 */
2546 static void
2547ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2548{
2549 int len;
2550 char_u *p;
2551 char_u *ptr = ptr_arg;
2552
2553 if (ptr == NULL)
2554 {
2555 if (compl_leader != NULL)
2556 ptr = compl_leader;
2557 else
2558 return; // nothing to do
2559 }
2560 if (compl_orig_text != NULL)
2561 {
2562 p = compl_orig_text;
2563 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2564 ;
2565 if (len > 0)
2566 len -= (*mb_head_off)(p, p + len);
2567 for (p += len; *p != NUL; MB_PTR_ADV(p))
2568 AppendCharToRedobuff(K_BS);
2569 }
2570 else
2571 len = 0;
2572 if (ptr != NULL)
2573 AppendToRedobuffLit(ptr + len, -1);
2574}
2575
2576/*
2577 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2578 * (depending on flag) starting from buf and looking for a non-scanned
2579 * buffer (other than curbuf). curbuf is special, if it is called with
2580 * buf=curbuf then it has to be the first call for a given flag/expansion.
2581 *
2582 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2583 */
2584 static buf_T *
2585ins_compl_next_buf(buf_T *buf, int flag)
2586{
2587 static win_T *wp = NULL;
2588
2589 if (flag == 'w') // just windows
2590 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002591 if (buf == curbuf || !win_valid(wp))
2592 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002593 wp = curwin;
2594 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2595 && wp->w_buffer->b_scanned)
2596 ;
2597 buf = wp->w_buffer;
2598 }
2599 else
2600 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2601 // (unlisted buffers)
2602 // When completing whole lines skip unloaded buffers.
2603 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2604 && ((flag == 'U'
2605 ? buf->b_p_bl
2606 : (!buf->b_p_bl
2607 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2608 || buf->b_scanned))
2609 ;
2610 return buf;
2611}
2612
2613#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002614
2615# ifdef FEAT_EVAL
2616static callback_T cfu_cb; // 'completefunc' callback function
2617static callback_T ofu_cb; // 'omnifunc' callback function
2618static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2619# endif
2620
2621/*
2622 * Copy a global callback function to a buffer local callback.
2623 */
2624 static void
2625copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2626{
2627 free_callback(bufcb);
2628 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2629 copy_callback(bufcb, globcb);
2630}
2631
2632/*
2633 * Parse the 'completefunc' option value and set the callback function.
2634 * Invoked when the 'completefunc' option is set. The option value can be a
2635 * name of a function (string), or function(<name>) or funcref(<name>) or a
2636 * lambda expression.
2637 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002638 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002639did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002640{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002641 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2642 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002643
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002644 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002645
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002646 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002647}
2648
2649/*
2650 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002651 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002652 */
2653 void
2654set_buflocal_cfu_callback(buf_T *buf UNUSED)
2655{
2656# ifdef FEAT_EVAL
2657 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2658# endif
2659}
2660
2661/*
2662 * Parse the 'omnifunc' option value and set the callback function.
2663 * Invoked when the 'omnifunc' option is set. The option value can be a
2664 * name of a function (string), or function(<name>) or funcref(<name>) or a
2665 * lambda expression.
2666 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002667 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002668did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002669{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002670 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2671 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002672
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002673 set_buflocal_ofu_callback(curbuf);
2674 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002675}
2676
2677/*
2678 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002679 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002680 */
2681 void
2682set_buflocal_ofu_callback(buf_T *buf UNUSED)
2683{
2684# ifdef FEAT_EVAL
2685 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2686# endif
2687}
2688
2689/*
2690 * Parse the 'thesaurusfunc' option value and set the callback function.
2691 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2692 * name of a function (string), or function(<name>) or funcref(<name>) or a
2693 * lambda expression.
2694 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002695 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002696did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002697{
2698 int retval;
2699
2700 if (*curbuf->b_p_tsrfu != NUL)
2701 {
2702 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002703 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2704 &curbuf->b_tsrfu_cb);
2705 }
2706 else
2707 {
2708 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002709 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2710 }
2711
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002712 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002713}
2714
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002715/*
2716 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002717 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002718 */
2719 int
2720set_ref_in_insexpand_funcs(int copyID)
2721{
2722 int abort = FALSE;
2723
2724 abort = set_ref_in_callback(&cfu_cb, copyID);
2725 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2726 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2727
2728 return abort;
2729}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002730
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002731/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002732 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002733 */
2734 static char_u *
2735get_complete_funcname(int type)
2736{
2737 switch (type)
2738 {
2739 case CTRL_X_FUNCTION:
2740 return curbuf->b_p_cfu;
2741 case CTRL_X_OMNI:
2742 return curbuf->b_p_ofu;
2743 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002744 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002745 default:
2746 return (char_u *)"";
2747 }
2748}
2749
2750/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002751 * Get the callback to use for insert mode completion.
2752 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002753 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002754get_insert_callback(int type)
2755{
2756 if (type == CTRL_X_FUNCTION)
2757 return &curbuf->b_cfu_cb;
2758 if (type == CTRL_X_OMNI)
2759 return &curbuf->b_ofu_cb;
2760 // CTRL_X_THESAURUS
2761 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2762}
2763
2764/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002765 * Execute user defined complete function 'completefunc', 'omnifunc' or
2766 * 'thesaurusfunc', and get matches in "matches".
2767 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002768 */
2769 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002770expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002771{
2772 list_T *matchlist = NULL;
2773 dict_T *matchdict = NULL;
2774 typval_T args[3];
2775 char_u *funcname;
2776 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002777 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002778 typval_T rettv;
2779 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002780 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002781
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002782 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002783 if (*funcname == NUL)
2784 return;
2785
2786 // Call 'completefunc' to obtain the list of matches.
2787 args[0].v_type = VAR_NUMBER;
2788 args[0].vval.v_number = 0;
2789 args[1].v_type = VAR_STRING;
2790 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2791 args[2].v_type = VAR_UNKNOWN;
2792
2793 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002794 // Lock the text to avoid weird things from happening. Also disallow
2795 // switching to another window, it should not be needed and may end up in
2796 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01002797 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002798
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002799 cb = get_insert_callback(type);
2800 retval = call_callback(cb, 0, &rettv, 2, args);
2801
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002802 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002803 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002804 {
2805 switch (rettv.v_type)
2806 {
2807 case VAR_LIST:
2808 matchlist = rettv.vval.v_list;
2809 break;
2810 case VAR_DICT:
2811 matchdict = rettv.vval.v_dict;
2812 break;
2813 case VAR_SPECIAL:
2814 if (rettv.vval.v_number == VVAL_NONE)
2815 compl_opt_suppress_empty = TRUE;
2816 // FALLTHROUGH
2817 default:
2818 // TODO: Give error message?
2819 clear_tv(&rettv);
2820 break;
2821 }
2822 }
zeertzjqcfe45652022-05-27 17:26:55 +01002823 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002824
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002825 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02002826 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002827 validate_cursor();
2828 if (!EQUAL_POS(curwin->w_cursor, pos))
2829 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00002830 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002831 goto theend;
2832 }
2833
2834 if (matchlist != NULL)
2835 ins_compl_add_list(matchlist);
2836 else if (matchdict != NULL)
2837 ins_compl_add_dict(matchdict);
2838
2839theend:
2840 // Restore State, it might have been changed.
2841 State = save_State;
2842
2843 if (matchdict != NULL)
2844 dict_unref(matchdict);
2845 if (matchlist != NULL)
2846 list_unref(matchlist);
2847}
2848#endif // FEAT_COMPL_FUNC
2849
2850#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02002851
2852 static inline int
2853get_user_highlight_attr(char_u *hlname)
2854{
2855 if (hlname != NULL && *hlname != NUL)
2856 return syn_name2attr(hlname);
2857 return -1;
2858}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002859/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002860 * Add a match to the list of matches from a typeval_T.
2861 * If the given string is already in the list of completions, then return
2862 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2863 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002864 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002865 */
2866 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002867ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002868{
2869 char_u *word;
2870 int dup = FALSE;
2871 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002872 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002873 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002874 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002875 int status;
zeertzjq41008522024-07-27 13:21:49 +02002876 char_u *user_hlname;
glepnir38f99a12024-08-23 18:31:06 +02002877 char_u *user_kind_hlname;
zeertzjq41008522024-07-27 13:21:49 +02002878 int user_hlattr = -1;
glepnir38f99a12024-08-23 18:31:06 +02002879 int user_kind_hlattr = -1;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002880
Bram Moolenaar08928322020-01-04 14:32:48 +01002881 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002882 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2883 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01002884 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
2885 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
2886 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
2887 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
2888 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02002889
zeertzjq41008522024-07-27 13:21:49 +02002890 user_hlname = dict_get_string(tv->vval.v_dict, "hl_group", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02002891 user_hlattr = get_user_highlight_attr(user_hlname);
2892
2893 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
2894 user_kind_hlattr = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02002895
Bram Moolenaard61efa52022-07-23 09:52:04 +01002896 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
2897 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
2898 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002899 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01002900 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
2901 dup = dict_get_number(tv->vval.v_dict, "dup");
2902 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
2903 empty = dict_get_number(tv->vval.v_dict, "empty");
2904 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
2905 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002906 flags |= CP_EQUAL;
2907 }
2908 else
2909 {
2910 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002911 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002912 }
2913 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002914 {
2915 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002916 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002917 }
glepnir508e7852024-07-25 21:39:08 +02002918 status = ins_compl_add(word, -1, NULL, cptext,
glepnir38f99a12024-08-23 18:31:06 +02002919 &user_data, dir, flags, dup, user_hlattr, user_kind_hlattr);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00002920 if (status != OK)
2921 clear_tv(&user_data);
2922 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002923}
2924
2925/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002926 * Add completions from a list.
2927 */
2928 static void
2929ins_compl_add_list(list_T *list)
2930{
2931 listitem_T *li;
2932 int dir = compl_direction;
2933
2934 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002935 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002936 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002937 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002938 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002939 // if dir was BACKWARD then honor it just once
2940 dir = FORWARD;
2941 else if (did_emsg)
2942 break;
2943 }
2944}
2945
2946/*
2947 * Add completions from a dict.
2948 */
2949 static void
2950ins_compl_add_dict(dict_T *dict)
2951{
2952 dictitem_T *di_refresh;
2953 dictitem_T *di_words;
2954
2955 // Check for optional "refresh" item.
2956 compl_opt_refresh_always = FALSE;
2957 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2958 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2959 {
2960 char_u *v = di_refresh->di_tv.vval.v_string;
2961
2962 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2963 compl_opt_refresh_always = TRUE;
2964 }
2965
2966 // Add completions from a "words" list.
2967 di_words = dict_find(dict, (char_u *)"words", 5);
2968 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2969 ins_compl_add_list(di_words->di_tv.vval.v_list);
2970}
2971
2972/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002973 * Start completion for the complete() function.
2974 * "startcol" is where the matched text starts (1 is first column).
2975 * "list" is the list of matches.
2976 */
2977 static void
2978set_completion(colnr_T startcol, list_T *list)
2979{
2980 int save_w_wrow = curwin->w_wrow;
2981 int save_w_leftcol = curwin->w_leftcol;
2982 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02002983 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02002984 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
2985 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
2986 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002987
2988 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002989 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002990 ins_compl_prep(' ');
2991 ins_compl_clear();
2992 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01002993 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002994
2995 compl_direction = FORWARD;
2996 if (startcol > curwin->w_cursor.col)
2997 startcol = curwin->w_cursor.col;
2998 compl_col = startcol;
2999 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3000 // compl_pattern doesn't need to be set
3001 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
3002 if (p_ic)
3003 flags |= CP_ICASE;
3004 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02003005 -1, NULL, NULL, NULL, 0,
glepnir38f99a12024-08-23 18:31:06 +02003006 flags | CP_FAST, FALSE, -1, -1) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003007 return;
3008
3009 ctrl_x_mode = CTRL_X_EVAL;
3010
3011 ins_compl_add_list(list);
3012 compl_matches = ins_compl_make_cyclic();
3013 compl_started = TRUE;
3014 compl_used_match = TRUE;
3015 compl_cont_status = 0;
3016
3017 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003018 int no_select = compl_no_select || compl_longest;
3019 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003020 {
3021 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003022 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003023 // Down/Up has no real effect.
3024 ins_complete(K_UP, FALSE);
3025 }
3026 else
3027 ins_complete(Ctrl_N, FALSE);
3028 compl_enter_selects = compl_no_insert;
3029
3030 // Lazily show the popup menu, unless we got interrupted.
3031 if (!compl_interrupted)
3032 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003033 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003034 out_flush();
3035}
3036
3037/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003038 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003039 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003040 void
3041f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003042{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003043 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003044
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003045 if (in_vim9script()
3046 && (check_for_number_arg(argvars, 0) == FAIL
3047 || check_for_list_arg(argvars, 1) == FAIL))
3048 return;
3049
Bram Moolenaar24959102022-05-07 20:01:16 +01003050 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003051 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003052 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003053 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003054 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003055
3056 // Check for undo allowed here, because if something was already inserted
3057 // the line was already saved for undo and this check isn't done.
3058 if (!undo_allowed())
3059 return;
3060
Bram Moolenaard83392a2022-09-01 12:22:46 +01003061 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003062 {
3063 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3064 if (startcol > 0)
3065 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003066 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003067}
3068
3069/*
3070 * "complete_add()" function
3071 */
3072 void
3073f_complete_add(typval_T *argvars, typval_T *rettv)
3074{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003075 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003076 return;
3077
Bram Moolenaar440cf092021-04-03 20:13:30 +02003078 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003079}
3080
3081/*
3082 * "complete_check()" function
3083 */
3084 void
3085f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3086{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003087 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003088 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003089
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003090 ins_compl_check_keys(0, TRUE);
3091 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003092
3093 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003094}
3095
3096/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003097 * Return Insert completion mode name string
3098 */
3099 static char_u *
3100ins_compl_mode(void)
3101{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003102 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003103 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3104
3105 return (char_u *)"";
3106}
3107
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003108/*
3109 * Assign the sequence number to all the completion matches which don't have
3110 * one assigned yet.
3111 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003112 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003113ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003114{
3115 int number = 0;
3116 compl_T *match;
3117
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003118 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003119 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003120 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003121 // This should normally succeed already at the first loop
3122 // cycle, so it's fast!
3123 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003124 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003125 if (match->cp_number != -1)
3126 {
3127 number = match->cp_number;
3128 break;
3129 }
3130 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003131 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003132 for (match = match->cp_next;
3133 match != NULL && match->cp_number == -1;
3134 match = match->cp_next)
3135 match->cp_number = ++number;
3136 }
3137 else // BACKWARD
3138 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003139 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003140 // number. This should normally succeed already at the
3141 // first loop cycle, so it's fast!
3142 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003143 && !is_first_match(match); match = match->cp_next)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003144 if (match->cp_number != -1)
3145 {
3146 number = match->cp_number;
3147 break;
3148 }
3149 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003150 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003151 for (match = match->cp_prev; match
3152 && match->cp_number == -1;
3153 match = match->cp_prev)
3154 match->cp_number = ++number;
3155 }
3156}
3157
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003158/*
3159 * Get complete information
3160 */
3161 static void
3162get_complete_info(list_T *what_list, dict_T *retdict)
3163{
3164 int ret = OK;
3165 listitem_T *item;
3166#define CI_WHAT_MODE 0x01
3167#define CI_WHAT_PUM_VISIBLE 0x02
3168#define CI_WHAT_ITEMS 0x04
3169#define CI_WHAT_SELECTED 0x08
3170#define CI_WHAT_INSERTED 0x10
3171#define CI_WHAT_ALL 0xff
3172 int what_flag;
3173
3174 if (what_list == NULL)
3175 what_flag = CI_WHAT_ALL;
3176 else
3177 {
3178 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003179 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003180 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003181 {
3182 char_u *what = tv_get_string(&item->li_tv);
3183
3184 if (STRCMP(what, "mode") == 0)
3185 what_flag |= CI_WHAT_MODE;
3186 else if (STRCMP(what, "pum_visible") == 0)
3187 what_flag |= CI_WHAT_PUM_VISIBLE;
3188 else if (STRCMP(what, "items") == 0)
3189 what_flag |= CI_WHAT_ITEMS;
3190 else if (STRCMP(what, "selected") == 0)
3191 what_flag |= CI_WHAT_SELECTED;
3192 else if (STRCMP(what, "inserted") == 0)
3193 what_flag |= CI_WHAT_INSERTED;
3194 }
3195 }
3196
3197 if (ret == OK && (what_flag & CI_WHAT_MODE))
3198 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3199
3200 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3201 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3202
Girish Palya8950bf72024-03-20 20:07:29 +01003203 if (ret == OK && (what_flag & CI_WHAT_ITEMS || what_flag & CI_WHAT_SELECTED))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003204 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003205 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003206 dict_T *di;
3207 compl_T *match;
3208 int selected_idx = -1;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003209
Girish Palya8950bf72024-03-20 20:07:29 +01003210 if (what_flag & CI_WHAT_ITEMS)
3211 {
3212 li = list_alloc();
3213 if (li == NULL)
3214 return;
3215 ret = dict_add_list(retdict, "items", li);
3216 }
3217 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3218 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3219 ins_compl_update_sequence_numbers();
3220 if (ret == OK && compl_first_match != NULL)
3221 {
3222 int list_idx = 0;
3223 match = compl_first_match;
3224 do
3225 {
3226 if (!match_at_original_text(match))
3227 {
3228 if (what_flag & CI_WHAT_ITEMS)
3229 {
3230 di = dict_alloc();
3231 if (di == NULL)
3232 return;
3233 ret = list_append_dict(li, di);
3234 if (ret != OK)
3235 return;
3236 dict_add_string(di, "word", match->cp_str);
3237 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3238 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3239 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3240 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3241 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3242 // Add an empty string for backwards compatibility
3243 dict_add_string(di, "user_data", (char_u *)"");
3244 else
3245 dict_add_tv(di, "user_data", &match->cp_user_data);
3246 }
3247 if (compl_curr_match != NULL && compl_curr_match->cp_number == match->cp_number)
3248 selected_idx = list_idx;
3249 list_idx += 1;
3250 }
3251 match = match->cp_next;
3252 }
3253 while (match != NULL && !is_first_match(match));
3254 }
3255 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3256 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003257 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003258
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003259 if (ret == OK && (what_flag & CI_WHAT_INSERTED))
3260 {
3261 // TODO
3262 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003263}
3264
3265/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003266 * "complete_info()" function
3267 */
3268 void
3269f_complete_info(typval_T *argvars, typval_T *rettv)
3270{
3271 list_T *what_list = NULL;
3272
Bram Moolenaar93a10962022-06-16 11:42:09 +01003273 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003274 return;
3275
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003276 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3277 return;
3278
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003279 if (argvars[0].v_type != VAR_UNKNOWN)
3280 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003281 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003282 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003283 what_list = argvars[0].vval.v_list;
3284 }
3285 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003286}
3287#endif
3288
3289/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003290 * Returns TRUE when using a user-defined function for thesaurus completion.
3291 */
3292 static int
3293thesaurus_func_complete(int type UNUSED)
3294{
3295#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003296 return type == CTRL_X_THESAURUS
3297 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003298#else
3299 return FALSE;
3300#endif
3301}
3302
3303/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003304 * Return value of process_next_cpt_value()
3305 */
3306enum
3307{
3308 INS_COMPL_CPT_OK = 1,
3309 INS_COMPL_CPT_CONT,
3310 INS_COMPL_CPT_END
3311};
3312
3313/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003314 * state information used for getting the next set of insert completion
3315 * matches.
3316 */
3317typedef struct
3318{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003319 char_u *e_cpt_copy; // copy of 'complete'
3320 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003321 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003322 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003323 pos_T prev_match_pos; // previous match position
3324 int set_match_pos; // save first_match_pos/last_match_pos
3325 pos_T first_match_pos; // first match position
3326 pos_T last_match_pos; // last match position
3327 int found_all; // found all matches of a certain type.
3328 char_u *dict; // dictionary file to search
3329 int dict_f; // "dict" is an exact file name or not
3330} ins_compl_next_state_T;
3331
3332/*
3333 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003334 *
3335 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003336 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003337 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003338 * st->found_all - all matches of this type are found
3339 * st->ins_buf - search for completions in this buffer
3340 * st->first_match_pos - position of the first completion match
3341 * st->last_match_pos - position of the last completion match
3342 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003343 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003344 * st->dict - name of the dictionary or thesaurus file to search
3345 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003346 *
3347 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003348 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3349 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003350 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003351 */
3352 static int
3353process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003354 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003355 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003356 pos_T *start_match_pos,
3357 int in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003358{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003359 int compl_type = -1;
3360 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003361
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003362 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003363
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003364 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3365 st->e_cpt++;
3366
3367 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003368 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003369 st->ins_buf = curbuf;
3370 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003371 // Move the cursor back one character so that ^N can match the
3372 // word immediately after the cursor.
glepnir8159fb12024-07-17 20:32:54 +02003373 if (ctrl_x_mode_normal() && (!in_fuzzy && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003374 {
3375 // Move the cursor to after the last character in the
3376 // buffer, so that word at start of buffer is found
3377 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003378 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003379 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003380 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003381 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003382 compl_type = 0;
3383
3384 // Remember the first match so that the loop stops when we
3385 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003386 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003387 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003388 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003389 && (st->ins_buf = ins_compl_next_buf(
3390 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003391 {
3392 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003393 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003394 {
3395 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003396 st->first_match_pos.col = st->last_match_pos.col = 0;
3397 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3398 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003399 compl_type = 0;
3400 }
3401 else // unloaded buffer, scan like dictionary
3402 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003403 st->found_all = TRUE;
3404 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003405 {
3406 status = INS_COMPL_CPT_CONT;
3407 goto done;
3408 }
3409 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003410 st->dict = st->ins_buf->b_fname;
3411 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003412 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003413 if (!shortmess(SHM_COMPLETIONSCAN))
3414 {
3415 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3416 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3417 st->ins_buf->b_fname == NULL
3418 ? buf_spname(st->ins_buf)
3419 : st->ins_buf->b_sfname == NULL
3420 ? st->ins_buf->b_fname
3421 : st->ins_buf->b_sfname);
3422 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3423 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003424 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003425 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003426 status = INS_COMPL_CPT_END;
3427 else
3428 {
3429 if (ctrl_x_mode_line_or_eval())
3430 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003431 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003432 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003433 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003434 compl_type = CTRL_X_DICTIONARY;
3435 else
3436 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003437 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003438 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003439 st->dict = st->e_cpt;
3440 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003441 }
3442 }
3443#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003444 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003445 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003446 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003447 compl_type = CTRL_X_PATH_DEFINES;
3448#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003449 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003450 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003451 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003452 if (!shortmess(SHM_COMPLETIONSCAN))
3453 {
3454 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3455 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3456 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3457 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003458 }
3459 else
3460 compl_type = -1;
3461
3462 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003463 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003464
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003465 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003466 if (compl_type == -1)
3467 status = INS_COMPL_CPT_CONT;
3468 }
3469
3470done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003471 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003472 return status;
3473}
3474
3475#ifdef FEAT_FIND_ID
3476/*
3477 * Get the next set of identifiers or defines matching "compl_pattern" in
3478 * included files.
3479 */
3480 static void
3481get_next_include_file_completion(int compl_type)
3482{
3483 find_pattern_in_path(compl_pattern, compl_direction,
Mike Williams16b63bd2024-06-01 11:33:40 +02003484 (int)compl_patternlen, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003485 (compl_type == CTRL_X_PATH_DEFINES
3486 && !(compl_cont_status & CONT_SOL))
3487 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003488 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003489}
3490#endif
3491
3492/*
3493 * Get the next set of words matching "compl_pattern" in dictionary or
3494 * thesaurus files.
3495 */
3496 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003497get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003498{
3499#ifdef FEAT_COMPL_FUNC
3500 if (thesaurus_func_complete(compl_type))
3501 expand_by_function(compl_type, compl_pattern);
3502 else
3503#endif
3504 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003505 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003506 : (compl_type == CTRL_X_THESAURUS
3507 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3508 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3509 compl_pattern,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003510 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003511 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003512}
3513
3514/*
3515 * Get the next set of tag names matching "compl_pattern".
3516 */
3517 static void
3518get_next_tag_completion(void)
3519{
3520 int save_p_ic;
3521 char_u **matches;
3522 int num_matches;
3523
3524 // set p_ic according to p_ic, p_scs and pat for find_tags().
3525 save_p_ic = p_ic;
3526 p_ic = ignorecase(compl_pattern);
3527
3528 // Find up to TAG_MANY matches. Avoids that an enormous number
3529 // of matches is found when compl_pattern is empty
3530 g_tag_at_cursor = TRUE;
3531 if (find_tags(compl_pattern, &num_matches, &matches,
3532 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003533 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003534 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3535 ins_compl_add_matches(num_matches, matches, p_ic);
3536 g_tag_at_cursor = FALSE;
3537 p_ic = save_p_ic;
3538}
3539
3540/*
glepnir8159fb12024-07-17 20:32:54 +02003541 * Compare function for qsort
3542 */
3543static int compare_scores(const void *a, const void *b)
3544{
3545 int idx_a = *(const int *)a;
3546 int idx_b = *(const int *)b;
3547 int score_a = compl_fuzzy_scores[idx_a];
3548 int score_b = compl_fuzzy_scores[idx_b];
3549 return (score_a > score_b) ? -1 : (score_a < score_b) ? 1 : 0;
3550}
3551
3552/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003553 * Get the next set of filename matching "compl_pattern".
3554 */
3555 static void
3556get_next_filename_completion(void)
3557{
3558 char_u **matches;
3559 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003560 char_u *ptr;
3561 garray_T fuzzy_indices;
3562 int i;
3563 int score;
3564 char_u *leader = ins_compl_leader();
Ken Takata073cb022024-07-28 17:08:15 +02003565 size_t leader_len = STRLEN(leader);
glepnir8159fb12024-07-17 20:32:54 +02003566 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3567 char_u **sorted_matches;
3568 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003569 char_u *last_sep = NULL;
3570 size_t path_with_wildcard_len;
3571 char_u *path_with_wildcard;
glepnir8159fb12024-07-17 20:32:54 +02003572
glepnirb9de1a02024-08-02 19:14:38 +02003573#ifdef BACKSLASH_IN_FILENAME
3574 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3575 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3576#else
3577 char pathsep = PATHSEP;
3578#endif
3579
glepnir8159fb12024-07-17 20:32:54 +02003580 if (in_fuzzy)
3581 {
glepnirb9de1a02024-08-02 19:14:38 +02003582#ifdef BACKSLASH_IN_FILENAME
3583 if (curbuf->b_p_csl[0] == 's')
3584 {
3585 for (i = 0; i < leader_len; i++)
3586 {
3587 if (leader[i] == '\\')
3588 leader[i] = '/';
3589 }
3590 }
3591 else if (curbuf->b_p_csl[0] == 'b')
3592 {
3593 for (i = 0; i < leader_len; i++)
3594 {
3595 if (leader[i] == '/')
3596 leader[i] = '\\';
3597 }
3598 }
3599#endif
3600 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003601 if (last_sep == NULL)
3602 {
3603 // No path separator or separator is the last character,
3604 // fuzzy match the whole leader
3605 vim_free(compl_pattern);
3606 compl_pattern = vim_strsave((char_u *)"*");
3607 compl_patternlen = STRLEN(compl_pattern);
3608 }
3609 else if (*(last_sep + 1) == '\0')
3610 in_fuzzy = FALSE;
3611 else
3612 {
3613 // Split leader into path and file parts
3614 int path_len = last_sep - leader + 1;
3615 path_with_wildcard_len = path_len + 2;
3616 path_with_wildcard = alloc(path_with_wildcard_len);
3617 if (path_with_wildcard != NULL)
3618 {
3619 vim_strncpy(path_with_wildcard, leader, path_len);
3620 vim_strcat(path_with_wildcard, (char_u *)"*", path_with_wildcard_len);
3621 vim_free(compl_pattern);
3622 compl_pattern = path_with_wildcard;
3623 compl_patternlen = STRLEN(compl_pattern);
3624
3625 // Move leader to the file part
3626 leader = last_sep + 1;
glepnir6b6280c2024-07-27 16:25:45 +02003627 leader_len = STRLEN(leader);
glepnir0be03e12024-07-19 16:45:05 +02003628 }
3629 }
glepnir8159fb12024-07-17 20:32:54 +02003630 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003631
3632 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3633 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3634 return;
3635
3636 // May change home directory back to "~".
3637 tilde_replace(compl_pattern, num_matches, matches);
3638#ifdef BACKSLASH_IN_FILENAME
3639 if (curbuf->b_p_csl[0] != NUL)
3640 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003641 for (i = 0; i < num_matches; ++i)
3642 {
glepnir8159fb12024-07-17 20:32:54 +02003643 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003644 while (*ptr != NUL)
3645 {
3646 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3647 *ptr = '/';
3648 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3649 *ptr = '\\';
3650 ptr += (*mb_ptr2len)(ptr);
3651 }
3652 }
3653 }
3654#endif
glepnir8159fb12024-07-17 20:32:54 +02003655
3656 if (in_fuzzy)
3657 {
3658 ga_init2(&fuzzy_indices, sizeof(int), 10);
3659 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3660
3661 for (i = 0; i < num_matches; i++)
3662 {
3663 ptr = matches[i];
3664 score = fuzzy_match_str(ptr, leader);
3665 if (score > 0)
3666 {
3667 if (ga_grow(&fuzzy_indices, 1) == OK)
3668 {
3669 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3670 compl_fuzzy_scores[i] = score;
3671 fuzzy_indices.ga_len++;
3672 }
3673 }
3674 }
3675
Christian Brabandt220474d2024-07-20 13:26:44 +02003676 // prevent qsort from deref NULL pointer
3677 if (fuzzy_indices.ga_len > 0)
3678 {
3679 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3680 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003681
Christian Brabandt220474d2024-07-20 13:26:44 +02003682 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3683 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3684 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003685
Christian Brabandt220474d2024-07-20 13:26:44 +02003686 FreeWild(num_matches, matches);
3687 matches = sorted_matches;
3688 num_matches = fuzzy_indices.ga_len;
3689 }
glepnir6b6280c2024-07-27 16:25:45 +02003690 else if (leader_len > 0)
3691 {
3692 FreeWild(num_matches, matches);
3693 num_matches = 0;
3694 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003695
glepnir8159fb12024-07-17 20:32:54 +02003696 vim_free(compl_fuzzy_scores);
3697 ga_clear(&fuzzy_indices);
3698 }
3699
glepnir6b6280c2024-07-27 16:25:45 +02003700 if (num_matches > 0)
3701 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003702}
3703
3704/*
3705 * Get the next set of command-line completions matching "compl_pattern".
3706 */
3707 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003708get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003709{
3710 char_u **matches;
3711 int num_matches;
3712
3713 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003714 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003715 ins_compl_add_matches(num_matches, matches, FALSE);
3716}
3717
3718/*
3719 * Get the next set of spell suggestions matching "compl_pattern".
3720 */
3721 static void
3722get_next_spell_completion(linenr_T lnum UNUSED)
3723{
3724#ifdef FEAT_SPELL
3725 char_u **matches;
3726 int num_matches;
3727
3728 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3729 if (num_matches > 0)
3730 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003731 else
3732 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003733#endif
3734}
3735
3736/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003737 * Return the next word or line from buffer "ins_buf" at position
3738 * "cur_match_pos" for completion. The length of the match is set in "len".
3739 */
3740 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003741ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003742 buf_T *ins_buf, // buffer being scanned
3743 pos_T *cur_match_pos, // current match position
3744 int *match_len,
3745 int *cont_s_ipos) // next ^X<> will set initial_pos
3746{
3747 char_u *ptr;
3748 int len;
3749
3750 *match_len = 0;
3751 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3752 cur_match_pos->col;
3753 if (ctrl_x_mode_line_or_eval())
3754 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003755 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003756 {
3757 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3758 return NULL;
3759 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3760 if (!p_paste)
3761 ptr = skipwhite(ptr);
3762 }
3763 len = (int)STRLEN(ptr);
3764 }
3765 else
3766 {
3767 char_u *tmp_ptr = ptr;
3768
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003769 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003770 {
3771 tmp_ptr += compl_length;
3772 // Skip if already inside a word.
3773 if (vim_iswordp(tmp_ptr))
3774 return NULL;
3775 // Find start of next word.
3776 tmp_ptr = find_word_start(tmp_ptr);
3777 }
3778 // Find end of this word.
3779 tmp_ptr = find_word_end(tmp_ptr);
3780 len = (int)(tmp_ptr - ptr);
3781
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003782 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003783 {
3784 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3785 {
3786 // Try next line, if any. the new word will be
3787 // "join" as if the normal command "J" was used.
3788 // IOSIZE is always greater than
3789 // compl_length, so the next STRNCPY always
3790 // works -- Acevedo
3791 STRNCPY(IObuff, ptr, len);
3792 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3793 tmp_ptr = ptr = skipwhite(ptr);
3794 // Find start of next word.
3795 tmp_ptr = find_word_start(tmp_ptr);
3796 // Find end of next word.
3797 tmp_ptr = find_word_end(tmp_ptr);
3798 if (tmp_ptr > ptr)
3799 {
3800 if (*ptr != ')' && IObuff[len - 1] != TAB)
3801 {
3802 if (IObuff[len - 1] != ' ')
3803 IObuff[len++] = ' ';
3804 // IObuf =~ "\k.* ", thus len >= 2
3805 if (p_js
3806 && (IObuff[len - 2] == '.'
3807 || (vim_strchr(p_cpo, CPO_JOINSP)
3808 == NULL
3809 && (IObuff[len - 2] == '?'
3810 || IObuff[len - 2] == '!'))))
3811 IObuff[len++] = ' ';
3812 }
3813 // copy as much as possible of the new word
3814 if (tmp_ptr - ptr >= IOSIZE - len)
3815 tmp_ptr = ptr + IOSIZE - len - 1;
3816 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3817 len += (int)(tmp_ptr - ptr);
3818 *cont_s_ipos = TRUE;
3819 }
3820 IObuff[len] = NUL;
3821 ptr = IObuff;
3822 }
3823 if (len == compl_length)
3824 return NULL;
3825 }
3826 }
3827
3828 *match_len = len;
3829 return ptr;
3830}
3831
3832/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003833 * Get the next set of words matching "compl_pattern" for default completion(s)
3834 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003835 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3836 * position "st->start_pos" in the "compl_direction" direction. If
3837 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3838 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003839 * Returns OK if a new next match is found, otherwise returns FAIL.
3840 */
3841 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003842get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003843{
3844 int found_new_match = FAIL;
3845 int save_p_scs;
3846 int save_p_ws;
3847 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003848 char_u *ptr = NULL;
3849 int len = 0;
3850 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3851 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003852
3853 // If 'infercase' is set, don't use 'smartcase' here
3854 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003855 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003856 p_scs = FALSE;
3857
3858 // Buffers other than curbuf are scanned from the beginning or the
3859 // end but never from the middle, thus setting nowrapscan in this
3860 // buffer is a good idea, on the other hand, we always set
3861 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3862 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003863 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003864 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003865 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003866 p_ws = TRUE;
3867 looped_around = FALSE;
3868 for (;;)
3869 {
3870 int cont_s_ipos = FALSE;
3871
3872 ++msg_silent; // Don't want messages for wrapscan.
3873
3874 // ctrl_x_mode_line_or_eval() || word-wise search that
3875 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003876 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003877 found_new_match = search_for_exact_line(st->ins_buf,
3878 st->cur_match_pos, compl_direction, compl_pattern);
glepnir8159fb12024-07-17 20:32:54 +02003879 else if (in_fuzzy)
3880 found_new_match = search_for_fuzzy_match(st->ins_buf,
3881 st->cur_match_pos, leader, compl_direction,
3882 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003883 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003884 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003885 NULL, compl_direction, compl_pattern, compl_patternlen,
3886 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003887 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003888 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003889 {
3890 // set "compl_started" even on fail
3891 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003892 st->first_match_pos = *st->cur_match_pos;
3893 st->last_match_pos = *st->cur_match_pos;
3894 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003895 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003896 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3897 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003898 {
3899 found_new_match = FAIL;
3900 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003901 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003902 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3903 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3904 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003905 {
3906 if (looped_around)
3907 found_new_match = FAIL;
3908 else
3909 looped_around = TRUE;
3910 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003911 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003912 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3913 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3914 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003915 {
3916 if (looped_around)
3917 found_new_match = FAIL;
3918 else
3919 looped_around = TRUE;
3920 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003921 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003922 if (found_new_match == FAIL)
3923 break;
3924
3925 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003926 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003927 && start_pos->lnum == st->cur_match_pos->lnum
3928 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003929 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003930
glepnir8159fb12024-07-17 20:32:54 +02003931 if (!in_fuzzy)
3932 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3933 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003934 if (ptr == NULL)
3935 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003936
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003937 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003938 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003939 0, cont_s_ipos) != NOTDONE)
3940 {
3941 found_new_match = OK;
3942 break;
3943 }
3944 }
3945 p_scs = save_p_scs;
3946 p_ws = save_p_ws;
3947
3948 return found_new_match;
3949}
3950
3951/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003952 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003953 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003954 */
3955 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003956get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003957{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003958 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003959
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003960 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003961 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003962 case -1:
3963 break;
3964#ifdef FEAT_FIND_ID
3965 case CTRL_X_PATH_PATTERNS:
3966 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003967 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003968 break;
3969#endif
3970
3971 case CTRL_X_DICTIONARY:
3972 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003973 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3974 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003975 break;
3976
3977 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003978 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003979 break;
3980
3981 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003982 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003983 break;
3984
3985 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003986 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003987 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003988 break;
3989
3990#ifdef FEAT_COMPL_FUNC
3991 case CTRL_X_FUNCTION:
3992 case CTRL_X_OMNI:
3993 expand_by_function(type, compl_pattern);
3994 break;
3995#endif
3996
3997 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003998 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003999 break;
4000
4001 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004002 found_new_match = get_next_default_completion(st, ini);
4003 if (found_new_match == FAIL && st->ins_buf == curbuf)
4004 st->found_all = TRUE;
4005 }
4006
4007 // check if compl_curr_match has changed, (e.g. other type of
4008 // expansion added something)
4009 if (type != 0 && compl_curr_match != compl_old_match)
4010 found_new_match = OK;
4011
4012 return found_new_match;
4013}
4014
4015/*
4016 * Get the next expansion(s), using "compl_pattern".
4017 * The search starts at position "ini" in curbuf and in the direction
4018 * compl_direction.
4019 * When "compl_started" is FALSE start at that position, otherwise continue
4020 * where we stopped searching before.
4021 * This may return before finding all the matches.
4022 * Return the total number of matches or -1 if still unknown -- Acevedo
4023 */
4024 static int
4025ins_compl_get_exp(pos_T *ini)
4026{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004027 static ins_compl_next_state_T st;
4028 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004029 int i;
4030 int found_new_match;
4031 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004032 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004033
4034 if (!compl_started)
4035 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004036 buf_T *buf;
4037
4038 FOR_ALL_BUFFERS(buf)
4039 buf->b_scanned = 0;
4040 if (!st_cleared)
4041 {
4042 CLEAR_FIELD(st);
4043 st_cleared = TRUE;
4044 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004045 st.found_all = FALSE;
4046 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004047 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004048 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004049 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4050 ? (char_u *)"." : curbuf->b_p_cpt);
4051 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004052 st.last_match_pos = st.first_match_pos = *ini;
4053 }
4054 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4055 st.ins_buf = curbuf; // In case the buffer was wiped out.
4056
4057 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004058 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004059 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004060
4061 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4062 for (;;)
4063 {
4064 found_new_match = FAIL;
4065 st.set_match_pos = FALSE;
4066
4067 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4068 // or if found_all says this entry is done. For ^X^L only use the
4069 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004070 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004071 && (!compl_started || st.found_all))
4072 {
glepnir8159fb12024-07-17 20:32:54 +02004073 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004074
4075 if (status == INS_COMPL_CPT_END)
4076 break;
4077 if (status == INS_COMPL_CPT_CONT)
4078 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004079 }
4080
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004081 // If complete() was called then compl_pattern has been reset. The
4082 // following won't work then, bail out.
4083 if (compl_pattern == NULL)
4084 break;
4085
4086 // get the next set of completion matches
4087 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004088
4089 // break the loop for specialized modes (use 'complete' just for the
4090 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4091 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004092 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4093 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004094 {
4095 if (got_int)
4096 break;
4097 // Fill the popup menu as soon as possible.
4098 if (type != -1)
4099 ins_compl_check_keys(0, FALSE);
4100
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004101 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004102 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4103 break;
4104 compl_started = TRUE;
4105 }
4106 else
4107 {
4108 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004109 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004110 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004111
4112 compl_started = FALSE;
4113 }
4114 }
4115 compl_started = TRUE;
4116
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004117 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004118 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004119 found_new_match = FAIL;
4120
4121 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004122 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004123 && !ctrl_x_mode_line_or_eval()))
4124 i = ins_compl_make_cyclic();
4125
4126 if (compl_old_match != NULL)
4127 {
4128 // If several matches were added (FORWARD) or the search failed and has
4129 // just been made cyclic then we have to move compl_curr_match to the
4130 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004131 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004132 : compl_old_match->cp_prev;
4133 if (compl_curr_match == NULL)
4134 compl_curr_match = compl_old_match;
4135 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004136 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004137
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004138 return i;
4139}
4140
4141/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004142 * Update "compl_shown_match" to the actually shown match, it may differ when
4143 * "compl_leader" is used to omit some of the matches.
4144 */
4145 static void
4146ins_compl_update_shown_match(void)
4147{
4148 while (!ins_compl_equal(compl_shown_match,
4149 compl_leader, (int)STRLEN(compl_leader))
4150 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004151 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004152 compl_shown_match = compl_shown_match->cp_next;
4153
4154 // If we didn't find it searching forward, and compl_shows_dir is
4155 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004156 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004157 && !ins_compl_equal(compl_shown_match,
4158 compl_leader, (int)STRLEN(compl_leader))
4159 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004160 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004161 {
4162 while (!ins_compl_equal(compl_shown_match,
4163 compl_leader, (int)STRLEN(compl_leader))
4164 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004165 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004166 compl_shown_match = compl_shown_match->cp_prev;
4167 }
4168}
4169
4170/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004171 * Delete the old text being completed.
4172 */
4173 void
4174ins_compl_delete(void)
4175{
4176 int col;
4177
4178 // In insert mode: Delete the typed part.
4179 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004180 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004181 if ((int)curwin->w_cursor.col > col)
4182 {
4183 if (stop_arrow() == FAIL)
4184 return;
4185 backspace_until_column(col);
4186 }
4187
4188 // TODO: is this sufficient for redrawing? Redrawing everything causes
4189 // flicker, thus we can't do that.
4190 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004191#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004192 // clear v:completed_item
4193 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004194#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004195}
4196
4197/*
4198 * Insert the new text being completed.
4199 * "in_compl_func" is TRUE when called from complete_check().
4200 */
4201 void
4202ins_compl_insert(int in_compl_func)
4203{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004204 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004205
4206 // Make sure we don't go over the end of the string, this can happen with
4207 // illegal bytes.
4208 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4209 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004210 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004211 compl_used_match = FALSE;
4212 else
4213 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004214#ifdef FEAT_EVAL
4215 {
4216 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4217
4218 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4219 }
4220#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004221 if (!in_compl_func)
4222 compl_curr_match = compl_shown_match;
4223}
4224
4225/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004226 * show the file name for the completion match (if any). Truncate the file
4227 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004228 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004229 static void
4230ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004231{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004232 char *lead = _("match in file");
4233 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4234 char_u *s;
4235 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004236
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004237 if (space <= 0)
4238 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004239
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004240 // We need the tail that fits. With double-byte encoding going
4241 // back from the end is very slow, thus go from the start and keep
4242 // the text that fits in "space" between "s" and "e".
4243 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004244 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004245 space -= ptr2cells(e);
4246 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004247 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004248 space += ptr2cells(s);
4249 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004250 }
4251 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004252 msg_hist_off = TRUE;
4253 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4254 s > compl_shown_match->cp_fname ? "<" : "", s);
4255 msg((char *)IObuff);
4256 msg_hist_off = FALSE;
4257 redraw_cmdline = FALSE; // don't overwrite!
4258}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004259
glepnirdca57fb2024-06-04 22:01:21 +02004260/*
zeertzjq551d8c32024-06-05 19:53:32 +02004261 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004262 */
glepnira218cc62024-06-03 19:32:39 +02004263 static compl_T *
4264find_comp_when_fuzzy(void)
4265{
4266 int score;
4267 char_u* str;
4268 int target_idx = -1;
4269 int is_forward = compl_shows_dir_forward();
4270 int is_backward = compl_shows_dir_backward();
4271 compl_T *comp = NULL;
4272
glepnir43eef882024-06-19 20:20:48 +02004273 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004274 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004275 return compl_first_match != compl_shown_match ? compl_first_match :
4276 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004277
4278 if (is_forward)
4279 target_idx = compl_selected_item + 1;
4280 else if (is_backward)
4281 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004282 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004283
4284 score = compl_match_array[target_idx].pum_score;
4285 str = compl_match_array[target_idx].pum_text;
4286
4287 comp = compl_first_match;
4288 do {
4289 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4290 return comp;
4291 comp = comp->cp_next;
4292 } while (comp != NULL && !is_first_match(comp));
4293
4294 return NULL;
4295}
4296
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004297/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004298 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004299 * times. The number of matches found is returned in 'num_matches'.
4300 *
4301 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4302 * get more completions. If it is FALSE, then do nothing when there are no more
4303 * completions in the given direction.
4304 *
4305 * If "advance" is TRUE, then completion will move to the first match.
4306 * Otherwise, the original text will be shown.
4307 *
4308 * Returns OK on success and -1 if the number of matches are unknown.
4309 */
4310 static int
4311find_next_completion_match(
4312 int allow_get_expansion,
4313 int todo, // repeat completion this many times
4314 int advance,
4315 int *num_matches)
4316{
4317 int found_end = FALSE;
4318 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004319 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004320 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4321 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004322
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004323 while (--todo >= 0)
4324 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004325 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004326 {
glepniraced8c22024-06-15 15:13:05 +02004327 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4328 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004329 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004330 && (is_first_match(compl_shown_match->cp_next)
4331 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004332 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004333 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004334 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004335 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004336 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004337 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4338 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004339 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004340 }
4341 else
4342 {
4343 if (!allow_get_expansion)
4344 {
4345 if (advance)
4346 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004347 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004348 compl_pending -= todo + 1;
4349 else
4350 compl_pending += todo + 1;
4351 }
4352 return -1;
4353 }
4354
4355 if (!compl_no_select && advance)
4356 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004357 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004358 --compl_pending;
4359 else
4360 ++compl_pending;
4361 }
4362
4363 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004364 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004365
4366 // handle any pending completions
4367 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004368 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004369 {
4370 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4371 {
4372 compl_shown_match = compl_shown_match->cp_next;
4373 --compl_pending;
4374 }
4375 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4376 {
4377 compl_shown_match = compl_shown_match->cp_prev;
4378 ++compl_pending;
4379 }
4380 else
4381 break;
4382 }
4383 found_end = FALSE;
4384 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004385 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004386 && compl_leader != NULL
4387 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004388 compl_leader, (int)STRLEN(compl_leader))
4389 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004390 ++todo;
4391 else
4392 // Remember a matching item.
4393 found_compl = compl_shown_match;
4394
4395 // Stop at the end of the list when we found a usable match.
4396 if (found_end)
4397 {
4398 if (found_compl != NULL)
4399 {
4400 compl_shown_match = found_compl;
4401 break;
4402 }
4403 todo = 1; // use first usable match after wrapping around
4404 }
4405 }
4406
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004407 return OK;
4408}
4409
4410/*
4411 * Fill in the next completion in the current direction.
4412 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4413 * get more completions. If it is FALSE, then we just do nothing when there
4414 * are no more completions in a given direction. The latter case is used when
4415 * we are still in the middle of finding completions, to allow browsing
4416 * through the ones found so far.
4417 * Return the total number of matches, or -1 if still unknown -- webb.
4418 *
4419 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4420 * compl_shown_match here.
4421 *
4422 * Note that this function may be called recursively once only. First with
4423 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4424 * calls this function with "allow_get_expansion" FALSE.
4425 */
4426 static int
4427ins_compl_next(
4428 int allow_get_expansion,
4429 int count, // repeat completion this many times; should
4430 // be at least 1
4431 int insert_match, // Insert the newly selected match
4432 int in_compl_func) // called from complete_check()
4433{
4434 int num_matches = -1;
4435 int todo = count;
4436 int advance;
4437 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004438 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004439 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004440 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4441 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004442
4443 // When user complete function return -1 for findstart which is next
4444 // time of 'always', compl_shown_match become NULL.
4445 if (compl_shown_match == NULL)
4446 return -1;
4447
glepnira218cc62024-06-03 19:32:39 +02004448 if (compl_leader != NULL
4449 && !match_at_original_text(compl_shown_match)
4450 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004451 // Update "compl_shown_match" to the actually shown match
4452 ins_compl_update_shown_match();
4453
4454 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004455 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004456 // Delete old text to be replaced
4457 ins_compl_delete();
4458
4459 // When finding the longest common text we stick at the original text,
4460 // don't let CTRL-N or CTRL-P move to the first match.
4461 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4462
4463 // When restarting the search don't insert the first match either.
4464 if (compl_restarting)
4465 {
4466 advance = FALSE;
4467 compl_restarting = FALSE;
4468 }
4469
4470 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4471 // around.
4472 if (find_next_completion_match(allow_get_expansion, todo, advance,
4473 &num_matches) == -1)
4474 return -1;
4475
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004476 if (curbuf != orig_curbuf)
4477 {
4478 // In case some completion function switched buffer, don't want to
4479 // insert the completion elsewhere.
4480 return -1;
4481 }
4482
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004483 // Insert the text of the new completion, or the compl_leader.
4484 if (compl_no_insert && !started)
4485 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004486 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004487 compl_used_match = FALSE;
4488 }
4489 else if (insert_match)
4490 {
4491 if (!compl_get_longest || compl_used_match)
4492 ins_compl_insert(in_compl_func);
4493 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004494 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004495 }
4496 else
4497 compl_used_match = FALSE;
4498
4499 if (!allow_get_expansion)
4500 {
4501 // may undisplay the popup menu first
4502 ins_compl_upd_pum();
4503
4504 if (pum_enough_matches())
4505 // Will display the popup menu, don't redraw yet to avoid flicker.
4506 pum_call_update_screen();
4507 else
4508 // Not showing the popup menu yet, redraw to show the user what was
4509 // inserted.
4510 update_screen(0);
4511
4512 // display the updated popup menu
4513 ins_compl_show_pum();
4514#ifdef FEAT_GUI
4515 if (gui.in_use)
4516 {
4517 // Show the cursor after the match, not after the redrawn text.
4518 setcursor();
4519 out_flush_cursor(FALSE, FALSE);
4520 }
4521#endif
4522
4523 // Delete old text to be replaced, since we're still searching and
4524 // don't want to match ourselves!
4525 ins_compl_delete();
4526 }
4527
4528 // Enter will select a match when the match wasn't inserted and the popup
4529 // menu is visible.
4530 if (compl_no_insert && !started)
4531 compl_enter_selects = TRUE;
4532 else
4533 compl_enter_selects = !insert_match && compl_match_array != NULL;
4534
4535 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004536 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004537 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004538
4539 return num_matches;
4540}
4541
4542/*
4543 * Call this while finding completions, to check whether the user has hit a key
4544 * that should change the currently displayed completion, or exit completion
4545 * mode. Also, when compl_pending is not zero, show a completion as soon as
4546 * possible. -- webb
4547 * "frequency" specifies out of how many calls we actually check.
4548 * "in_compl_func" is TRUE when called from complete_check(), don't set
4549 * compl_curr_match.
4550 */
4551 void
4552ins_compl_check_keys(int frequency, int in_compl_func)
4553{
4554 static int count = 0;
4555 int c;
4556
4557 // Don't check when reading keys from a script, :normal or feedkeys().
4558 // That would break the test scripts. But do check for keys when called
4559 // from complete_check().
4560 if (!in_compl_func && (using_script() || ex_normal_busy))
4561 return;
4562
4563 // Only do this at regular intervals
4564 if (++count < frequency)
4565 return;
4566 count = 0;
4567
4568 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4569 // can't do its work correctly.
4570 c = vpeekc_any();
4571 if (c != NUL)
4572 {
4573 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4574 {
4575 c = safe_vgetc(); // Eat the character
4576 compl_shows_dir = ins_compl_key2dir(c);
4577 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4578 c != K_UP && c != K_DOWN, in_compl_func);
4579 }
4580 else
4581 {
4582 // Need to get the character to have KeyTyped set. We'll put it
4583 // back with vungetc() below. But skip K_IGNORE.
4584 c = safe_vgetc();
4585 if (c != K_IGNORE)
4586 {
4587 // Don't interrupt completion when the character wasn't typed,
4588 // e.g., when doing @q to replay keys.
4589 if (c != Ctrl_R && KeyTyped)
4590 compl_interrupted = TRUE;
4591
4592 vungetc(c);
4593 }
4594 }
4595 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004596 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004597 {
4598 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4599
4600 compl_pending = 0;
4601 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4602 }
4603}
4604
4605/*
4606 * Decide the direction of Insert mode complete from the key typed.
4607 * Returns BACKWARD or FORWARD.
4608 */
4609 static int
4610ins_compl_key2dir(int c)
4611{
4612 if (c == Ctrl_P || c == Ctrl_L
4613 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4614 return BACKWARD;
4615 return FORWARD;
4616}
4617
4618/*
4619 * Return TRUE for keys that are used for completion only when the popup menu
4620 * is visible.
4621 */
4622 static int
4623ins_compl_pum_key(int c)
4624{
4625 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4626 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4627 || c == K_UP || c == K_DOWN);
4628}
4629
4630/*
4631 * Decide the number of completions to move forward.
4632 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4633 */
4634 static int
4635ins_compl_key2count(int c)
4636{
4637 int h;
4638
4639 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4640 {
4641 h = pum_get_height();
4642 if (h > 3)
4643 h -= 2; // keep some context
4644 return h;
4645 }
4646 return 1;
4647}
4648
4649/*
4650 * Return TRUE if completion with "c" should insert the match, FALSE if only
4651 * to change the currently selected completion.
4652 */
4653 static int
4654ins_compl_use_match(int c)
4655{
4656 switch (c)
4657 {
4658 case K_UP:
4659 case K_DOWN:
4660 case K_PAGEDOWN:
4661 case K_KPAGEDOWN:
4662 case K_S_DOWN:
4663 case K_PAGEUP:
4664 case K_KPAGEUP:
4665 case K_S_UP:
4666 return FALSE;
4667 }
4668 return TRUE;
4669}
4670
4671/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004672 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4673 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004674 * Sets the global variables: compl_col, compl_length, compl_pattern and
4675 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004676 * Uses the global variables: compl_cont_status and ctrl_x_mode
4677 */
4678 static int
4679get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4680{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004681 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004682 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004683 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004684 {
4685 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4686 ;
4687 compl_col += ++startcol;
4688 compl_length = curs_col - startcol;
4689 }
4690 if (p_ic)
4691 compl_pattern = str_foldcase(line + compl_col,
4692 compl_length, NULL, 0);
4693 else
4694 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4695 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004696 {
4697 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004698 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004699 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004700 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004701 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004702 {
4703 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004704 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004705
4706 // we need up to 2 extra chars for the prefix
4707 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004708 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004709 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004710 {
4711 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004712 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004713 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004714 if (!vim_iswordp(line + compl_col)
4715 || (compl_col > 0
4716 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004717 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004718 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004719 prefixlen = 0;
4720 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004721 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004722 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004723 line + compl_col, compl_length);
4724 }
4725 else if (--startcol < 0
4726 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4727 {
4728 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004729 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004730 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004731 {
4732 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004733 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004734 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004735 compl_col += curs_col;
4736 compl_length = 0;
4737 }
4738 else
4739 {
4740 // Search the point of change class of multibyte character
4741 // or not a word single byte character backward.
4742 if (has_mbyte)
4743 {
4744 int base_class;
4745 int head_off;
4746
4747 startcol -= (*mb_head_off)(line, line + startcol);
4748 base_class = mb_get_class(line + startcol);
4749 while (--startcol >= 0)
4750 {
4751 head_off = (*mb_head_off)(line, line + startcol);
4752 if (base_class != mb_get_class(line + startcol
4753 - head_off))
4754 break;
4755 startcol -= head_off;
4756 }
4757 }
4758 else
4759 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4760 ;
4761 compl_col += ++startcol;
4762 compl_length = (int)curs_col - startcol;
4763 if (compl_length == 1)
4764 {
4765 // Only match word with at least two chars -- webb
4766 // there's no need to call quote_meta,
4767 // alloc(7) is enough -- Acevedo
4768 compl_pattern = alloc(7);
4769 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004770 {
4771 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004772 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004773 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004774 STRCPY((char *)compl_pattern, "\\<");
4775 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4776 STRCAT((char *)compl_pattern, "\\k");
4777 }
4778 else
4779 {
4780 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4781 compl_length) + 2);
4782 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004783 {
4784 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004785 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004786 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004787 STRCPY((char *)compl_pattern, "\\<");
4788 (void)quote_meta(compl_pattern + 2, line + compl_col,
4789 compl_length);
4790 }
4791 }
4792
John Marriott8c85a2a2024-05-20 19:18:26 +02004793 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004794 return OK;
4795}
4796
4797/*
4798 * Get the pattern, column and length for whole line completion or for the
4799 * complete() function.
4800 * Sets the global variables: compl_col, compl_length and compl_pattern.
4801 */
4802 static int
4803get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4804{
4805 compl_col = (colnr_T)getwhitecols(line);
4806 compl_length = (int)curs_col - (int)compl_col;
4807 if (compl_length < 0) // cursor in indent: empty pattern
4808 compl_length = 0;
4809 if (p_ic)
4810 compl_pattern = str_foldcase(line + compl_col, compl_length,
4811 NULL, 0);
4812 else
4813 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4814 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004815 {
4816 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004817 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004818 }
4819
4820 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004821
4822 return OK;
4823}
4824
4825/*
4826 * Get the pattern, column and length for filename completion.
4827 * Sets the global variables: compl_col, compl_length and compl_pattern.
4828 */
4829 static int
4830get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4831{
4832 // Go back to just before the first filename character.
4833 if (startcol > 0)
4834 {
4835 char_u *p = line + startcol;
4836
4837 MB_PTR_BACK(line, p);
4838 while (p > line && vim_isfilec(PTR2CHAR(p)))
4839 MB_PTR_BACK(line, p);
4840 if (p == line && vim_isfilec(PTR2CHAR(p)))
4841 startcol = 0;
4842 else
4843 startcol = (int)(p - line) + 1;
4844 }
4845
4846 compl_col += startcol;
4847 compl_length = (int)curs_col - startcol;
4848 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4849 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004850 {
4851 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004852 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004853 }
4854
4855 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004856
4857 return OK;
4858}
4859
4860/*
4861 * Get the pattern, column and length for command-line completion.
4862 * Sets the global variables: compl_col, compl_length and compl_pattern.
4863 */
4864 static int
4865get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4866{
4867 compl_pattern = vim_strnsave(line, curs_col);
4868 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004869 {
4870 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004871 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004872 }
4873 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004874 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004875 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004876 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4877 || compl_xp.xp_context == EXPAND_NOTHING)
4878 // No completion possible, use an empty pattern to get a
4879 // "pattern not found" message.
4880 compl_col = curs_col;
4881 else
4882 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4883 compl_length = curs_col - compl_col;
4884
4885 return OK;
4886}
4887
4888/*
4889 * Get the pattern, column and length for user defined completion ('omnifunc',
4890 * 'completefunc' and 'thesaurusfunc')
4891 * Sets the global variables: compl_col, compl_length and compl_pattern.
4892 * Uses the global variable: spell_bad_len
4893 */
4894 static int
4895get_userdefined_compl_info(colnr_T curs_col UNUSED)
4896{
4897 int ret = FAIL;
4898
4899#ifdef FEAT_COMPL_FUNC
4900 // Call user defined function 'completefunc' with "a:findstart"
4901 // set to 1 to obtain the length of text to use for completion.
4902 char_u *line;
4903 typval_T args[3];
4904 int col;
4905 char_u *funcname;
4906 pos_T pos;
4907 int save_State = State;
4908 callback_T *cb;
4909
4910 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4911 // length as a string
4912 funcname = get_complete_funcname(ctrl_x_mode);
4913 if (*funcname == NUL)
4914 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004915 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004916 ? "completefunc" : "omnifunc");
4917 return FAIL;
4918 }
4919
4920 args[0].v_type = VAR_NUMBER;
4921 args[0].vval.v_number = 1;
4922 args[1].v_type = VAR_STRING;
4923 args[1].vval.v_string = (char_u *)"";
4924 args[2].v_type = VAR_UNKNOWN;
4925 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004926 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004927 cb = get_insert_callback(ctrl_x_mode);
4928 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004929 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004930
4931 State = save_State;
4932 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004933 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004934 validate_cursor();
4935 if (!EQUAL_POS(curwin->w_cursor, pos))
4936 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004937 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004938 return FAIL;
4939 }
4940
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004941 // Return value -2 means the user complete function wants to cancel the
4942 // complete without an error, do the same if the function did not execute
4943 // successfully.
4944 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004945 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004946 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004947 if (col == -3)
4948 {
4949 ctrl_x_mode = CTRL_X_NORMAL;
4950 edit_submode = NULL;
4951 if (!shortmess(SHM_COMPLETIONMENU))
4952 msg_clr_cmdline();
4953 return FAIL;
4954 }
4955
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004956 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004957 // completion.
4958 compl_opt_refresh_always = FALSE;
4959 compl_opt_suppress_empty = FALSE;
4960
4961 if (col < 0)
4962 col = curs_col;
4963 compl_col = col;
4964 if (compl_col > curs_col)
4965 compl_col = curs_col;
4966
4967 // Setup variables for completion. Need to obtain "line" again,
4968 // it may have become invalid.
4969 line = ml_get(curwin->w_cursor.lnum);
4970 compl_length = curs_col - compl_col;
4971 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4972 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004973 {
4974 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004975 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004976 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004977
John Marriott8c85a2a2024-05-20 19:18:26 +02004978 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004979 ret = OK;
4980#endif
4981
4982 return ret;
4983}
4984
4985/*
4986 * Get the pattern, column and length for spell completion.
4987 * Sets the global variables: compl_col, compl_length and compl_pattern.
4988 * Uses the global variable: spell_bad_len
4989 */
4990 static int
4991get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4992{
4993 int ret = FAIL;
4994#ifdef FEAT_SPELL
4995 char_u *line;
4996
4997 if (spell_bad_len > 0)
4998 compl_col = curs_col - spell_bad_len;
4999 else
5000 compl_col = spell_word_start(startcol);
5001 if (compl_col >= (colnr_T)startcol)
5002 {
5003 compl_length = 0;
5004 compl_col = curs_col;
5005 }
5006 else
5007 {
5008 spell_expand_check_cap(compl_col);
5009 compl_length = (int)curs_col - compl_col;
5010 }
5011 // Need to obtain "line" again, it may have become invalid.
5012 line = ml_get(curwin->w_cursor.lnum);
5013 compl_pattern = vim_strnsave(line + compl_col, compl_length);
5014 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005015 {
5016 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005017 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005018 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005019
John Marriott8c85a2a2024-05-20 19:18:26 +02005020 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005021 ret = OK;
5022#endif
5023
5024 return ret;
5025}
5026
5027/*
5028 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005029 * "startcol" - start column number of the completion pattern/text
5030 * "cur_col" - current cursor column
5031 * On return, "line_invalid" is set to TRUE, if the current line may have
5032 * become invalid and needs to be fetched again.
5033 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005034 */
5035 static int
5036compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5037{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005038 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005039 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5040 && !thesaurus_func_complete(ctrl_x_mode)))
5041 {
5042 return get_normal_compl_info(line, startcol, curs_col);
5043 }
5044 else if (ctrl_x_mode_line_or_eval())
5045 {
5046 return get_wholeline_compl_info(line, curs_col);
5047 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005048 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005049 {
5050 return get_filename_compl_info(line, startcol, curs_col);
5051 }
5052 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5053 {
5054 return get_cmdline_compl_info(line, curs_col);
5055 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005056 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005057 || thesaurus_func_complete(ctrl_x_mode))
5058 {
5059 if (get_userdefined_compl_info(curs_col) == FAIL)
5060 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005061 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005062 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005063 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005064 {
5065 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5066 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005067 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005068 }
5069 else
5070 {
5071 internal_error("ins_complete()");
5072 return FAIL;
5073 }
5074
5075 return OK;
5076}
5077
5078/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005079 * Continue an interrupted completion mode search in "line".
5080 *
5081 * If this same ctrl_x_mode has been interrupted use the text from
5082 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5083 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5084 * the same line as the cursor then fix it (the line has been split because it
5085 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5086 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005087 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005088 static void
5089ins_compl_continue_search(char_u *line)
5090{
5091 // it is a continued search
5092 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005093 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5094 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005095 {
5096 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5097 {
5098 // line (probably) wrapped, set compl_startpos to the
5099 // first non_blank in the line, if it is not a wordchar
5100 // include it to get a better pattern, but then we don't
5101 // want the "\\<" prefix, check it below
5102 compl_col = (colnr_T)getwhitecols(line);
5103 compl_startpos.col = compl_col;
5104 compl_startpos.lnum = curwin->w_cursor.lnum;
5105 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5106 }
5107 else
5108 {
5109 // S_IPOS was set when we inserted a word that was at the
5110 // beginning of the line, which means that we'll go to SOL
5111 // mode but first we need to redefine compl_startpos
5112 if (compl_cont_status & CONT_S_IPOS)
5113 {
5114 compl_cont_status |= CONT_SOL;
5115 compl_startpos.col = (colnr_T)(skipwhite(
5116 line + compl_length
5117 + compl_startpos.col) - line);
5118 }
5119 compl_col = compl_startpos.col;
5120 }
5121 compl_length = curwin->w_cursor.col - (int)compl_col;
5122 // IObuff is used to add a "word from the next line" would we
5123 // have enough space? just being paranoid
5124#define MIN_SPACE 75
5125 if (compl_length > (IOSIZE - MIN_SPACE))
5126 {
5127 compl_cont_status &= ~CONT_SOL;
5128 compl_length = (IOSIZE - MIN_SPACE);
5129 compl_col = curwin->w_cursor.col - compl_length;
5130 }
5131 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5132 if (compl_length < 1)
5133 compl_cont_status &= CONT_LOCAL;
5134 }
5135 else if (ctrl_x_mode_line_or_eval())
5136 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5137 else
5138 compl_cont_status = 0;
5139}
5140
5141/*
5142 * start insert mode completion
5143 */
5144 static int
5145ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005146{
5147 char_u *line;
5148 int startcol = 0; // column where searched text starts
5149 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005150 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005151 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005152 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005153
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005154 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005155
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005156 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005157 did_si = FALSE;
5158 can_si = FALSE;
5159 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005160 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005161 return FAIL;
5162
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005163 line = ml_get(curwin->w_cursor.lnum);
5164 curs_col = curwin->w_cursor.col;
5165 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005166
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005167 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5168 && compl_cont_mode == ctrl_x_mode)
5169 // this same ctrl-x_mode was interrupted previously. Continue the
5170 // completion.
5171 ins_compl_continue_search(line);
5172 else
5173 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005174
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005175 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005176 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005177 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005178 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005179 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5180 compl_cont_status = 0;
5181 compl_cont_status |= CONT_N_ADDS;
5182 compl_startpos = curwin->w_cursor;
5183 startcol = (int)curs_col;
5184 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005185 }
5186
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005187 // Work out completion pattern and original text -- webb
5188 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5189 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005190 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5191 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005192 // restore did_ai, so that adding comment leader works
5193 did_ai = save_did_ai;
5194 return FAIL;
5195 }
5196 // If "line" was changed while getting completion info get it again.
5197 if (line_invalid)
5198 line = ml_get(curwin->w_cursor.lnum);
5199
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005200 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005201 {
5202 edit_submode_pre = (char_u *)_(" Adding");
5203 if (ctrl_x_mode_line_or_eval())
5204 {
5205 // Insert a new line, keep indentation but ignore 'comments'.
5206 char_u *old = curbuf->b_p_com;
5207
5208 curbuf->b_p_com = (char_u *)"";
5209 compl_startpos.lnum = curwin->w_cursor.lnum;
5210 compl_startpos.col = compl_col;
5211 ins_eol('\r');
5212 curbuf->b_p_com = old;
5213 compl_length = 0;
5214 compl_col = curwin->w_cursor.col;
5215 }
5216 }
5217 else
5218 {
5219 edit_submode_pre = NULL;
5220 compl_startpos.col = compl_col;
5221 }
5222
5223 if (compl_cont_status & CONT_LOCAL)
5224 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5225 else
5226 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5227
5228 // If any of the original typed text has been changed we need to fix
5229 // the redo buffer.
5230 ins_compl_fixRedoBufForLeader(NULL);
5231
5232 // Always add completion for the original text.
5233 vim_free(compl_orig_text);
5234 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5235 if (p_ic)
5236 flags |= CP_ICASE;
5237 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
glepnir38f99a12024-08-23 18:31:06 +02005238 -1, NULL, NULL, NULL, 0, flags, FALSE, -1, -1) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005239 {
5240 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005241 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005242 VIM_CLEAR(compl_orig_text);
5243 return FAIL;
5244 }
5245
5246 // showmode might reset the internal line pointers, so it must
5247 // be called before line = ml_get(), or when this address is no
5248 // longer needed. -- Acevedo.
5249 edit_submode_extra = (char_u *)_("-- Searching...");
5250 edit_submode_highl = HLF_COUNT;
5251 showmode();
5252 edit_submode_extra = NULL;
5253 out_flush();
5254
5255 return OK;
5256}
5257
5258/*
5259 * display the completion status message
5260 */
5261 static void
5262ins_compl_show_statusmsg(void)
5263{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005264 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005265 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005266 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005267 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005268 ? (char_u *)_("Hit end of paragraph")
5269 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005270 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005271 }
5272
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005273 if (edit_submode_extra == NULL)
5274 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005275 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005276 {
5277 edit_submode_extra = (char_u *)_("Back at original");
5278 edit_submode_highl = HLF_W;
5279 }
5280 else if (compl_cont_status & CONT_S_IPOS)
5281 {
5282 edit_submode_extra = (char_u *)_("Word from other line");
5283 edit_submode_highl = HLF_COUNT;
5284 }
5285 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5286 {
5287 edit_submode_extra = (char_u *)_("The only match");
5288 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005289 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005290 }
5291 else
5292 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005293#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005294 // Update completion sequence number when needed.
5295 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005296 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005297#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005298 // The match should always have a sequence number now, this is
5299 // just a safety check.
5300 if (compl_curr_match->cp_number != -1)
5301 {
5302 // Space for 10 text chars. + 2x10-digit no.s = 31.
5303 // Translations may need more than twice that.
5304 static char_u match_ref[81];
5305
5306 if (compl_matches > 0)
5307 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005308 _("match %d of %d"),
5309 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005310 else
5311 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005312 _("match %d"),
5313 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005314 edit_submode_extra = match_ref;
5315 edit_submode_highl = HLF_R;
5316 if (dollar_vcol >= 0)
5317 curs_columns(FALSE);
5318 }
5319 }
5320 }
5321
5322 // Show a message about what (completion) mode we're in.
5323 if (!compl_opt_suppress_empty)
5324 {
5325 showmode();
5326 if (!shortmess(SHM_COMPLETIONMENU))
5327 {
5328 if (edit_submode_extra != NULL)
5329 {
5330 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005331 {
5332 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005333 msg_attr((char *)edit_submode_extra,
5334 edit_submode_highl < HLF_COUNT
5335 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005336 msg_hist_off = FALSE;
5337 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005338 }
5339 else
5340 msg_clr_cmdline(); // necessary for "noshowmode"
5341 }
5342 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005343}
5344
5345/*
5346 * Do Insert mode completion.
5347 * Called when character "c" was typed, which has a meaning for completion.
5348 * Returns OK if completion was done, FAIL if something failed (out of mem).
5349 */
5350 int
5351ins_complete(int c, int enable_pum)
5352{
5353 int n;
5354 int save_w_wrow;
5355 int save_w_leftcol;
5356 int insert_match;
5357
5358 compl_direction = ins_compl_key2dir(c);
5359 insert_match = ins_compl_use_match(c);
5360
5361 if (!compl_started)
5362 {
5363 if (ins_compl_start() == FAIL)
5364 return FAIL;
5365 }
5366 else if (insert_match && stop_arrow() == FAIL)
5367 return FAIL;
5368
5369 compl_shown_match = compl_curr_match;
5370 compl_shows_dir = compl_direction;
5371
5372 // Find next match (and following matches).
5373 save_w_wrow = curwin->w_wrow;
5374 save_w_leftcol = curwin->w_leftcol;
5375 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5376
5377 // may undisplay the popup menu
5378 ins_compl_upd_pum();
5379
5380 if (n > 1) // all matches have been found
5381 compl_matches = n;
5382 compl_curr_match = compl_shown_match;
5383 compl_direction = compl_shows_dir;
5384
5385 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5386 // mode.
5387 if (got_int && !global_busy)
5388 {
5389 (void)vgetc();
5390 got_int = FALSE;
5391 }
5392
5393 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005394 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005395 {
5396 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5397 // because we couldn't expand anything at first place, but if we used
5398 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5399 // (such as M in M'exico) if not tried already. -- Acevedo
5400 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005401 || compl_status_adding()
5402 || (ctrl_x_mode_not_default()
5403 && !ctrl_x_mode_path_patterns()
5404 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005405 compl_cont_status &= ~CONT_N_ADDS;
5406 }
5407
5408 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5409 compl_cont_status |= CONT_S_IPOS;
5410 else
5411 compl_cont_status &= ~CONT_S_IPOS;
5412
5413 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005414
5415 // Show the popup menu, unless we got interrupted.
5416 if (enable_pum && !compl_interrupted)
5417 show_pum(save_w_wrow, save_w_leftcol);
5418
5419 compl_was_interrupted = compl_interrupted;
5420 compl_interrupted = FALSE;
5421
5422 return OK;
5423}
5424
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005425/*
5426 * Remove (if needed) and show the popup menu
5427 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005428 static void
5429show_pum(int prev_w_wrow, int prev_w_leftcol)
5430{
5431 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005432 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005433 RedrawingDisabled = 0;
5434
5435 // If the cursor moved or the display scrolled we need to remove the pum
5436 // first.
5437 setcursor();
5438 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5439 ins_compl_del_pum();
5440
5441 ins_compl_show_pum();
5442 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005443
5444 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005445}
5446
5447/*
5448 * Looks in the first "len" chars. of "src" for search-metachars.
5449 * If dest is not NULL the chars. are copied there quoting (with
5450 * a backslash) the metachars, and dest would be NUL terminated.
5451 * Returns the length (needed) of dest
5452 */
5453 static unsigned
5454quote_meta(char_u *dest, char_u *src, int len)
5455{
5456 unsigned m = (unsigned)len + 1; // one extra for the NUL
5457
5458 for ( ; --len >= 0; src++)
5459 {
5460 switch (*src)
5461 {
5462 case '.':
5463 case '*':
5464 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005465 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005466 break;
5467 // FALLTHROUGH
5468 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005469 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005470 break;
5471 // FALLTHROUGH
5472 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005473 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005474 break;
5475 // FALLTHROUGH
5476 case '^': // currently it's not needed.
5477 case '$':
5478 m++;
5479 if (dest != NULL)
5480 *dest++ = '\\';
5481 break;
5482 }
5483 if (dest != NULL)
5484 *dest++ = *src;
5485 // Copy remaining bytes of a multibyte character.
5486 if (has_mbyte)
5487 {
5488 int i, mb_len;
5489
5490 mb_len = (*mb_ptr2len)(src) - 1;
5491 if (mb_len > 0 && len >= mb_len)
5492 for (i = 0; i < mb_len; ++i)
5493 {
5494 --len;
5495 ++src;
5496 if (dest != NULL)
5497 *dest++ = *src;
5498 }
5499 }
5500 }
5501 if (dest != NULL)
5502 *dest = NUL;
5503
5504 return m;
5505}
5506
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005507#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005508 void
5509free_insexpand_stuff(void)
5510{
5511 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005512# ifdef FEAT_EVAL
5513 free_callback(&cfu_cb);
5514 free_callback(&ofu_cb);
5515 free_callback(&tsrfu_cb);
5516# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005517}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005518#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005519
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005520#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005521/*
5522 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5523 * spelled word, if there is one.
5524 */
5525 static void
5526spell_back_to_badword(void)
5527{
5528 pos_T tpos = curwin->w_cursor;
5529
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005530 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005531 if (curwin->w_cursor.col != tpos.col)
5532 start_arrow(&tpos);
5533}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005534#endif