blob: d424fff0071a6048c0e49ace6d82c8a82fe1d67f [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];
zeertzjq58d70522024-08-31 17:05:39 +02003549 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3550 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003551}
3552
3553/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003554 * Get the next set of filename matching "compl_pattern".
3555 */
3556 static void
3557get_next_filename_completion(void)
3558{
3559 char_u **matches;
3560 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02003561 char_u *ptr;
3562 garray_T fuzzy_indices;
3563 int i;
3564 int score;
3565 char_u *leader = ins_compl_leader();
Ken Takata073cb022024-07-28 17:08:15 +02003566 size_t leader_len = STRLEN(leader);
glepnir8159fb12024-07-17 20:32:54 +02003567 int in_fuzzy = ((get_cot_flags() & COT_FUZZY) != 0 && leader_len > 0);
3568 char_u **sorted_matches;
3569 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02003570 char_u *last_sep = NULL;
3571 size_t path_with_wildcard_len;
3572 char_u *path_with_wildcard;
glepnir8159fb12024-07-17 20:32:54 +02003573
glepnirb9de1a02024-08-02 19:14:38 +02003574#ifdef BACKSLASH_IN_FILENAME
3575 char pathsep = (curbuf->b_p_csl[0] == 's') ?
3576 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
3577#else
3578 char pathsep = PATHSEP;
3579#endif
3580
glepnir8159fb12024-07-17 20:32:54 +02003581 if (in_fuzzy)
3582 {
glepnirb9de1a02024-08-02 19:14:38 +02003583#ifdef BACKSLASH_IN_FILENAME
3584 if (curbuf->b_p_csl[0] == 's')
3585 {
3586 for (i = 0; i < leader_len; i++)
3587 {
3588 if (leader[i] == '\\')
3589 leader[i] = '/';
3590 }
3591 }
3592 else if (curbuf->b_p_csl[0] == 'b')
3593 {
3594 for (i = 0; i < leader_len; i++)
3595 {
3596 if (leader[i] == '/')
3597 leader[i] = '\\';
3598 }
3599 }
3600#endif
3601 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02003602 if (last_sep == NULL)
3603 {
3604 // No path separator or separator is the last character,
3605 // fuzzy match the whole leader
3606 vim_free(compl_pattern);
3607 compl_pattern = vim_strsave((char_u *)"*");
3608 compl_patternlen = STRLEN(compl_pattern);
3609 }
3610 else if (*(last_sep + 1) == '\0')
3611 in_fuzzy = FALSE;
3612 else
3613 {
3614 // Split leader into path and file parts
3615 int path_len = last_sep - leader + 1;
3616 path_with_wildcard_len = path_len + 2;
3617 path_with_wildcard = alloc(path_with_wildcard_len);
3618 if (path_with_wildcard != NULL)
3619 {
3620 vim_strncpy(path_with_wildcard, leader, path_len);
3621 vim_strcat(path_with_wildcard, (char_u *)"*", path_with_wildcard_len);
3622 vim_free(compl_pattern);
3623 compl_pattern = path_with_wildcard;
3624 compl_patternlen = STRLEN(compl_pattern);
3625
3626 // Move leader to the file part
3627 leader = last_sep + 1;
glepnir6b6280c2024-07-27 16:25:45 +02003628 leader_len = STRLEN(leader);
glepnir0be03e12024-07-19 16:45:05 +02003629 }
3630 }
glepnir8159fb12024-07-17 20:32:54 +02003631 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003632
3633 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3634 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3635 return;
3636
3637 // May change home directory back to "~".
3638 tilde_replace(compl_pattern, num_matches, matches);
3639#ifdef BACKSLASH_IN_FILENAME
3640 if (curbuf->b_p_csl[0] != NUL)
3641 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003642 for (i = 0; i < num_matches; ++i)
3643 {
glepnir8159fb12024-07-17 20:32:54 +02003644 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003645 while (*ptr != NUL)
3646 {
3647 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3648 *ptr = '/';
3649 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3650 *ptr = '\\';
3651 ptr += (*mb_ptr2len)(ptr);
3652 }
3653 }
3654 }
3655#endif
glepnir8159fb12024-07-17 20:32:54 +02003656
3657 if (in_fuzzy)
3658 {
3659 ga_init2(&fuzzy_indices, sizeof(int), 10);
3660 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
3661
3662 for (i = 0; i < num_matches; i++)
3663 {
3664 ptr = matches[i];
3665 score = fuzzy_match_str(ptr, leader);
3666 if (score > 0)
3667 {
3668 if (ga_grow(&fuzzy_indices, 1) == OK)
3669 {
3670 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
3671 compl_fuzzy_scores[i] = score;
3672 fuzzy_indices.ga_len++;
3673 }
3674 }
3675 }
3676
Christian Brabandt220474d2024-07-20 13:26:44 +02003677 // prevent qsort from deref NULL pointer
3678 if (fuzzy_indices.ga_len > 0)
3679 {
3680 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
3681 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02003682
Christian Brabandt220474d2024-07-20 13:26:44 +02003683 sorted_matches = (char_u **)alloc(sizeof(char_u *) * fuzzy_indices.ga_len);
3684 for (i = 0; i < fuzzy_indices.ga_len; ++i)
3685 sorted_matches[i] = vim_strsave(matches[fuzzy_indices_data[i]]);
glepnir8159fb12024-07-17 20:32:54 +02003686
Christian Brabandt220474d2024-07-20 13:26:44 +02003687 FreeWild(num_matches, matches);
3688 matches = sorted_matches;
3689 num_matches = fuzzy_indices.ga_len;
3690 }
glepnir6b6280c2024-07-27 16:25:45 +02003691 else if (leader_len > 0)
3692 {
3693 FreeWild(num_matches, matches);
3694 num_matches = 0;
3695 }
Christian Brabandt220474d2024-07-20 13:26:44 +02003696
glepnir8159fb12024-07-17 20:32:54 +02003697 vim_free(compl_fuzzy_scores);
3698 ga_clear(&fuzzy_indices);
3699 }
3700
glepnir6b6280c2024-07-27 16:25:45 +02003701 if (num_matches > 0)
3702 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003703}
3704
3705/*
3706 * Get the next set of command-line completions matching "compl_pattern".
3707 */
3708 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003709get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003710{
3711 char_u **matches;
3712 int num_matches;
3713
3714 if (expand_cmdline(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02003715 (int)compl_patternlen, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003716 ins_compl_add_matches(num_matches, matches, FALSE);
3717}
3718
3719/*
3720 * Get the next set of spell suggestions matching "compl_pattern".
3721 */
3722 static void
3723get_next_spell_completion(linenr_T lnum UNUSED)
3724{
3725#ifdef FEAT_SPELL
3726 char_u **matches;
3727 int num_matches;
3728
3729 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3730 if (num_matches > 0)
3731 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003732 else
3733 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003734#endif
3735}
3736
3737/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003738 * Return the next word or line from buffer "ins_buf" at position
3739 * "cur_match_pos" for completion. The length of the match is set in "len".
3740 */
3741 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00003742ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003743 buf_T *ins_buf, // buffer being scanned
3744 pos_T *cur_match_pos, // current match position
3745 int *match_len,
3746 int *cont_s_ipos) // next ^X<> will set initial_pos
3747{
3748 char_u *ptr;
3749 int len;
3750
3751 *match_len = 0;
3752 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3753 cur_match_pos->col;
3754 if (ctrl_x_mode_line_or_eval())
3755 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003756 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003757 {
3758 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3759 return NULL;
3760 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3761 if (!p_paste)
3762 ptr = skipwhite(ptr);
3763 }
3764 len = (int)STRLEN(ptr);
3765 }
3766 else
3767 {
3768 char_u *tmp_ptr = ptr;
3769
Bram Moolenaara6f9e302022-07-28 21:51:37 +01003770 if (compl_status_adding() && compl_length <= (int)STRLEN(tmp_ptr))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003771 {
3772 tmp_ptr += compl_length;
3773 // Skip if already inside a word.
3774 if (vim_iswordp(tmp_ptr))
3775 return NULL;
3776 // Find start of next word.
3777 tmp_ptr = find_word_start(tmp_ptr);
3778 }
3779 // Find end of this word.
3780 tmp_ptr = find_word_end(tmp_ptr);
3781 len = (int)(tmp_ptr - ptr);
3782
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003783 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003784 {
3785 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3786 {
3787 // Try next line, if any. the new word will be
3788 // "join" as if the normal command "J" was used.
3789 // IOSIZE is always greater than
3790 // compl_length, so the next STRNCPY always
3791 // works -- Acevedo
3792 STRNCPY(IObuff, ptr, len);
3793 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3794 tmp_ptr = ptr = skipwhite(ptr);
3795 // Find start of next word.
3796 tmp_ptr = find_word_start(tmp_ptr);
3797 // Find end of next word.
3798 tmp_ptr = find_word_end(tmp_ptr);
3799 if (tmp_ptr > ptr)
3800 {
3801 if (*ptr != ')' && IObuff[len - 1] != TAB)
3802 {
3803 if (IObuff[len - 1] != ' ')
3804 IObuff[len++] = ' ';
3805 // IObuf =~ "\k.* ", thus len >= 2
3806 if (p_js
3807 && (IObuff[len - 2] == '.'
3808 || (vim_strchr(p_cpo, CPO_JOINSP)
3809 == NULL
3810 && (IObuff[len - 2] == '?'
3811 || IObuff[len - 2] == '!'))))
3812 IObuff[len++] = ' ';
3813 }
3814 // copy as much as possible of the new word
3815 if (tmp_ptr - ptr >= IOSIZE - len)
3816 tmp_ptr = ptr + IOSIZE - len - 1;
3817 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3818 len += (int)(tmp_ptr - ptr);
3819 *cont_s_ipos = TRUE;
3820 }
3821 IObuff[len] = NUL;
3822 ptr = IObuff;
3823 }
3824 if (len == compl_length)
3825 return NULL;
3826 }
3827 }
3828
3829 *match_len = len;
3830 return ptr;
3831}
3832
3833/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003834 * Get the next set of words matching "compl_pattern" for default completion(s)
3835 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003836 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
3837 * position "st->start_pos" in the "compl_direction" direction. If
3838 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
3839 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003840 * Returns OK if a new next match is found, otherwise returns FAIL.
3841 */
3842 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003843get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003844{
3845 int found_new_match = FAIL;
3846 int save_p_scs;
3847 int save_p_ws;
3848 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003849 char_u *ptr = NULL;
3850 int len = 0;
3851 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0 && compl_length > 0;
3852 char_u *leader = ins_compl_leader();
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003853
3854 // If 'infercase' is set, don't use 'smartcase' here
3855 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003856 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003857 p_scs = FALSE;
3858
3859 // Buffers other than curbuf are scanned from the beginning or the
3860 // end but never from the middle, thus setting nowrapscan in this
3861 // buffer is a good idea, on the other hand, we always set
3862 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3863 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003864 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003865 p_ws = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02003866 else if (*st->e_cpt == '.' && !in_fuzzy)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003867 p_ws = TRUE;
3868 looped_around = FALSE;
3869 for (;;)
3870 {
3871 int cont_s_ipos = FALSE;
3872
3873 ++msg_silent; // Don't want messages for wrapscan.
3874
3875 // ctrl_x_mode_line_or_eval() || word-wise search that
3876 // has added a word that was at the beginning of the line
glepnir8159fb12024-07-17 20:32:54 +02003877 if ((ctrl_x_mode_whole_line() && !in_fuzzy) || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003878 found_new_match = search_for_exact_line(st->ins_buf,
3879 st->cur_match_pos, compl_direction, compl_pattern);
glepnir8159fb12024-07-17 20:32:54 +02003880 else if (in_fuzzy)
3881 found_new_match = search_for_fuzzy_match(st->ins_buf,
3882 st->cur_match_pos, leader, compl_direction,
3883 start_pos, &len, &ptr, ctrl_x_mode_whole_line());
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003884 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003885 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott8c85a2a2024-05-20 19:18:26 +02003886 NULL, compl_direction, compl_pattern, compl_patternlen,
3887 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003888 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003889 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003890 {
3891 // set "compl_started" even on fail
3892 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003893 st->first_match_pos = *st->cur_match_pos;
3894 st->last_match_pos = *st->cur_match_pos;
3895 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003896 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003897 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
3898 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003899 {
3900 found_new_match = FAIL;
3901 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003902 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003903 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
3904 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3905 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003906 {
3907 if (looped_around)
3908 found_new_match = FAIL;
3909 else
3910 looped_around = TRUE;
3911 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003912 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003913 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
3914 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
3915 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003916 {
3917 if (looped_around)
3918 found_new_match = FAIL;
3919 else
3920 looped_around = TRUE;
3921 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003922 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003923 if (found_new_match == FAIL)
3924 break;
3925
3926 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003927 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003928 && start_pos->lnum == st->cur_match_pos->lnum
3929 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003930 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003931
glepnir8159fb12024-07-17 20:32:54 +02003932 if (!in_fuzzy)
3933 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
3934 &len, &cont_s_ipos);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003935 if (ptr == NULL)
3936 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003937
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003938 if (ins_compl_add_infercase(ptr, len, p_ic,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003939 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003940 0, cont_s_ipos) != NOTDONE)
3941 {
3942 found_new_match = OK;
3943 break;
3944 }
3945 }
3946 p_scs = save_p_scs;
3947 p_ws = save_p_ws;
3948
3949 return found_new_match;
3950}
3951
3952/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003953 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003954 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003955 */
3956 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003957get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003958{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003959 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003960
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003961 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003962 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003963 case -1:
3964 break;
3965#ifdef FEAT_FIND_ID
3966 case CTRL_X_PATH_PATTERNS:
3967 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003968 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003969 break;
3970#endif
3971
3972 case CTRL_X_DICTIONARY:
3973 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003974 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
3975 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003976 break;
3977
3978 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003979 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003980 break;
3981
3982 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003983 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003984 break;
3985
3986 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003987 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003988 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003989 break;
3990
3991#ifdef FEAT_COMPL_FUNC
3992 case CTRL_X_FUNCTION:
3993 case CTRL_X_OMNI:
3994 expand_by_function(type, compl_pattern);
3995 break;
3996#endif
3997
3998 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003999 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004000 break;
4001
4002 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004003 found_new_match = get_next_default_completion(st, ini);
4004 if (found_new_match == FAIL && st->ins_buf == curbuf)
4005 st->found_all = TRUE;
4006 }
4007
4008 // check if compl_curr_match has changed, (e.g. other type of
4009 // expansion added something)
4010 if (type != 0 && compl_curr_match != compl_old_match)
4011 found_new_match = OK;
4012
4013 return found_new_match;
4014}
4015
4016/*
4017 * Get the next expansion(s), using "compl_pattern".
4018 * The search starts at position "ini" in curbuf and in the direction
4019 * compl_direction.
4020 * When "compl_started" is FALSE start at that position, otherwise continue
4021 * where we stopped searching before.
4022 * This may return before finding all the matches.
4023 * Return the total number of matches or -1 if still unknown -- Acevedo
4024 */
4025 static int
4026ins_compl_get_exp(pos_T *ini)
4027{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004028 static ins_compl_next_state_T st;
4029 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004030 int i;
4031 int found_new_match;
4032 int type = ctrl_x_mode;
glepnir8159fb12024-07-17 20:32:54 +02004033 int in_fuzzy = (get_cot_flags() & COT_FUZZY) != 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004034
4035 if (!compl_started)
4036 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004037 buf_T *buf;
4038
4039 FOR_ALL_BUFFERS(buf)
4040 buf->b_scanned = 0;
4041 if (!st_cleared)
4042 {
4043 CLEAR_FIELD(st);
4044 st_cleared = TRUE;
4045 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004046 st.found_all = FALSE;
4047 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004048 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004049 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004050 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4051 ? (char_u *)"." : curbuf->b_p_cpt);
4052 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004053 st.last_match_pos = st.first_match_pos = *ini;
4054 }
4055 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4056 st.ins_buf = curbuf; // In case the buffer was wiped out.
4057
4058 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004059 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004060 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004061
4062 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
4063 for (;;)
4064 {
4065 found_new_match = FAIL;
4066 st.set_match_pos = FALSE;
4067
4068 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4069 // or if found_all says this entry is done. For ^X^L only use the
4070 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004071 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004072 && (!compl_started || st.found_all))
4073 {
glepnir8159fb12024-07-17 20:32:54 +02004074 int status = process_next_cpt_value(&st, &type, ini, in_fuzzy);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004075
4076 if (status == INS_COMPL_CPT_END)
4077 break;
4078 if (status == INS_COMPL_CPT_CONT)
4079 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004080 }
4081
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004082 // If complete() was called then compl_pattern has been reset. The
4083 // following won't work then, bail out.
4084 if (compl_pattern == NULL)
4085 break;
4086
4087 // get the next set of completion matches
4088 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004089
4090 // break the loop for specialized modes (use 'complete' just for the
4091 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4092 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004093 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4094 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004095 {
4096 if (got_int)
4097 break;
4098 // Fill the popup menu as soon as possible.
4099 if (type != -1)
4100 ins_compl_check_keys(0, FALSE);
4101
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004102 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004103 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4104 break;
4105 compl_started = TRUE;
4106 }
4107 else
4108 {
4109 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004110 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004111 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004112
4113 compl_started = FALSE;
4114 }
4115 }
4116 compl_started = TRUE;
4117
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004118 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004119 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004120 found_new_match = FAIL;
4121
4122 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004123 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004124 && !ctrl_x_mode_line_or_eval()))
4125 i = ins_compl_make_cyclic();
4126
4127 if (compl_old_match != NULL)
4128 {
4129 // If several matches were added (FORWARD) or the search failed and has
4130 // just been made cyclic then we have to move compl_curr_match to the
4131 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004132 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004133 : compl_old_match->cp_prev;
4134 if (compl_curr_match == NULL)
4135 compl_curr_match = compl_old_match;
4136 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004137 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004138
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004139 return i;
4140}
4141
4142/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004143 * Update "compl_shown_match" to the actually shown match, it may differ when
4144 * "compl_leader" is used to omit some of the matches.
4145 */
4146 static void
4147ins_compl_update_shown_match(void)
4148{
4149 while (!ins_compl_equal(compl_shown_match,
4150 compl_leader, (int)STRLEN(compl_leader))
4151 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004152 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004153 compl_shown_match = compl_shown_match->cp_next;
4154
4155 // If we didn't find it searching forward, and compl_shows_dir is
4156 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004157 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004158 && !ins_compl_equal(compl_shown_match,
4159 compl_leader, (int)STRLEN(compl_leader))
4160 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004161 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004162 {
4163 while (!ins_compl_equal(compl_shown_match,
4164 compl_leader, (int)STRLEN(compl_leader))
4165 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004166 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004167 compl_shown_match = compl_shown_match->cp_prev;
4168 }
4169}
4170
4171/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004172 * Delete the old text being completed.
4173 */
4174 void
4175ins_compl_delete(void)
4176{
4177 int col;
4178
4179 // In insert mode: Delete the typed part.
4180 // In replace mode: Put the old characters back, if any.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004181 col = compl_col + (compl_status_adding() ? compl_length : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004182 if ((int)curwin->w_cursor.col > col)
4183 {
4184 if (stop_arrow() == FAIL)
4185 return;
4186 backspace_until_column(col);
4187 }
4188
4189 // TODO: is this sufficient for redrawing? Redrawing everything causes
4190 // flicker, thus we can't do that.
4191 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004192#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004193 // clear v:completed_item
4194 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004195#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004196}
4197
4198/*
4199 * Insert the new text being completed.
4200 * "in_compl_func" is TRUE when called from complete_check().
4201 */
4202 void
4203ins_compl_insert(int in_compl_func)
4204{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004205 int compl_len = get_compl_len();
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004206
4207 // Make sure we don't go over the end of the string, this can happen with
4208 // illegal bytes.
4209 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
4210 ins_bytes(compl_shown_match->cp_str + compl_len);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004211 if (match_at_original_text(compl_shown_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004212 compl_used_match = FALSE;
4213 else
4214 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004215#ifdef FEAT_EVAL
4216 {
4217 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4218
4219 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4220 }
4221#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004222 if (!in_compl_func)
4223 compl_curr_match = compl_shown_match;
4224}
4225
4226/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004227 * show the file name for the completion match (if any). Truncate the file
4228 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004229 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004230 static void
4231ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004232{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004233 char *lead = _("match in file");
4234 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4235 char_u *s;
4236 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004237
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004238 if (space <= 0)
4239 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004240
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004241 // We need the tail that fits. With double-byte encoding going
4242 // back from the end is very slow, thus go from the start and keep
4243 // the text that fits in "space" between "s" and "e".
4244 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004245 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004246 space -= ptr2cells(e);
4247 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004248 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004249 space += ptr2cells(s);
4250 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004251 }
4252 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004253 msg_hist_off = TRUE;
4254 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4255 s > compl_shown_match->cp_fname ? "<" : "", s);
4256 msg((char *)IObuff);
4257 msg_hist_off = FALSE;
4258 redraw_cmdline = FALSE; // don't overwrite!
4259}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004260
glepnirdca57fb2024-06-04 22:01:21 +02004261/*
zeertzjq551d8c32024-06-05 19:53:32 +02004262 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004263 */
glepnira218cc62024-06-03 19:32:39 +02004264 static compl_T *
4265find_comp_when_fuzzy(void)
4266{
4267 int score;
4268 char_u* str;
4269 int target_idx = -1;
4270 int is_forward = compl_shows_dir_forward();
4271 int is_backward = compl_shows_dir_backward();
4272 compl_T *comp = NULL;
4273
glepnir43eef882024-06-19 20:20:48 +02004274 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004275 || (is_backward && compl_selected_item == 0))
glepnir65407ce2024-07-06 16:09:19 +02004276 return compl_first_match != compl_shown_match ? compl_first_match :
4277 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004278
4279 if (is_forward)
4280 target_idx = compl_selected_item + 1;
4281 else if (is_backward)
4282 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004283 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004284
4285 score = compl_match_array[target_idx].pum_score;
4286 str = compl_match_array[target_idx].pum_text;
4287
4288 comp = compl_first_match;
4289 do {
4290 if (comp->cp_score == score && (str == comp->cp_str || str == comp->cp_text[CPT_ABBR]))
4291 return comp;
4292 comp = comp->cp_next;
4293 } while (comp != NULL && !is_first_match(comp));
4294
4295 return NULL;
4296}
4297
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004298/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004299 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004300 * times. The number of matches found is returned in 'num_matches'.
4301 *
4302 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4303 * get more completions. If it is FALSE, then do nothing when there are no more
4304 * completions in the given direction.
4305 *
4306 * If "advance" is TRUE, then completion will move to the first match.
4307 * Otherwise, the original text will be shown.
4308 *
4309 * Returns OK on success and -1 if the number of matches are unknown.
4310 */
4311 static int
4312find_next_completion_match(
4313 int allow_get_expansion,
4314 int todo, // repeat completion this many times
4315 int advance,
4316 int *num_matches)
4317{
4318 int found_end = FALSE;
4319 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004320 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004321 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4322 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004323
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004324 while (--todo >= 0)
4325 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004326 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004327 {
glepniraced8c22024-06-15 15:13:05 +02004328 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4329 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004330 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004331 && (is_first_match(compl_shown_match->cp_next)
4332 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004333 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004334 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004335 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004336 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004337 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004338 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4339 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004340 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004341 }
4342 else
4343 {
4344 if (!allow_get_expansion)
4345 {
4346 if (advance)
4347 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004348 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004349 compl_pending -= todo + 1;
4350 else
4351 compl_pending += todo + 1;
4352 }
4353 return -1;
4354 }
4355
4356 if (!compl_no_select && advance)
4357 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004358 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004359 --compl_pending;
4360 else
4361 ++compl_pending;
4362 }
4363
4364 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004365 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004366
4367 // handle any pending completions
4368 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004369 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004370 {
4371 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
4372 {
4373 compl_shown_match = compl_shown_match->cp_next;
4374 --compl_pending;
4375 }
4376 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
4377 {
4378 compl_shown_match = compl_shown_match->cp_prev;
4379 ++compl_pending;
4380 }
4381 else
4382 break;
4383 }
4384 found_end = FALSE;
4385 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004386 if (!match_at_original_text(compl_shown_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004387 && compl_leader != NULL
4388 && !ins_compl_equal(compl_shown_match,
glepnira218cc62024-06-03 19:32:39 +02004389 compl_leader, (int)STRLEN(compl_leader))
4390 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004391 ++todo;
4392 else
4393 // Remember a matching item.
4394 found_compl = compl_shown_match;
4395
4396 // Stop at the end of the list when we found a usable match.
4397 if (found_end)
4398 {
4399 if (found_compl != NULL)
4400 {
4401 compl_shown_match = found_compl;
4402 break;
4403 }
4404 todo = 1; // use first usable match after wrapping around
4405 }
4406 }
4407
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004408 return OK;
4409}
4410
4411/*
4412 * Fill in the next completion in the current direction.
4413 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
4414 * get more completions. If it is FALSE, then we just do nothing when there
4415 * are no more completions in a given direction. The latter case is used when
4416 * we are still in the middle of finding completions, to allow browsing
4417 * through the ones found so far.
4418 * Return the total number of matches, or -1 if still unknown -- webb.
4419 *
4420 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
4421 * compl_shown_match here.
4422 *
4423 * Note that this function may be called recursively once only. First with
4424 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
4425 * calls this function with "allow_get_expansion" FALSE.
4426 */
4427 static int
4428ins_compl_next(
4429 int allow_get_expansion,
4430 int count, // repeat completion this many times; should
4431 // be at least 1
4432 int insert_match, // Insert the newly selected match
4433 int in_compl_func) // called from complete_check()
4434{
4435 int num_matches = -1;
4436 int todo = count;
4437 int advance;
4438 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004439 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02004440 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004441 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
4442 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004443
4444 // When user complete function return -1 for findstart which is next
4445 // time of 'always', compl_shown_match become NULL.
4446 if (compl_shown_match == NULL)
4447 return -1;
4448
glepnira218cc62024-06-03 19:32:39 +02004449 if (compl_leader != NULL
4450 && !match_at_original_text(compl_shown_match)
4451 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004452 // Update "compl_shown_match" to the actually shown match
4453 ins_compl_update_shown_match();
4454
4455 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02004456 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004457 // Delete old text to be replaced
4458 ins_compl_delete();
4459
4460 // When finding the longest common text we stick at the original text,
4461 // don't let CTRL-N or CTRL-P move to the first match.
4462 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
4463
4464 // When restarting the search don't insert the first match either.
4465 if (compl_restarting)
4466 {
4467 advance = FALSE;
4468 compl_restarting = FALSE;
4469 }
4470
4471 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
4472 // around.
4473 if (find_next_completion_match(allow_get_expansion, todo, advance,
4474 &num_matches) == -1)
4475 return -1;
4476
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004477 if (curbuf != orig_curbuf)
4478 {
4479 // In case some completion function switched buffer, don't want to
4480 // insert the completion elsewhere.
4481 return -1;
4482 }
4483
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004484 // Insert the text of the new completion, or the compl_leader.
4485 if (compl_no_insert && !started)
4486 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004487 ins_bytes(compl_orig_text + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004488 compl_used_match = FALSE;
4489 }
4490 else if (insert_match)
4491 {
4492 if (!compl_get_longest || compl_used_match)
4493 ins_compl_insert(in_compl_func);
4494 else
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004495 ins_bytes(compl_leader + get_compl_len());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004496 }
4497 else
4498 compl_used_match = FALSE;
4499
4500 if (!allow_get_expansion)
4501 {
4502 // may undisplay the popup menu first
4503 ins_compl_upd_pum();
4504
4505 if (pum_enough_matches())
4506 // Will display the popup menu, don't redraw yet to avoid flicker.
4507 pum_call_update_screen();
4508 else
4509 // Not showing the popup menu yet, redraw to show the user what was
4510 // inserted.
4511 update_screen(0);
4512
4513 // display the updated popup menu
4514 ins_compl_show_pum();
4515#ifdef FEAT_GUI
4516 if (gui.in_use)
4517 {
4518 // Show the cursor after the match, not after the redrawn text.
4519 setcursor();
4520 out_flush_cursor(FALSE, FALSE);
4521 }
4522#endif
4523
4524 // Delete old text to be replaced, since we're still searching and
4525 // don't want to match ourselves!
4526 ins_compl_delete();
4527 }
4528
4529 // Enter will select a match when the match wasn't inserted and the popup
4530 // menu is visible.
4531 if (compl_no_insert && !started)
4532 compl_enter_selects = TRUE;
4533 else
4534 compl_enter_selects = !insert_match && compl_match_array != NULL;
4535
4536 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004537 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004538 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004539
4540 return num_matches;
4541}
4542
4543/*
4544 * Call this while finding completions, to check whether the user has hit a key
4545 * that should change the currently displayed completion, or exit completion
4546 * mode. Also, when compl_pending is not zero, show a completion as soon as
4547 * possible. -- webb
4548 * "frequency" specifies out of how many calls we actually check.
4549 * "in_compl_func" is TRUE when called from complete_check(), don't set
4550 * compl_curr_match.
4551 */
4552 void
4553ins_compl_check_keys(int frequency, int in_compl_func)
4554{
4555 static int count = 0;
4556 int c;
4557
4558 // Don't check when reading keys from a script, :normal or feedkeys().
4559 // That would break the test scripts. But do check for keys when called
4560 // from complete_check().
4561 if (!in_compl_func && (using_script() || ex_normal_busy))
4562 return;
4563
4564 // Only do this at regular intervals
4565 if (++count < frequency)
4566 return;
4567 count = 0;
4568
4569 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4570 // can't do its work correctly.
4571 c = vpeekc_any();
4572 if (c != NUL)
4573 {
4574 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4575 {
4576 c = safe_vgetc(); // Eat the character
4577 compl_shows_dir = ins_compl_key2dir(c);
4578 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4579 c != K_UP && c != K_DOWN, in_compl_func);
4580 }
4581 else
4582 {
4583 // Need to get the character to have KeyTyped set. We'll put it
4584 // back with vungetc() below. But skip K_IGNORE.
4585 c = safe_vgetc();
4586 if (c != K_IGNORE)
4587 {
4588 // Don't interrupt completion when the character wasn't typed,
4589 // e.g., when doing @q to replay keys.
4590 if (c != Ctrl_R && KeyTyped)
4591 compl_interrupted = TRUE;
4592
4593 vungetc(c);
4594 }
4595 }
4596 }
zeertzjq529b9ad2024-06-05 20:27:06 +02004597 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004598 {
4599 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4600
4601 compl_pending = 0;
4602 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4603 }
4604}
4605
4606/*
4607 * Decide the direction of Insert mode complete from the key typed.
4608 * Returns BACKWARD or FORWARD.
4609 */
4610 static int
4611ins_compl_key2dir(int c)
4612{
4613 if (c == Ctrl_P || c == Ctrl_L
4614 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4615 return BACKWARD;
4616 return FORWARD;
4617}
4618
4619/*
4620 * Return TRUE for keys that are used for completion only when the popup menu
4621 * is visible.
4622 */
4623 static int
4624ins_compl_pum_key(int c)
4625{
4626 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4627 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4628 || c == K_UP || c == K_DOWN);
4629}
4630
4631/*
4632 * Decide the number of completions to move forward.
4633 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4634 */
4635 static int
4636ins_compl_key2count(int c)
4637{
4638 int h;
4639
4640 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4641 {
4642 h = pum_get_height();
4643 if (h > 3)
4644 h -= 2; // keep some context
4645 return h;
4646 }
4647 return 1;
4648}
4649
4650/*
4651 * Return TRUE if completion with "c" should insert the match, FALSE if only
4652 * to change the currently selected completion.
4653 */
4654 static int
4655ins_compl_use_match(int c)
4656{
4657 switch (c)
4658 {
4659 case K_UP:
4660 case K_DOWN:
4661 case K_PAGEDOWN:
4662 case K_KPAGEDOWN:
4663 case K_S_DOWN:
4664 case K_PAGEUP:
4665 case K_KPAGEUP:
4666 case K_S_UP:
4667 return FALSE;
4668 }
4669 return TRUE;
4670}
4671
4672/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004673 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4674 * completion)
John Marriott8c85a2a2024-05-20 19:18:26 +02004675 * Sets the global variables: compl_col, compl_length, compl_pattern and
4676 * compl_patternlen.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004677 * Uses the global variables: compl_cont_status and ctrl_x_mode
4678 */
4679 static int
4680get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4681{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004682 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004683 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004684 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004685 {
4686 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4687 ;
4688 compl_col += ++startcol;
4689 compl_length = curs_col - startcol;
4690 }
4691 if (p_ic)
4692 compl_pattern = str_foldcase(line + compl_col,
4693 compl_length, NULL, 0);
4694 else
4695 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4696 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004697 {
4698 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004699 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004700 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004701 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004702 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004703 {
4704 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02004705 size_t prefixlen = STRLEN_LITERAL("\\<");
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004706
4707 // we need up to 2 extra chars for the prefix
4708 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
John Marriott8c85a2a2024-05-20 19:18:26 +02004709 compl_length) + prefixlen);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004710 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004711 {
4712 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004713 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004714 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004715 if (!vim_iswordp(line + compl_col)
4716 || (compl_col > 0
4717 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02004718 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004719 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02004720 prefixlen = 0;
4721 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004722 STRCPY((char *)compl_pattern, prefix);
John Marriott8c85a2a2024-05-20 19:18:26 +02004723 (void)quote_meta(compl_pattern + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004724 line + compl_col, compl_length);
4725 }
4726 else if (--startcol < 0
4727 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4728 {
4729 // Match any word of at least two chars
John Marriott8c85a2a2024-05-20 19:18:26 +02004730 compl_pattern = vim_strnsave((char_u *)"\\<\\k\\k", STRLEN_LITERAL("\\<\\k\\k"));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004731 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004732 {
4733 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004734 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004735 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004736 compl_col += curs_col;
4737 compl_length = 0;
4738 }
4739 else
4740 {
4741 // Search the point of change class of multibyte character
4742 // or not a word single byte character backward.
4743 if (has_mbyte)
4744 {
4745 int base_class;
4746 int head_off;
4747
4748 startcol -= (*mb_head_off)(line, line + startcol);
4749 base_class = mb_get_class(line + startcol);
4750 while (--startcol >= 0)
4751 {
4752 head_off = (*mb_head_off)(line, line + startcol);
4753 if (base_class != mb_get_class(line + startcol
4754 - head_off))
4755 break;
4756 startcol -= head_off;
4757 }
4758 }
4759 else
4760 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4761 ;
4762 compl_col += ++startcol;
4763 compl_length = (int)curs_col - startcol;
4764 if (compl_length == 1)
4765 {
4766 // Only match word with at least two chars -- webb
4767 // there's no need to call quote_meta,
4768 // alloc(7) is enough -- Acevedo
4769 compl_pattern = alloc(7);
4770 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004771 {
4772 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004773 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004774 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004775 STRCPY((char *)compl_pattern, "\\<");
4776 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4777 STRCAT((char *)compl_pattern, "\\k");
4778 }
4779 else
4780 {
4781 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4782 compl_length) + 2);
4783 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004784 {
4785 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004786 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004787 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004788 STRCPY((char *)compl_pattern, "\\<");
4789 (void)quote_meta(compl_pattern + 2, line + compl_col,
4790 compl_length);
4791 }
4792 }
4793
John Marriott8c85a2a2024-05-20 19:18:26 +02004794 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004795 return OK;
4796}
4797
4798/*
4799 * Get the pattern, column and length for whole line completion or for the
4800 * complete() function.
4801 * Sets the global variables: compl_col, compl_length and compl_pattern.
4802 */
4803 static int
4804get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4805{
4806 compl_col = (colnr_T)getwhitecols(line);
4807 compl_length = (int)curs_col - (int)compl_col;
4808 if (compl_length < 0) // cursor in indent: empty pattern
4809 compl_length = 0;
4810 if (p_ic)
4811 compl_pattern = str_foldcase(line + compl_col, compl_length,
4812 NULL, 0);
4813 else
4814 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4815 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004816 {
4817 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004818 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004819 }
4820
4821 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004822
4823 return OK;
4824}
4825
4826/*
4827 * Get the pattern, column and length for filename completion.
4828 * Sets the global variables: compl_col, compl_length and compl_pattern.
4829 */
4830 static int
4831get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4832{
4833 // Go back to just before the first filename character.
4834 if (startcol > 0)
4835 {
4836 char_u *p = line + startcol;
4837
4838 MB_PTR_BACK(line, p);
4839 while (p > line && vim_isfilec(PTR2CHAR(p)))
4840 MB_PTR_BACK(line, p);
4841 if (p == line && vim_isfilec(PTR2CHAR(p)))
4842 startcol = 0;
4843 else
4844 startcol = (int)(p - line) + 1;
4845 }
4846
4847 compl_col += startcol;
4848 compl_length = (int)curs_col - startcol;
4849 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4850 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004851 {
4852 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004853 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004854 }
4855
4856 compl_patternlen = STRLEN(compl_pattern);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004857
4858 return OK;
4859}
4860
4861/*
4862 * Get the pattern, column and length for command-line completion.
4863 * Sets the global variables: compl_col, compl_length and compl_pattern.
4864 */
4865 static int
4866get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4867{
4868 compl_pattern = vim_strnsave(line, curs_col);
4869 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004870 {
4871 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004872 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004873 }
4874 compl_patternlen = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004875 set_cmd_context(&compl_xp, compl_pattern,
Mike Williams16b63bd2024-06-01 11:33:40 +02004876 (int)compl_patternlen, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004877 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4878 || compl_xp.xp_context == EXPAND_NOTHING)
4879 // No completion possible, use an empty pattern to get a
4880 // "pattern not found" message.
4881 compl_col = curs_col;
4882 else
4883 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4884 compl_length = curs_col - compl_col;
4885
4886 return OK;
4887}
4888
4889/*
4890 * Get the pattern, column and length for user defined completion ('omnifunc',
4891 * 'completefunc' and 'thesaurusfunc')
4892 * Sets the global variables: compl_col, compl_length and compl_pattern.
4893 * Uses the global variable: spell_bad_len
4894 */
4895 static int
4896get_userdefined_compl_info(colnr_T curs_col UNUSED)
4897{
4898 int ret = FAIL;
4899
4900#ifdef FEAT_COMPL_FUNC
4901 // Call user defined function 'completefunc' with "a:findstart"
4902 // set to 1 to obtain the length of text to use for completion.
4903 char_u *line;
4904 typval_T args[3];
4905 int col;
4906 char_u *funcname;
4907 pos_T pos;
4908 int save_State = State;
4909 callback_T *cb;
4910
4911 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4912 // length as a string
4913 funcname = get_complete_funcname(ctrl_x_mode);
4914 if (*funcname == NUL)
4915 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004916 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004917 ? "completefunc" : "omnifunc");
4918 return FAIL;
4919 }
4920
4921 args[0].v_type = VAR_NUMBER;
4922 args[0].vval.v_number = 1;
4923 args[1].v_type = VAR_STRING;
4924 args[1].vval.v_string = (char_u *)"";
4925 args[2].v_type = VAR_UNKNOWN;
4926 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01004927 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004928 cb = get_insert_callback(ctrl_x_mode);
4929 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01004930 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004931
4932 State = save_State;
4933 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02004934 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004935 validate_cursor();
4936 if (!EQUAL_POS(curwin->w_cursor, pos))
4937 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00004938 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004939 return FAIL;
4940 }
4941
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004942 // Return value -2 means the user complete function wants to cancel the
4943 // complete without an error, do the same if the function did not execute
4944 // successfully.
4945 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004946 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01004947 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004948 if (col == -3)
4949 {
4950 ctrl_x_mode = CTRL_X_NORMAL;
4951 edit_submode = NULL;
4952 if (!shortmess(SHM_COMPLETIONMENU))
4953 msg_clr_cmdline();
4954 return FAIL;
4955 }
4956
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004957 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004958 // completion.
4959 compl_opt_refresh_always = FALSE;
4960 compl_opt_suppress_empty = FALSE;
4961
4962 if (col < 0)
4963 col = curs_col;
4964 compl_col = col;
4965 if (compl_col > curs_col)
4966 compl_col = curs_col;
4967
4968 // Setup variables for completion. Need to obtain "line" again,
4969 // it may have become invalid.
4970 line = ml_get(curwin->w_cursor.lnum);
4971 compl_length = curs_col - compl_col;
4972 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4973 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02004974 {
4975 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004976 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02004977 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004978
John Marriott8c85a2a2024-05-20 19:18:26 +02004979 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004980 ret = OK;
4981#endif
4982
4983 return ret;
4984}
4985
4986/*
4987 * Get the pattern, column and length for spell completion.
4988 * Sets the global variables: compl_col, compl_length and compl_pattern.
4989 * Uses the global variable: spell_bad_len
4990 */
4991 static int
4992get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4993{
4994 int ret = FAIL;
4995#ifdef FEAT_SPELL
4996 char_u *line;
4997
4998 if (spell_bad_len > 0)
4999 compl_col = curs_col - spell_bad_len;
5000 else
5001 compl_col = spell_word_start(startcol);
5002 if (compl_col >= (colnr_T)startcol)
5003 {
5004 compl_length = 0;
5005 compl_col = curs_col;
5006 }
5007 else
5008 {
5009 spell_expand_check_cap(compl_col);
5010 compl_length = (int)curs_col - compl_col;
5011 }
5012 // Need to obtain "line" again, it may have become invalid.
5013 line = ml_get(curwin->w_cursor.lnum);
5014 compl_pattern = vim_strnsave(line + compl_col, compl_length);
5015 if (compl_pattern == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005016 {
5017 compl_patternlen = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005018 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005019 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005020
John Marriott8c85a2a2024-05-20 19:18:26 +02005021 compl_patternlen = compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005022 ret = OK;
5023#endif
5024
5025 return ret;
5026}
5027
5028/*
5029 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005030 * "startcol" - start column number of the completion pattern/text
5031 * "cur_col" - current cursor column
5032 * On return, "line_invalid" is set to TRUE, if the current line may have
5033 * become invalid and needs to be fetched again.
5034 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005035 */
5036 static int
5037compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5038{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005039 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005040 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5041 && !thesaurus_func_complete(ctrl_x_mode)))
5042 {
5043 return get_normal_compl_info(line, startcol, curs_col);
5044 }
5045 else if (ctrl_x_mode_line_or_eval())
5046 {
5047 return get_wholeline_compl_info(line, curs_col);
5048 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005049 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005050 {
5051 return get_filename_compl_info(line, startcol, curs_col);
5052 }
5053 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5054 {
5055 return get_cmdline_compl_info(line, curs_col);
5056 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005057 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005058 || thesaurus_func_complete(ctrl_x_mode))
5059 {
5060 if (get_userdefined_compl_info(curs_col) == FAIL)
5061 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005062 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005063 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005064 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005065 {
5066 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5067 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005068 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005069 }
5070 else
5071 {
5072 internal_error("ins_complete()");
5073 return FAIL;
5074 }
5075
5076 return OK;
5077}
5078
5079/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005080 * Continue an interrupted completion mode search in "line".
5081 *
5082 * If this same ctrl_x_mode has been interrupted use the text from
5083 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5084 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5085 * the same line as the cursor then fix it (the line has been split because it
5086 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5087 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005088 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005089 static void
5090ins_compl_continue_search(char_u *line)
5091{
5092 // it is a continued search
5093 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005094 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5095 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005096 {
5097 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5098 {
5099 // line (probably) wrapped, set compl_startpos to the
5100 // first non_blank in the line, if it is not a wordchar
5101 // include it to get a better pattern, but then we don't
5102 // want the "\\<" prefix, check it below
5103 compl_col = (colnr_T)getwhitecols(line);
5104 compl_startpos.col = compl_col;
5105 compl_startpos.lnum = curwin->w_cursor.lnum;
5106 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5107 }
5108 else
5109 {
5110 // S_IPOS was set when we inserted a word that was at the
5111 // beginning of the line, which means that we'll go to SOL
5112 // mode but first we need to redefine compl_startpos
5113 if (compl_cont_status & CONT_S_IPOS)
5114 {
5115 compl_cont_status |= CONT_SOL;
5116 compl_startpos.col = (colnr_T)(skipwhite(
5117 line + compl_length
5118 + compl_startpos.col) - line);
5119 }
5120 compl_col = compl_startpos.col;
5121 }
5122 compl_length = curwin->w_cursor.col - (int)compl_col;
5123 // IObuff is used to add a "word from the next line" would we
5124 // have enough space? just being paranoid
5125#define MIN_SPACE 75
5126 if (compl_length > (IOSIZE - MIN_SPACE))
5127 {
5128 compl_cont_status &= ~CONT_SOL;
5129 compl_length = (IOSIZE - MIN_SPACE);
5130 compl_col = curwin->w_cursor.col - compl_length;
5131 }
5132 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5133 if (compl_length < 1)
5134 compl_cont_status &= CONT_LOCAL;
5135 }
5136 else if (ctrl_x_mode_line_or_eval())
5137 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5138 else
5139 compl_cont_status = 0;
5140}
5141
5142/*
5143 * start insert mode completion
5144 */
5145 static int
5146ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005147{
5148 char_u *line;
5149 int startcol = 0; // column where searched text starts
5150 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005151 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005152 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005153 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005154
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005155 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005156
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005157 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005158 did_si = FALSE;
5159 can_si = FALSE;
5160 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005161 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005162 return FAIL;
5163
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005164 line = ml_get(curwin->w_cursor.lnum);
5165 curs_col = curwin->w_cursor.col;
5166 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005167
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005168 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5169 && compl_cont_mode == ctrl_x_mode)
5170 // this same ctrl-x_mode was interrupted previously. Continue the
5171 // completion.
5172 ins_compl_continue_search(line);
5173 else
5174 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005175
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005176 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005177 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005178 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005179 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005180 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5181 compl_cont_status = 0;
5182 compl_cont_status |= CONT_N_ADDS;
5183 compl_startpos = curwin->w_cursor;
5184 startcol = (int)curs_col;
5185 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005186 }
5187
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005188 // Work out completion pattern and original text -- webb
5189 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5190 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005191 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5192 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005193 // restore did_ai, so that adding comment leader works
5194 did_ai = save_did_ai;
5195 return FAIL;
5196 }
5197 // If "line" was changed while getting completion info get it again.
5198 if (line_invalid)
5199 line = ml_get(curwin->w_cursor.lnum);
5200
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005201 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005202 {
5203 edit_submode_pre = (char_u *)_(" Adding");
5204 if (ctrl_x_mode_line_or_eval())
5205 {
5206 // Insert a new line, keep indentation but ignore 'comments'.
5207 char_u *old = curbuf->b_p_com;
5208
5209 curbuf->b_p_com = (char_u *)"";
5210 compl_startpos.lnum = curwin->w_cursor.lnum;
5211 compl_startpos.col = compl_col;
5212 ins_eol('\r');
5213 curbuf->b_p_com = old;
5214 compl_length = 0;
5215 compl_col = curwin->w_cursor.col;
5216 }
5217 }
5218 else
5219 {
5220 edit_submode_pre = NULL;
5221 compl_startpos.col = compl_col;
5222 }
5223
5224 if (compl_cont_status & CONT_LOCAL)
5225 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5226 else
5227 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5228
5229 // If any of the original typed text has been changed we need to fix
5230 // the redo buffer.
5231 ins_compl_fixRedoBufForLeader(NULL);
5232
5233 // Always add completion for the original text.
5234 vim_free(compl_orig_text);
5235 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
5236 if (p_ic)
5237 flags |= CP_ICASE;
5238 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
glepnir38f99a12024-08-23 18:31:06 +02005239 -1, NULL, NULL, NULL, 0, flags, FALSE, -1, -1) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005240 {
5241 VIM_CLEAR(compl_pattern);
John Marriott8c85a2a2024-05-20 19:18:26 +02005242 compl_patternlen = 0;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005243 VIM_CLEAR(compl_orig_text);
5244 return FAIL;
5245 }
5246
5247 // showmode might reset the internal line pointers, so it must
5248 // be called before line = ml_get(), or when this address is no
5249 // longer needed. -- Acevedo.
5250 edit_submode_extra = (char_u *)_("-- Searching...");
5251 edit_submode_highl = HLF_COUNT;
5252 showmode();
5253 edit_submode_extra = NULL;
5254 out_flush();
5255
5256 return OK;
5257}
5258
5259/*
5260 * display the completion status message
5261 */
5262 static void
5263ins_compl_show_statusmsg(void)
5264{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005265 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005266 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005267 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005268 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005269 ? (char_u *)_("Hit end of paragraph")
5270 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005271 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005272 }
5273
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005274 if (edit_submode_extra == NULL)
5275 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005276 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005277 {
5278 edit_submode_extra = (char_u *)_("Back at original");
5279 edit_submode_highl = HLF_W;
5280 }
5281 else if (compl_cont_status & CONT_S_IPOS)
5282 {
5283 edit_submode_extra = (char_u *)_("Word from other line");
5284 edit_submode_highl = HLF_COUNT;
5285 }
5286 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
5287 {
5288 edit_submode_extra = (char_u *)_("The only match");
5289 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005290 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005291 }
5292 else
5293 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005294#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005295 // Update completion sequence number when needed.
5296 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01005297 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01005298#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005299 // The match should always have a sequence number now, this is
5300 // just a safety check.
5301 if (compl_curr_match->cp_number != -1)
5302 {
5303 // Space for 10 text chars. + 2x10-digit no.s = 31.
5304 // Translations may need more than twice that.
5305 static char_u match_ref[81];
5306
5307 if (compl_matches > 0)
5308 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005309 _("match %d of %d"),
5310 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005311 else
5312 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005313 _("match %d"),
5314 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005315 edit_submode_extra = match_ref;
5316 edit_submode_highl = HLF_R;
5317 if (dollar_vcol >= 0)
5318 curs_columns(FALSE);
5319 }
5320 }
5321 }
5322
5323 // Show a message about what (completion) mode we're in.
5324 if (!compl_opt_suppress_empty)
5325 {
5326 showmode();
5327 if (!shortmess(SHM_COMPLETIONMENU))
5328 {
5329 if (edit_submode_extra != NULL)
5330 {
5331 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01005332 {
5333 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005334 msg_attr((char *)edit_submode_extra,
5335 edit_submode_highl < HLF_COUNT
5336 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01005337 msg_hist_off = FALSE;
5338 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005339 }
5340 else
5341 msg_clr_cmdline(); // necessary for "noshowmode"
5342 }
5343 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005344}
5345
5346/*
5347 * Do Insert mode completion.
5348 * Called when character "c" was typed, which has a meaning for completion.
5349 * Returns OK if completion was done, FAIL if something failed (out of mem).
5350 */
5351 int
5352ins_complete(int c, int enable_pum)
5353{
5354 int n;
5355 int save_w_wrow;
5356 int save_w_leftcol;
5357 int insert_match;
5358
5359 compl_direction = ins_compl_key2dir(c);
5360 insert_match = ins_compl_use_match(c);
5361
5362 if (!compl_started)
5363 {
5364 if (ins_compl_start() == FAIL)
5365 return FAIL;
5366 }
5367 else if (insert_match && stop_arrow() == FAIL)
5368 return FAIL;
5369
5370 compl_shown_match = compl_curr_match;
5371 compl_shows_dir = compl_direction;
5372
5373 // Find next match (and following matches).
5374 save_w_wrow = curwin->w_wrow;
5375 save_w_leftcol = curwin->w_leftcol;
5376 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
5377
5378 // may undisplay the popup menu
5379 ins_compl_upd_pum();
5380
5381 if (n > 1) // all matches have been found
5382 compl_matches = n;
5383 compl_curr_match = compl_shown_match;
5384 compl_direction = compl_shows_dir;
5385
5386 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
5387 // mode.
5388 if (got_int && !global_busy)
5389 {
5390 (void)vgetc();
5391 got_int = FALSE;
5392 }
5393
5394 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005395 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005396 {
5397 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
5398 // because we couldn't expand anything at first place, but if we used
5399 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
5400 // (such as M in M'exico) if not tried already. -- Acevedo
5401 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005402 || compl_status_adding()
5403 || (ctrl_x_mode_not_default()
5404 && !ctrl_x_mode_path_patterns()
5405 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005406 compl_cont_status &= ~CONT_N_ADDS;
5407 }
5408
5409 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
5410 compl_cont_status |= CONT_S_IPOS;
5411 else
5412 compl_cont_status &= ~CONT_S_IPOS;
5413
5414 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005415
5416 // Show the popup menu, unless we got interrupted.
5417 if (enable_pum && !compl_interrupted)
5418 show_pum(save_w_wrow, save_w_leftcol);
5419
5420 compl_was_interrupted = compl_interrupted;
5421 compl_interrupted = FALSE;
5422
5423 return OK;
5424}
5425
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00005426/*
5427 * Remove (if needed) and show the popup menu
5428 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005429 static void
5430show_pum(int prev_w_wrow, int prev_w_leftcol)
5431{
5432 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005433 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005434 RedrawingDisabled = 0;
5435
5436 // If the cursor moved or the display scrolled we need to remove the pum
5437 // first.
5438 setcursor();
5439 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
5440 ins_compl_del_pum();
5441
5442 ins_compl_show_pum();
5443 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01005444
5445 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005446}
5447
5448/*
5449 * Looks in the first "len" chars. of "src" for search-metachars.
5450 * If dest is not NULL the chars. are copied there quoting (with
5451 * a backslash) the metachars, and dest would be NUL terminated.
5452 * Returns the length (needed) of dest
5453 */
5454 static unsigned
5455quote_meta(char_u *dest, char_u *src, int len)
5456{
5457 unsigned m = (unsigned)len + 1; // one extra for the NUL
5458
5459 for ( ; --len >= 0; src++)
5460 {
5461 switch (*src)
5462 {
5463 case '.':
5464 case '*':
5465 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005466 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005467 break;
5468 // FALLTHROUGH
5469 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01005470 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005471 break;
5472 // FALLTHROUGH
5473 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005474 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005475 break;
5476 // FALLTHROUGH
5477 case '^': // currently it's not needed.
5478 case '$':
5479 m++;
5480 if (dest != NULL)
5481 *dest++ = '\\';
5482 break;
5483 }
5484 if (dest != NULL)
5485 *dest++ = *src;
5486 // Copy remaining bytes of a multibyte character.
5487 if (has_mbyte)
5488 {
5489 int i, mb_len;
5490
5491 mb_len = (*mb_ptr2len)(src) - 1;
5492 if (mb_len > 0 && len >= mb_len)
5493 for (i = 0; i < mb_len; ++i)
5494 {
5495 --len;
5496 ++src;
5497 if (dest != NULL)
5498 *dest++ = *src;
5499 }
5500 }
5501 }
5502 if (dest != NULL)
5503 *dest = NUL;
5504
5505 return m;
5506}
5507
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005508#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005509 void
5510free_insexpand_stuff(void)
5511{
5512 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00005513# ifdef FEAT_EVAL
5514 free_callback(&cfu_cb);
5515 free_callback(&ofu_cb);
5516 free_callback(&tsrfu_cb);
5517# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005518}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005519#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005520
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005521#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005522/*
5523 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
5524 * spelled word, if there is one.
5525 */
5526 static void
5527spell_back_to_badword(void)
5528{
5529 pos_T tpos = curwin->w_cursor;
5530
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02005531 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005532 if (curwin->w_cursor.col != tpos.col)
5533 start_arrow(&tpos);
5534}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02005535#endif