blob: 8c15adeee4fc7d4309d333a7bbe3b010a286aebe [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/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010091 * Structure used to store one match for insert completion.
92 */
93typedef struct compl_S compl_T;
94struct compl_S
95{
96 compl_T *cp_next;
97 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +010098 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +010099 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200100 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100101#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100102 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100103#endif
glepnir0fe17f82024-10-08 22:26:44 +0200104 char_u *cp_fname; // file containing the match, allocated when
105 // cp_flags has CP_FREE_FNAME
106 int cp_flags; // CP_ values
107 int cp_number; // sequence number
108 int cp_score; // fuzzy match score
glepnird4088ed2024-12-31 10:55:22 +0100109 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200110 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200111 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palyacbe53192025-04-14 22:13:15 +0200112 int cp_cpt_value_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100113};
114
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200115// values for cp_flags
116# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
117# define CP_FREE_FNAME 2 // cp_fname is allocated
118# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
119# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
120# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200121# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100122
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100123/*
124 * All the current matches are stored in a list.
125 * "compl_first_match" points to the start of the list.
126 * "compl_curr_match" points to the currently selected entry.
127 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200128 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000129 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100130 */
131static compl_T *compl_first_match = NULL;
132static compl_T *compl_curr_match = NULL;
133static compl_T *compl_shown_match = NULL;
134static compl_T *compl_old_match = NULL;
135
glepnirf31cfa22025-03-06 21:59:13 +0100136// list used to store the compl_T which have the max score
137// used for completefuzzycollect
138static compl_T **compl_best_matches = NULL;
139static int compl_num_bests = 0;
140// inserted a longest when completefuzzycollect enabled
141static int compl_cfc_longest_ins = FALSE;
142
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100143// After using a cursor key <Enter> selects a match in the popup menu,
144// otherwise it inserts a line break.
145static int compl_enter_selects = FALSE;
146
147// When "compl_leader" is not NULL only matches that start with this string
148// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100149static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100150
151static int compl_get_longest = FALSE; // put longest common string
152 // in compl_leader
153
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100154// Selected one of the matches. When FALSE the match was edited or using the
155// longest common string.
156static int compl_used_match;
157
158// didn't finish finding completions.
159static int compl_was_interrupted = FALSE;
160
161// Set when character typed while looking for matches and it means we should
162// stop looking for matches.
163static int compl_interrupted = FALSE;
164
165static int compl_restarting = FALSE; // don't insert match
166
167// When the first completion is done "compl_started" is set. When it's
168// FALSE the word to be completed must be located.
169static int compl_started = FALSE;
170
171// Which Ctrl-X mode are we in?
172static int ctrl_x_mode = CTRL_X_NORMAL;
173
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000174static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200175static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
176#ifdef FEAT_COMPL_FUNC
177static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
178#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100179static int compl_direction = FORWARD;
180static int compl_shows_dir = FORWARD;
181static int compl_pending = 0; // > 1 for postponed CTRL-N
182static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000183// Length in bytes of the text being completed (this is deleted to be replaced
184// by the match.)
185static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100186static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100187static colnr_T compl_col = 0; // column where the text starts
188 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100189static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100190static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100191 // completion started
192static int compl_cont_mode = 0;
193static expand_T compl_xp;
194
glepnircf7f0122025-04-15 19:02:00 +0200195static win_T *compl_curr_win = NULL; // win where completion is active
196static buf_T *compl_curr_buf = NULL; // buf where completion is active
197
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000198// List of flags for method of completion.
199static int compl_cont_status = 0;
200# define CONT_ADDING 1 // "normal" or "adding" expansion
201# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
202 // it's set only iff N_ADDS is set
203# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
204# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
205 // if so, word-wise-expansion will set SOL
206# define CONT_SOL 16 // pattern includes start of line, just for
207 // word-wise expansion, not set for ^X^L
208# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
209 // expansion, (eg use complete=.)
210
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100211static int compl_opt_refresh_always = FALSE;
212static int compl_opt_suppress_empty = FALSE;
213
glepnira218cc62024-06-03 19:32:39 +0200214static int compl_selected_item = -1;
215
glepnir8159fb12024-07-17 20:32:54 +0200216static int *compl_fuzzy_scores;
217
Girish Palyacbe53192025-04-14 22:13:15 +0200218static int *cpt_func_refresh_always; // array indicating which 'cpt' functions have 'refresh:always' set
219static int cpt_value_count; // total number of completion sources specified in the 'cpt' option
220static int cpt_value_idx; // index of the current completion source being expanded
221
glepnir6a38aff2024-12-16 21:56:16 +0100222// "compl_match_array" points the currently displayed list of entries in the
223// popup menu. It is NULL when there is no popup menu.
224static pumitem_T *compl_match_array = NULL;
225static int compl_match_arraysize;
226
glepnirf31cfa22025-03-06 21:59:13 +0100227static 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_hl, int score);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100228static void ins_compl_longest_match(compl_T *match);
229static void ins_compl_del_pum(void);
230static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100231static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100232static int ins_compl_need_restart(void);
233static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000234static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100235static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100236static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100237static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
238# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
239static void ins_compl_add_list(list_T *list);
240static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200241static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
242static callback_T *get_cpt_func_callback(char_u *funcname);
243static void get_cpt_func_completion_matches(callback_T *cb);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100244# endif
Girish Palyacbe53192025-04-14 22:13:15 +0200245static int cpt_compl_src_init(char_u *p_cpt);
246static int is_cpt_func_refresh_always(void);
247static void cpt_compl_src_clear(void);
248static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100249static int ins_compl_key2dir(int c);
250static int ins_compl_pum_key(int c);
251static int ins_compl_key2count(int c);
252static void show_pum(int prev_w_wrow, int prev_w_leftcol);
253static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100254static int ins_compl_has_multiple(void);
255static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100256static void ins_compl_longest_insert(char_u *prefix);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100257
258#ifdef FEAT_SPELL
259static void spell_back_to_badword(void);
260static int spell_bad_len = 0; // length of located bad word
261#endif
262
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100263/*
264 * CTRL-X pressed in Insert mode.
265 */
266 void
267ins_ctrl_x(void)
268{
zeertzjqdca29d92021-08-31 19:12:51 +0200269 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100270 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000271 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100272 if (compl_cont_status & CONT_N_ADDS)
273 compl_cont_status |= CONT_INTRPT;
274 else
275 compl_cont_status = 0;
276 // We're not sure which CTRL-X mode it will be yet
277 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
278 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
279 edit_submode_pre = NULL;
280 showmode();
281 }
zeertzjqdca29d92021-08-31 19:12:51 +0200282 else
283 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
284 // CTRL-V look like CTRL-N
285 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100286
LemonBoy2bf52dd2022-04-09 18:17:34 +0100287 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100288}
289
290/*
291 * Functions to check the current CTRL-X mode.
292 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000293int ctrl_x_mode_none(void)
294 { return ctrl_x_mode == 0; }
295int ctrl_x_mode_normal(void)
296 { return ctrl_x_mode == CTRL_X_NORMAL; }
297int ctrl_x_mode_scroll(void)
298 { return ctrl_x_mode == CTRL_X_SCROLL; }
299int ctrl_x_mode_whole_line(void)
300 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
301int ctrl_x_mode_files(void)
302 { return ctrl_x_mode == CTRL_X_FILES; }
303int ctrl_x_mode_tags(void)
304 { return ctrl_x_mode == CTRL_X_TAGS; }
305int ctrl_x_mode_path_patterns(void)
306 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
307int ctrl_x_mode_path_defines(void)
308 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
309int ctrl_x_mode_dictionary(void)
310 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
311int ctrl_x_mode_thesaurus(void)
312 { return ctrl_x_mode == CTRL_X_THESAURUS; }
313int ctrl_x_mode_cmdline(void)
314 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200315 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000316int ctrl_x_mode_function(void)
317 { return ctrl_x_mode == CTRL_X_FUNCTION; }
318int ctrl_x_mode_omni(void)
319 { return ctrl_x_mode == CTRL_X_OMNI; }
320int ctrl_x_mode_spell(void)
321 { return ctrl_x_mode == CTRL_X_SPELL; }
322static int ctrl_x_mode_eval(void)
323 { return ctrl_x_mode == CTRL_X_EVAL; }
324int ctrl_x_mode_line_or_eval(void)
325 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100326
327/*
328 * Whether other than default completion has been selected.
329 */
330 int
331ctrl_x_mode_not_default(void)
332{
333 return ctrl_x_mode != CTRL_X_NORMAL;
334}
335
336/*
zeertzjqdca29d92021-08-31 19:12:51 +0200337 * Whether CTRL-X was typed without a following character,
338 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100339 */
340 int
341ctrl_x_mode_not_defined_yet(void)
342{
343 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
344}
345
346/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000347 * Return TRUE if currently in "normal" or "adding" insert completion matches
348 * state
349 */
350 int
351compl_status_adding(void)
352{
353 return compl_cont_status & CONT_ADDING;
354}
355
356/*
357 * Return TRUE if the completion pattern includes start of line, just for
358 * word-wise expansion.
359 */
360 int
361compl_status_sol(void)
362{
363 return compl_cont_status & CONT_SOL;
364}
365
366/*
367 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
368 */
369 int
370compl_status_local(void)
371{
372 return compl_cont_status & CONT_LOCAL;
373}
374
375/*
376 * Clear the completion status flags
377 */
378 void
379compl_status_clear(void)
380{
381 compl_cont_status = 0;
382}
383
384/*
385 * Return TRUE if completion is using the forward direction matches
386 */
387 static int
388compl_dir_forward(void)
389{
390 return compl_direction == FORWARD;
391}
392
393/*
394 * Return TRUE if currently showing forward completion matches
395 */
396 static int
397compl_shows_dir_forward(void)
398{
399 return compl_shows_dir == FORWARD;
400}
401
402/*
403 * Return TRUE if currently showing backward completion matches
404 */
405 static int
406compl_shows_dir_backward(void)
407{
408 return compl_shows_dir == BACKWARD;
409}
410
411/*
412 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100413 */
414 int
415has_compl_option(int dict_opt)
416{
417 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200418#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100419 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200420#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100421 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100422 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
423#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100424 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100425#endif
426 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100427 {
428 ctrl_x_mode = CTRL_X_NORMAL;
429 edit_submode = NULL;
430 msg_attr(dict_opt ? _("'dictionary' option is empty")
431 : _("'thesaurus' option is empty"),
432 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100433 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100434 {
435 vim_beep(BO_COMPL);
436 setcursor();
437 out_flush();
438#ifdef FEAT_EVAL
439 if (!get_vim_var_nr(VV_TESTING))
440#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100441 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100442 }
443 return FALSE;
444 }
445 return TRUE;
446}
447
448/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000449 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100450 * This depends on the current mode.
451 */
452 int
453vim_is_ctrl_x_key(int c)
454{
455 // Always allow ^R - let its results then be checked
456 if (c == Ctrl_R)
457 return TRUE;
458
459 // Accept <PageUp> and <PageDown> if the popup menu is visible.
460 if (ins_compl_pum_key(c))
461 return TRUE;
462
463 switch (ctrl_x_mode)
464 {
465 case 0: // Not in any CTRL-X mode
466 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
467 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200468 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100469 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
470 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
471 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
472 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
473 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200474 || c == Ctrl_S || c == Ctrl_K || c == 's'
475 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100476 case CTRL_X_SCROLL:
477 return (c == Ctrl_Y || c == Ctrl_E);
478 case CTRL_X_WHOLE_LINE:
479 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
480 case CTRL_X_FILES:
481 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
482 case CTRL_X_DICTIONARY:
483 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
484 case CTRL_X_THESAURUS:
485 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
486 case CTRL_X_TAGS:
487 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
488#ifdef FEAT_FIND_ID
489 case CTRL_X_PATH_PATTERNS:
490 return (c == Ctrl_P || c == Ctrl_N);
491 case CTRL_X_PATH_DEFINES:
492 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
493#endif
494 case CTRL_X_CMDLINE:
495 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
496 || c == Ctrl_X);
497#ifdef FEAT_COMPL_FUNC
498 case CTRL_X_FUNCTION:
499 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
500 case CTRL_X_OMNI:
501 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
502#endif
503 case CTRL_X_SPELL:
504 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
505 case CTRL_X_EVAL:
506 return (c == Ctrl_P || c == Ctrl_N);
507 }
508 internal_error("vim_is_ctrl_x_key()");
509 return FALSE;
510}
511
512/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000513 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000514 */
515 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000516match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000517{
518 return match->cp_flags & CP_ORIGINAL_TEXT;
519}
520
521/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000522 * Returns TRUE if "match" is the first match in the completion list.
523 */
524 static int
525is_first_match(compl_T *match)
526{
527 return match == compl_first_match;
528}
529
530/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100531 * Return TRUE when character "c" is part of the item currently being
532 * completed. Used to decide whether to abandon complete mode when the menu
533 * is visible.
534 */
535 int
536ins_compl_accept_char(int c)
537{
538 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
539 // When expanding an identifier only accept identifier chars.
540 return vim_isIDc(c);
541
542 switch (ctrl_x_mode)
543 {
544 case CTRL_X_FILES:
545 // When expanding file name only accept file name chars. But not
546 // path separators, so that "proto/<Tab>" expands files in
547 // "proto", not "proto/" as a whole
548 return vim_isfilec(c) && !vim_ispathsep(c);
549
550 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200551 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100552 case CTRL_X_OMNI:
553 // Command line and Omni completion can work with just about any
554 // printable character, but do stop at white space.
555 return vim_isprintc(c) && !VIM_ISWHITE(c);
556
557 case CTRL_X_WHOLE_LINE:
558 // For while line completion a space can be part of the line.
559 return vim_isprintc(c);
560 }
561 return vim_iswordc(c);
562}
563
564/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000565 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100566 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000567 */
568 static char_u *
569ins_compl_infercase_gettext(
570 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100571 int char_len,
572 int compl_char_len,
573 int min_len,
574 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000575{
576 int *wca; // Wide character array.
577 char_u *p;
578 int i, c;
579 int has_lower = FALSE;
580 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100581 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000582
583 IObuff[0] = NUL;
584
585 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100586 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000587 if (wca == NULL)
588 return IObuff;
589
590 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100591 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100592 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000593 if (has_mbyte)
594 wca[i] = mb_ptr2char_adv(&p);
595 else
596 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100597 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000598
599 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100600 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000601 for (i = 0; i < min_len; ++i)
602 {
glepnir6e199932024-12-14 21:13:27 +0100603 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000604 if (MB_ISLOWER(c))
605 {
606 has_lower = TRUE;
607 if (MB_ISUPPER(wca[i]))
608 {
609 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100610 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000611 wca[i] = MB_TOLOWER(wca[i]);
612 break;
613 }
614 }
615 }
616
617 // Rule 2: No lower case, 2nd consecutive letter converted to
618 // upper case.
619 if (!has_lower)
620 {
John Marriott5e6ea922024-11-23 14:01:57 +0100621 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000622 for (i = 0; i < min_len; ++i)
623 {
glepnir6e199932024-12-14 21:13:27 +0100624 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000625 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
626 {
627 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100628 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000629 wca[i] = MB_TOUPPER(wca[i]);
630 break;
631 }
632 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
633 }
634 }
635
636 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100637 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000638 for (i = 0; i < min_len; ++i)
639 {
glepnir6e199932024-12-14 21:13:27 +0100640 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000641 if (MB_ISLOWER(c))
642 wca[i] = MB_TOLOWER(wca[i]);
643 else if (MB_ISUPPER(c))
644 wca[i] = MB_TOUPPER(wca[i]);
645 }
646
647 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000648 p = IObuff;
649 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100650 ga_init2(&gap, 1, 500);
651 while (i < char_len)
652 {
653 if (gap.ga_data != NULL)
654 {
655 if (ga_grow(&gap, 10) == FAIL)
656 {
657 ga_clear(&gap);
658 return (char_u *)"[failed]";
659 }
660 p = (char_u *)gap.ga_data + gap.ga_len;
661 if (has_mbyte)
662 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
663 else
664 {
665 *p = wca[i++];
666 ++gap.ga_len;
667 }
668 }
669 else if ((p - IObuff) + 6 >= IOSIZE)
670 {
671 // Multi-byte characters can occupy up to five bytes more than
672 // ASCII characters, and we also need one byte for NUL, so when
673 // getting to six bytes from the edge of IObuff switch to using a
674 // growarray. Add the character in the next round.
675 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100676 {
677 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100678 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100679 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100680 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100681 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100682 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100683 }
684 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000685 p += (*mb_char2bytes)(wca[i++], p);
686 else
687 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100688 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000689 vim_free(wca);
690
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100691 if (gap.ga_data != NULL)
692 {
693 *tofree = gap.ga_data;
694 return gap.ga_data;
695 }
696
697 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000698 return IObuff;
699}
700
701/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100702 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
703 * case of the originally typed text is used, and the case of the completed
704 * text is inferred, ie this tries to work out what case you probably wanted
705 * the rest of the word to be in -- webb
706 */
707 int
708ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200709 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100710 int len,
711 int icase,
712 char_u *fname,
713 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100714 int cont_s_ipos, // next ^X<> will set initial_pos
715 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100716{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200717 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100718 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100719 int char_len; // count multi-byte characters
720 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100721 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200722 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100723 int res;
724 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100725
726 if (p_ic && curbuf->b_p_inf && len > 0)
727 {
728 // Infer case of completed part.
729
730 // Find actual length of completion.
731 if (has_mbyte)
732 {
733 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100734 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100735 while (*p != NUL)
736 {
737 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100738 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100739 }
740 }
741 else
glepnir6e199932024-12-14 21:13:27 +0100742 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100743 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100744 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100745
746 // Find actual length of original text.
747 if (has_mbyte)
748 {
John Marriott5e6ea922024-11-23 14:01:57 +0100749 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100750 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100751 while (*p != NUL)
752 {
753 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100754 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100755 }
756 }
757 else
glepnir6e199932024-12-14 21:13:27 +0100758 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100759 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100760 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100761
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100762 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100763 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100764 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100765
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100766 str = ins_compl_infercase_gettext(str, char_len,
767 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100768 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200769 if (cont_s_ipos)
770 flags |= CP_CONT_S_IPOS;
771 if (icase)
772 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200773
glepnirf31cfa22025-03-06 21:59:13 +0100774 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100775 vim_free(tofree);
776 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100777}
778
779/*
glepnirf31cfa22025-03-06 21:59:13 +0100780 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
781 */
782 static int
783cfc_has_mode(void)
784{
glepnir58760162025-03-13 21:39:51 +0100785 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
786 return (cfc_flags & CFC_KEYWORD) != 0;
787 else if (ctrl_x_mode_files())
788 return (cfc_flags & CFC_FILES) != 0;
789 else if (ctrl_x_mode_whole_line())
790 return (cfc_flags & CFC_WHOLELINE) != 0;
791 else
792 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100793}
794
795/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000796 * Add a match to the list of matches. The arguments are:
797 * str - text of the match to add
798 * len - length of "str". If -1, then the length of "str" is
799 * computed.
800 * fname - file name to associate with this match.
801 * cptext - list of strings to use with this match (for abbr, menu, info
802 * and kind)
803 * user_data - user supplied data (any vim type) for this match
804 * cdir - match direction. If 0, use "compl_direction".
805 * flags_arg - match flags (cp_flags)
806 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100807 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000808 * If "cdir" is FORWARD, then the match is added after the current match.
809 * Otherwise, it is added before the current match.
810 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100811 * If the given string is already in the list of completions, then return
812 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
813 * maybe because alloc() returns NULL, then FAIL is returned.
814 */
815 static int
816ins_compl_add(
817 char_u *str,
818 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100820 char_u **cptext, // extra text for popup menu or NULL
821 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100822 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200823 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200824 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100825 int *user_hl, // user abbr/kind hlattr
826 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100827{
glepnirf31cfa22025-03-06 21:59:13 +0100828 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200830 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100831 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100832
Bram Moolenaarceb06192021-04-04 15:05:22 +0200833 if (flags & CP_FAST)
834 fast_breakcheck();
835 else
836 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100837 if (got_int)
838 return FAIL;
839 if (len < 0)
840 len = (int)STRLEN(str);
841
842 // If the same match is already present, don't add it.
843 if (compl_first_match != NULL && !adup)
844 {
845 match = compl_first_match;
846 do
847 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000848 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100849 && STRNCMP(match->cp_str.string, str, len) == 0
850 && ((int)match->cp_str.length <= len
851 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100852 return NOTDONE;
853 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000854 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100855 }
856
857 // Remove any popup menu before changing the list of matches.
858 ins_compl_del_pum();
859
860 // Allocate a new match structure.
861 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200862 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100863 if (match == NULL)
864 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100865 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100866 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100867 {
868 vim_free(match);
869 return FAIL;
870 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100871
John Marriott5e6ea922024-11-23 14:01:57 +0100872 match->cp_str.length = len;
873
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100874 // match-fname is:
875 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200876 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100877 // - NULL otherwise. --Acevedo
878 if (fname != NULL
879 && compl_curr_match != NULL
880 && compl_curr_match->cp_fname != NULL
881 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
882 match->cp_fname = compl_curr_match->cp_fname;
883 else if (fname != NULL)
884 {
885 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200886 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100887 }
888 else
889 match->cp_fname = NULL;
890 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100891 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
892 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100893 match->cp_score = score;
Girish Palyacbe53192025-04-14 22:13:15 +0200894 match->cp_cpt_value_idx = cpt_value_idx;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100895
896 if (cptext != NULL)
897 {
898 int i;
899
900 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100901 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100902 if (cptext[i] != NULL && *cptext[i] != NUL)
903 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100904 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100905 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100906#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100907 if (user_data != NULL)
908 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100909#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100910
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000911 // Link the new match structure after (FORWARD) or before (BACKWARD) the
912 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100913 if (compl_first_match == NULL)
914 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +0100915 else if (cfc_has_mode() && score > 0 && compl_get_longest)
916 {
917 current = compl_first_match->cp_next;
918 prev = compl_first_match;
919 inserted = FALSE;
920 // The direction is ignored when using longest and
921 // completefuzzycollect, because matches are inserted
922 // and sorted by score.
923 while (current != NULL && current != compl_first_match)
924 {
925 if (current->cp_score < score)
926 {
927 match->cp_next = current;
928 match->cp_prev = current->cp_prev;
929 if (current->cp_prev)
930 current->cp_prev->cp_next = match;
931 current->cp_prev = match;
932 inserted = TRUE;
933 break;
934 }
935 prev = current;
936 current = current->cp_next;
937 }
938 if (!inserted)
939 {
940 prev->cp_next = match;
941 match->cp_prev = prev;
942 match->cp_next = compl_first_match;
943 compl_first_match->cp_prev = match;
944 }
945 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100946 else if (dir == FORWARD)
947 {
948 match->cp_next = compl_curr_match->cp_next;
949 match->cp_prev = compl_curr_match;
950 }
951 else // BACKWARD
952 {
953 match->cp_next = compl_curr_match;
954 match->cp_prev = compl_curr_match->cp_prev;
955 }
956 if (match->cp_next)
957 match->cp_next->cp_prev = match;
958 if (match->cp_prev)
959 match->cp_prev->cp_next = match;
960 else // if there's nothing before, it is the first match
961 compl_first_match = match;
962 compl_curr_match = match;
963
964 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +0100965 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100966 ins_compl_longest_match(match);
967
968 return OK;
969}
970
971/*
972 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200973 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100974 */
975 static int
976ins_compl_equal(compl_T *match, char_u *str, int len)
977{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200978 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200979 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200980 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100981 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
982 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100983}
984
985/*
glepnir6a38aff2024-12-16 21:56:16 +0100986 * when len is -1 mean use whole length of p otherwise part of p
987 */
988 static void
989ins_compl_insert_bytes(char_u *p, int len)
990{
991 if (len == -1)
992 len = (int)STRLEN(p);
993 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +0100994 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +0100995}
996
997/*
zeertzjqd32bf0a2024-12-17 20:55:13 +0100998 * Checks if the column is within the currently inserted completion text
999 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001000 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001001 */
1002 int
glepnir76bdb822025-02-08 19:04:51 +01001003ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001004{
glepnir76bdb822025-02-08 19:04:51 +01001005 int start_col;
1006 int attr;
1007
1008 if ((get_cot_flags() & COT_FUZZY)
1009 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001010 return -1;
1011
glepnir76bdb822025-02-08 19:04:51 +01001012 start_col = compl_col + (int)ins_compl_leader_len();
1013 if (!ins_compl_has_multiple())
1014 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1015
1016 // Multiple lines
1017 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1018 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1019 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1020 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001021
1022 return -1;
1023}
1024
1025/*
glepnir76bdb822025-02-08 19:04:51 +01001026 * Returns TRUE if the current completion string contains newline characters,
1027 * indicating it's a multi-line completion.
1028 */
1029 static int
1030ins_compl_has_multiple(void)
1031{
1032 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1033}
1034
1035/*
1036 * Returns TRUE if the given line number falls within the range of a multi-line
1037 * completion, i.e. between the starting line (compl_lnum) and current cursor
1038 * line. Always returns FALSE for single-line completions.
1039 */
1040 int
1041ins_compl_lnum_in_range(linenr_T lnum)
1042{
1043 if (!ins_compl_has_multiple())
1044 return FALSE;
1045 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1046}
1047
1048/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001049 * Reduce the longest common string for match "match".
1050 */
1051 static void
1052ins_compl_longest_match(compl_T *match)
1053{
1054 char_u *p, *s;
1055 int c1, c2;
1056 int had_match;
1057
John Marriott5e6ea922024-11-23 14:01:57 +01001058 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001059 {
1060 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001061 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1062 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001063 return;
1064
John Marriott5e6ea922024-11-23 14:01:57 +01001065 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001066 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001067 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001068
1069 // When the match isn't there (to avoid matching itself) remove it
1070 // again after redrawing.
1071 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001072 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001073 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001074
1075 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001076 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001077
1078 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001079 p = compl_leader.string;
1080 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001081 while (*p != NUL)
1082 {
1083 if (has_mbyte)
1084 {
1085 c1 = mb_ptr2char(p);
1086 c2 = mb_ptr2char(s);
1087 }
1088 else
1089 {
1090 c1 = *p;
1091 c2 = *s;
1092 }
1093 if ((match->cp_flags & CP_ICASE)
1094 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1095 break;
1096 if (has_mbyte)
1097 {
1098 MB_PTR_ADV(p);
1099 MB_PTR_ADV(s);
1100 }
1101 else
1102 {
1103 ++p;
1104 ++s;
1105 }
1106 }
1107
1108 if (*p != NUL)
1109 {
1110 // Leader was shortened, need to change the inserted text.
1111 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001112 compl_leader.length = (size_t)(p - compl_leader.string);
1113
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001114 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001115 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001116
1117 // When the match isn't there (to avoid matching itself) remove it
1118 // again after redrawing.
1119 if (!had_match)
1120 ins_compl_delete();
1121 }
1122
1123 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001124}
1125
1126/*
1127 * Add an array of matches to the list of matches.
1128 * Frees matches[].
1129 */
1130 static void
1131ins_compl_add_matches(
1132 int num_matches,
1133 char_u **matches,
1134 int icase)
1135{
1136 int i;
1137 int add_r = OK;
1138 int dir = compl_direction;
1139
1140 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001141 {
1142 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001143 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001144 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001145 // if dir was BACKWARD then honor it just once
1146 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001147 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001148 FreeWild(num_matches, matches);
1149}
1150
1151/*
1152 * Make the completion list cyclic.
1153 * Return the number of matches (excluding the original).
1154 */
1155 static int
1156ins_compl_make_cyclic(void)
1157{
1158 compl_T *match;
1159 int count = 0;
1160
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001161 if (compl_first_match == NULL)
1162 return 0;
1163
1164 // Find the end of the list.
1165 match = compl_first_match;
1166 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001167 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001168 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001169 match = match->cp_next;
1170 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001171 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001172 match->cp_next = compl_first_match;
1173 compl_first_match->cp_prev = match;
1174
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001175 return count;
1176}
1177
1178/*
1179 * Return whether there currently is a shown match.
1180 */
1181 int
1182ins_compl_has_shown_match(void)
1183{
1184 return compl_shown_match == NULL
1185 || compl_shown_match != compl_shown_match->cp_next;
1186}
1187
1188/*
1189 * Return whether the shown match is long enough.
1190 */
1191 int
1192ins_compl_long_shown_match(void)
1193{
John Marriott5e6ea922024-11-23 14:01:57 +01001194 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001195 > curwin->w_cursor.col - compl_col;
1196}
1197
1198/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001199 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001200 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001201 unsigned int
1202get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001203{
zeertzjq529b9ad2024-06-05 20:27:06 +02001204 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001205}
1206
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001207/*
1208 * Update the screen and when there is any scrolling remove the popup menu.
1209 */
1210 static void
1211ins_compl_upd_pum(void)
1212{
1213 int h;
1214
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001215 if (compl_match_array == NULL)
1216 return;
1217
1218 h = curwin->w_cline_height;
1219 // Update the screen later, before drawing the popup menu over it.
1220 pum_call_update_screen();
1221 if (h != curwin->w_cline_height)
1222 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001223}
1224
1225/*
1226 * Remove any popup menu.
1227 */
1228 static void
1229ins_compl_del_pum(void)
1230{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001231 if (compl_match_array == NULL)
1232 return;
1233
1234 pum_undisplay();
1235 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001236}
1237
1238/*
1239 * Return TRUE if the popup menu should be displayed.
1240 */
1241 int
1242pum_wanted(void)
1243{
1244 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001245 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001246 return FALSE;
1247
1248 // The display looks bad on a B&W display.
1249 if (t_colors < 8
1250#ifdef FEAT_GUI
1251 && !gui.in_use
1252#endif
1253 )
1254 return FALSE;
1255 return TRUE;
1256}
1257
1258/*
1259 * Return TRUE if there are two or more matches to be shown in the popup menu.
1260 * One if 'completopt' contains "menuone".
1261 */
1262 static int
1263pum_enough_matches(void)
1264{
1265 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001266 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001267
1268 // Don't display the popup menu if there are no matches or there is only
1269 // one (ignoring the original text).
1270 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001271 do
1272 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001273 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001274 break;
1275 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001276 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001277
zeertzjq529b9ad2024-06-05 20:27:06 +02001278 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001279 return (i >= 1);
1280 return (i >= 2);
1281}
1282
Bram Moolenaar3075a452021-11-17 15:51:52 +00001283#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001284/*
1285 * Allocate Dict for the completed item.
1286 * { word, abbr, menu, kind, info }
1287 */
1288 static dict_T *
1289ins_compl_dict_alloc(compl_T *match)
1290{
1291 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1292
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001293 if (dict == NULL)
1294 return NULL;
1295
John Marriott5e6ea922024-11-23 14:01:57 +01001296 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001297 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1298 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1299 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1300 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1301 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1302 dict_add_string(dict, "user_data", (char_u *)"");
1303 else
1304 dict_add_tv(dict, "user_data", &match->cp_user_data);
1305
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001306 return dict;
1307}
1308
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001309/*
1310 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1311 * completion menu is changed.
1312 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001313 static void
1314trigger_complete_changed_event(int cur)
1315{
1316 dict_T *v_event;
1317 dict_T *item;
1318 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001319 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001320
1321 if (recursive)
1322 return;
1323
glepnir40891ba2025-02-10 22:18:00 +01001324 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001325 if (item == NULL)
1326 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001327 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001328 dict_add_dict(v_event, "completed_item", item);
1329 pum_set_event_info(v_event);
1330 dict_set_items_ro(v_event);
1331
1332 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001333 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001334 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001335 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001336 recursive = FALSE;
1337
Bram Moolenaar3075a452021-11-17 15:51:52 +00001338 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001339}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001340#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001341
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001342/*
glepnira218cc62024-06-03 19:32:39 +02001343 * pumitem qsort compare func
1344 */
1345 static int
zeertzjq8e567472024-06-14 20:04:42 +02001346ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001347{
1348 const int sa = (*(pumitem_T *)a).pum_score;
1349 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001350 const int ia = (*(pumitem_T *)a).pum_idx;
1351 const int ib = (*(pumitem_T *)b).pum_idx;
1352 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001353}
1354
1355/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001356 * Build a popup menu to show the completion matches.
1357 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1358 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001359 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001360 static int
1361ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001362{
1363 compl_T *compl;
1364 compl_T *shown_compl = NULL;
1365 int did_find_shown_match = FALSE;
1366 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001367 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001368 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001369 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001370 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001371 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001372 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1373 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001374 compl_T *match_head = NULL;
1375 compl_T *match_tail = NULL;
1376 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001377 int update_shown_match = fuzzy_filter;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001378
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001379 // Need to build the popup menu list.
1380 compl_match_arraysize = 0;
1381 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001382
glepnira49c0772024-11-30 10:56:30 +01001383 // If the current match is the original text don't find the first
1384 // match after it, don't highlight anything.
1385 if (match_at_original_text(compl_shown_match))
1386 shown_match_ok = TRUE;
1387
glepnire4e4d1c2025-04-02 20:18:25 +02001388 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1389 && compl_shown_match->cp_score > 0)
1390 update_shown_match = FALSE;
1391
glepnira49c0772024-11-30 10:56:30 +01001392 if (compl_leader.string != NULL
1393 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1394 && shown_match_ok == FALSE)
1395 compl_shown_match = compl_no_select ? compl_first_match
1396 : compl_first_match->cp_next;
1397
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001398 do
1399 {
glepnird4088ed2024-12-31 10:55:22 +01001400 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001401 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1402 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001403 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001404 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001405
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001406 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001407 && (compl_leader.string == NULL
1408 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001409 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001410 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001411 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001412 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001413 if (match_head == NULL)
1414 match_head = compl;
1415 else
glepnira49c0772024-11-30 10:56:30 +01001416 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001417 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001418
glepnirf400a0c2025-01-23 19:55:14 +01001419 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001420 {
1421 if (compl == compl_shown_match || did_find_shown_match)
1422 {
1423 // This item is the shown match or this is the
1424 // first displayed item after the shown match.
1425 compl_shown_match = compl;
1426 did_find_shown_match = TRUE;
1427 shown_match_ok = TRUE;
1428 }
1429 else
1430 // Remember this displayed match for when the
1431 // shown match is just below it.
1432 shown_compl = compl;
1433 cur = i;
1434 }
glepnirf400a0c2025-01-23 19:55:14 +01001435 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001436 {
1437 if (i == 0)
1438 shown_compl = compl;
1439 // Update the maximum fuzzy score and the shown match
1440 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001441 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1442 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001443 {
1444 did_find_shown_match = TRUE;
1445 max_fuzzy_score = compl->cp_score;
1446 if (!compl_no_select)
1447 compl_shown_match = compl;
1448 }
1449
glepnir3af0a8d2025-02-20 22:06:16 +01001450 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001451 {
1452 cur = i;
1453 shown_match_ok = TRUE;
1454 }
1455 }
1456 i++;
glepnir80b66202024-11-27 21:53:53 +01001457 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001458
glepnirf400a0c2025-01-23 19:55:14 +01001459 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001460 {
1461 did_find_shown_match = TRUE;
1462
1463 // When the original text is the shown match don't set
1464 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001465 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001466 shown_match_ok = TRUE;
1467
1468 if (!shown_match_ok && shown_compl != NULL)
1469 {
1470 // The shown match isn't displayed, set it to the
1471 // previously displayed match.
1472 compl_shown_match = shown_compl;
1473 shown_match_ok = TRUE;
1474 }
1475 }
glepnira49c0772024-11-30 10:56:30 +01001476 compl = compl->cp_next;
1477 } while (compl != NULL && !is_first_match(compl));
1478
1479 if (compl_match_arraysize == 0)
1480 return -1;
1481
glepnirc0b7ca42025-02-13 20:27:44 +01001482 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1483 {
1484 compl_shown_match = shown_compl;
1485 shown_match_ok = TRUE;
1486 cur = 0;
1487 }
1488
glepnira49c0772024-11-30 10:56:30 +01001489 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1490 if (compl_match_array == NULL)
1491 return -1;
1492
1493 compl = match_head;
1494 i = 0;
1495 while (compl != NULL)
1496 {
glepnir6e199932024-12-14 21:13:27 +01001497 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1498 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001499 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1500 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1501 compl_match_array[i].pum_score = compl->cp_score;
1502 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1503 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001504 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1505 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001506 match_next = compl->cp_match_next;
1507 compl->cp_match_next = NULL;
1508 compl = match_next;
1509 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001510
zeertzjqd65aa1b2025-01-25 15:29:03 +01001511 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001512 {
1513 for (i = 0; i < compl_match_arraysize; i++)
1514 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001515 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001516 qsort(compl_match_array, (size_t)compl_match_arraysize,
1517 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001518 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001519 }
glepnira218cc62024-06-03 19:32:39 +02001520
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001521 if (!shown_match_ok) // no displayed match at all
1522 cur = -1;
1523
1524 return cur;
1525}
1526
1527/*
1528 * Show the popup menu for the list of matches.
1529 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1530 */
1531 void
1532ins_compl_show_pum(void)
1533{
1534 int i;
1535 int cur = -1;
1536 colnr_T col;
1537
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001538 if (!pum_wanted() || !pum_enough_matches())
1539 return;
1540
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001541 // Update the screen later, before drawing the popup menu over it.
1542 pum_call_update_screen();
1543
1544 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001545 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001546 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001547 else
1548 {
1549 // popup menu already exists, only need to find the current item.
1550 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001551 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001552 || compl_match_array[i].pum_text
1553 == compl_shown_match->cp_text[CPT_ABBR])
1554 {
1555 cur = i;
1556 break;
1557 }
1558 }
1559
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001560 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001561 {
1562#ifdef FEAT_EVAL
1563 if (compl_started && has_completechanged())
1564 trigger_complete_changed_event(cur);
1565#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001566 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001567 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001568
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001569 // In Replace mode when a $ is displayed at the end of the line only
1570 // part of the screen would be updated. We do need to redraw here.
1571 dollar_vcol = -1;
1572
1573 // Compute the screen column of the start of the completed text.
1574 // Use the cursor to get all wrapping and other settings right.
1575 col = curwin->w_cursor.col;
1576 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001577 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001578 pum_display(compl_match_array, compl_match_arraysize, cur);
1579 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001580
glepnircbb46b42024-02-03 18:11:13 +01001581 // After adding leader, set the current match to shown match.
1582 if (compl_started && compl_curr_match != compl_shown_match)
1583 compl_curr_match = compl_shown_match;
1584
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001585#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001586 if (has_completechanged())
1587 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001588#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001589}
1590
1591#define DICT_FIRST (1) // use just first element in "dict"
1592#define DICT_EXACT (2) // "dict" is the exact name of a file
1593
1594/*
glepnir40c1c332024-06-11 19:37:04 +02001595 * Get current completion leader
1596 */
1597 char_u *
1598ins_compl_leader(void)
1599{
John Marriott5e6ea922024-11-23 14:01:57 +01001600 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1601}
1602
1603/*
1604 * Get current completion leader length
1605 */
1606 size_t
1607ins_compl_leader_len(void)
1608{
1609 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001610}
1611
1612/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001613 * Add any identifiers that match the given pattern "pat" in the list of
1614 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001615 */
1616 static void
1617ins_compl_dictionaries(
1618 char_u *dict_start,
1619 char_u *pat,
1620 int flags, // DICT_FIRST and/or DICT_EXACT
1621 int thesaurus) // Thesaurus completion
1622{
1623 char_u *dict = dict_start;
1624 char_u *ptr;
1625 char_u *buf;
1626 regmatch_T regmatch;
1627 char_u **files;
1628 int count;
1629 int save_p_scs;
1630 int dir = compl_direction;
1631
1632 if (*dict == NUL)
1633 {
1634#ifdef FEAT_SPELL
1635 // When 'dictionary' is empty and spell checking is enabled use
1636 // "spell".
1637 if (!thesaurus && curwin->w_p_spell)
1638 dict = (char_u *)"spell";
1639 else
1640#endif
1641 return;
1642 }
1643
1644 buf = alloc(LSIZE);
1645 if (buf == NULL)
1646 return;
1647 regmatch.regprog = NULL; // so that we can goto theend
1648
1649 // If 'infercase' is set, don't use 'smartcase' here
1650 save_p_scs = p_scs;
1651 if (curbuf->b_p_inf)
1652 p_scs = FALSE;
1653
1654 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1655 // to only match at the start of a line. Otherwise just match the
1656 // pattern. Also need to double backslashes.
1657 if (ctrl_x_mode_line_or_eval())
1658 {
1659 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1660 size_t len;
1661
1662 if (pat_esc == NULL)
1663 goto theend;
1664 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001665 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001666 if (ptr == NULL)
1667 {
1668 vim_free(pat_esc);
1669 goto theend;
1670 }
1671 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1672 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1673 vim_free(pat_esc);
1674 vim_free(ptr);
1675 }
1676 else
1677 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001678 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001679 if (regmatch.regprog == NULL)
1680 goto theend;
1681 }
1682
1683 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1684 regmatch.rm_ic = ignorecase(pat);
1685 while (*dict != NUL && !got_int && !compl_interrupted)
1686 {
1687 // copy one dictionary file name into buf
1688 if (flags == DICT_EXACT)
1689 {
1690 count = 1;
1691 files = &dict;
1692 }
1693 else
1694 {
1695 // Expand wildcards in the dictionary name, but do not allow
1696 // backticks (for security, the 'dict' option may have been set in
1697 // a modeline).
1698 copy_option_part(&dict, buf, LSIZE, ",");
1699# ifdef FEAT_SPELL
1700 if (!thesaurus && STRCMP(buf, "spell") == 0)
1701 count = -1;
1702 else
1703# endif
1704 if (vim_strchr(buf, '`') != NULL
1705 || expand_wildcards(1, &buf, &count, &files,
1706 EW_FILE|EW_SILENT) != OK)
1707 count = 0;
1708 }
1709
1710# ifdef FEAT_SPELL
1711 if (count == -1)
1712 {
1713 // Complete from active spelling. Skip "\<" in the pattern, we
1714 // don't use it as a RE.
1715 if (pat[0] == '\\' && pat[1] == '<')
1716 ptr = pat + 2;
1717 else
1718 ptr = pat;
1719 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1720 }
1721 else
1722# endif
1723 if (count > 0) // avoid warning for using "files" uninit
1724 {
1725 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001726 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001727 if (flags != DICT_EXACT)
1728 FreeWild(count, files);
1729 }
1730 if (flags != 0)
1731 break;
1732 }
1733
1734theend:
1735 p_scs = save_p_scs;
1736 vim_regfree(regmatch.regprog);
1737 vim_free(buf);
1738}
1739
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001740/*
1741 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1742 * skipping the word at 'skip_word'. Returns OK on success.
1743 */
1744 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001745thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001746 char_u *fname,
1747 char_u **buf_arg,
1748 int dir,
1749 char_u *skip_word)
1750{
1751 int status = OK;
1752 char_u *ptr;
1753 char_u *wstart;
1754
1755 // Add the other matches on the line
1756 ptr = *buf_arg;
1757 while (!got_int)
1758 {
1759 // Find start of the next word. Skip white
1760 // space and punctuation.
1761 ptr = find_word_start(ptr);
1762 if (*ptr == NUL || *ptr == NL)
1763 break;
1764 wstart = ptr;
1765
1766 // Find end of the word.
1767 if (has_mbyte)
1768 // Japanese words may have characters in
1769 // different classes, only separate words
1770 // with single-byte non-word characters.
1771 while (*ptr != NUL)
1772 {
1773 int l = (*mb_ptr2len)(ptr);
1774
1775 if (l < 2 && !vim_iswordc(*ptr))
1776 break;
1777 ptr += l;
1778 }
1779 else
1780 ptr = find_word_end(ptr);
1781
1782 // Add the word. Skip the regexp match.
1783 if (wstart != skip_word)
1784 {
1785 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001786 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001787 if (status == FAIL)
1788 break;
1789 }
1790 }
1791
1792 *buf_arg = ptr;
1793 return status;
1794}
1795
1796/*
1797 * Process "count" dictionary/thesaurus "files" and add the text matching
1798 * "regmatch".
1799 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001800 static void
1801ins_compl_files(
1802 int count,
1803 char_u **files,
1804 int thesaurus,
1805 int flags,
1806 regmatch_T *regmatch,
1807 char_u *buf,
1808 int *dir)
1809{
1810 char_u *ptr;
1811 int i;
1812 FILE *fp;
1813 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001814 char_u *leader = NULL;
1815 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001816 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001817 int score = 0;
1818 int len = 0;
1819 char_u *line_end = NULL;
1820
1821 if (in_fuzzy_collect)
1822 {
1823 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001824 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001825 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001826
1827 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1828 {
1829 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001830 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001831 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001832 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001833 vim_snprintf((char *)IObuff, IOSIZE,
1834 _("Scanning dictionary: %s"), (char *)files[i]);
1835 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1836 }
1837
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001838 if (fp == NULL)
1839 continue;
1840
1841 // Read dictionary file line by line.
1842 // Check each line for a match.
1843 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001844 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001845 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001846 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001847 {
glepnirf31cfa22025-03-06 21:59:13 +01001848 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001849 {
glepnirf31cfa22025-03-06 21:59:13 +01001850 ptr = regmatch->startp[0];
1851 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1852 : find_word_end(ptr);
1853 add_r = ins_compl_add_infercase(regmatch->startp[0],
1854 (int)(ptr - regmatch->startp[0]),
1855 p_ic, files[i], *dir, FALSE, 0);
1856 if (thesaurus)
1857 {
1858 // For a thesaurus, add all the words in the line
1859 ptr = buf;
1860 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1861 regmatch->startp[0]);
1862 }
1863 if (add_r == OK)
1864 // if dir was BACKWARD then honor it just once
1865 *dir = FORWARD;
1866 else if (add_r == FAIL)
1867 break;
1868 // avoid expensive call to vim_regexec() when at end
1869 // of line
1870 if (*ptr == '\n' || got_int)
1871 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001872 }
glepnirf31cfa22025-03-06 21:59:13 +01001873 }
1874 else if (in_fuzzy_collect && leader_len > 0)
1875 {
1876 line_end = find_line_end(ptr);
1877 while (ptr < line_end)
1878 {
1879 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1880 {
1881 char_u *end_ptr = ctrl_x_mode_line_or_eval()
1882 ? find_line_end(ptr) : find_word_end(ptr);
1883 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
1884 p_ic, files[i], *dir, FALSE, score);
1885 if (add_r == FAIL)
1886 break;
1887 ptr = end_ptr; // start from next word
1888 if (compl_get_longest && ctrl_x_mode_normal()
1889 && compl_first_match->cp_next
1890 && score == compl_first_match->cp_next->cp_score)
1891 compl_num_bests++;
1892 }
glepnirf31cfa22025-03-06 21:59:13 +01001893 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001894 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001895 line_breakcheck();
1896 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001897 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001898 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001899 }
1900}
1901
1902/*
1903 * Find the start of the next word.
1904 * Returns a pointer to the first char of the word. Also stops at a NUL.
1905 */
1906 char_u *
1907find_word_start(char_u *ptr)
1908{
1909 if (has_mbyte)
1910 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1911 ptr += (*mb_ptr2len)(ptr);
1912 else
1913 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1914 ++ptr;
1915 return ptr;
1916}
1917
1918/*
1919 * Find the end of the word. Assumes it starts inside a word.
1920 * Returns a pointer to just after the word.
1921 */
1922 char_u *
1923find_word_end(char_u *ptr)
1924{
1925 int start_class;
1926
1927 if (has_mbyte)
1928 {
1929 start_class = mb_get_class(ptr);
1930 if (start_class > 1)
1931 while (*ptr != NUL)
1932 {
1933 ptr += (*mb_ptr2len)(ptr);
1934 if (mb_get_class(ptr) != start_class)
1935 break;
1936 }
1937 }
1938 else
1939 while (vim_iswordc(*ptr))
1940 ++ptr;
1941 return ptr;
1942}
1943
1944/*
1945 * Find the end of the line, omitting CR and NL at the end.
1946 * Returns a pointer to just after the line.
1947 */
glepnirdd42b052025-03-08 16:52:55 +01001948 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001949find_line_end(char_u *ptr)
1950{
1951 char_u *s;
1952
1953 s = ptr + STRLEN(ptr);
1954 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1955 --s;
1956 return s;
1957}
1958
1959/*
Girish Palyacbe53192025-04-14 22:13:15 +02001960 * Free a completion item in the list
1961 */
1962 static void
1963ins_compl_item_free(compl_T *match)
1964{
1965 int i;
1966
1967 VIM_CLEAR_STRING(match->cp_str);
1968 // several entries may use the same fname, free it just once.
1969 if (match->cp_flags & CP_FREE_FNAME)
1970 vim_free(match->cp_fname);
1971 for (i = 0; i < CPT_COUNT; ++i)
1972 vim_free(match->cp_text[i]);
1973#ifdef FEAT_EVAL
1974 clear_tv(&match->cp_user_data);
1975#endif
1976 vim_free(match);
1977}
1978
1979/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001980 * Free the list of completions
1981 */
1982 static void
1983ins_compl_free(void)
1984{
1985 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001986
John Marriott5e6ea922024-11-23 14:01:57 +01001987 VIM_CLEAR_STRING(compl_pattern);
1988 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001989
1990 if (compl_first_match == NULL)
1991 return;
1992
1993 ins_compl_del_pum();
1994 pum_clear();
1995
1996 compl_curr_match = compl_first_match;
1997 do
1998 {
1999 match = compl_curr_match;
2000 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002001 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002002 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002003 compl_first_match = compl_curr_match = NULL;
2004 compl_shown_match = NULL;
2005 compl_old_match = NULL;
2006}
2007
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002008/*
2009 * Reset/clear the completion state.
2010 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002011 void
2012ins_compl_clear(void)
2013{
2014 compl_cont_status = 0;
2015 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002016 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002017 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002018 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002019 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002020 compl_curr_win = NULL;
2021 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002022 VIM_CLEAR_STRING(compl_pattern);
2023 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002024 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002025 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002026 compl_enter_selects = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02002027 cpt_compl_src_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002028#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002029 // clear v:completed_item
2030 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002031#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002032}
2033
2034/*
2035 * Return TRUE when Insert completion is active.
2036 */
2037 int
2038ins_compl_active(void)
2039{
2040 return compl_started;
2041}
2042
2043/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002044 * Return True when wp is the actual completion window
2045 */
2046 int
glepnircf7f0122025-04-15 19:02:00 +02002047ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002048{
glepnircf7f0122025-04-15 19:02:00 +02002049 return ins_compl_active() && wp == compl_curr_win
2050 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002051}
2052
2053/*
Girish Palyacbe53192025-04-14 22:13:15 +02002054 * Selected one of the matches. When FALSE, the match was either edited or
2055 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002056 */
2057 int
2058ins_compl_used_match(void)
2059{
2060 return compl_used_match;
2061}
2062
2063/*
2064 * Initialize get longest common string.
2065 */
2066 void
2067ins_compl_init_get_longest(void)
2068{
2069 compl_get_longest = FALSE;
2070}
2071
2072/*
2073 * Returns TRUE when insert completion is interrupted.
2074 */
2075 int
2076ins_compl_interrupted(void)
2077{
2078 return compl_interrupted;
2079}
2080
2081/*
2082 * Returns TRUE if the <Enter> key selects a match in the completion popup
2083 * menu.
2084 */
2085 int
2086ins_compl_enter_selects(void)
2087{
2088 return compl_enter_selects;
2089}
2090
2091/*
2092 * Return the column where the text starts that is being completed
2093 */
2094 colnr_T
2095ins_compl_col(void)
2096{
2097 return compl_col;
2098}
2099
2100/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002101 * Return the length in bytes of the text being completed
2102 */
2103 int
2104ins_compl_len(void)
2105{
2106 return compl_length;
2107}
2108
2109/*
glepnir94a045e2025-03-01 16:12:23 +01002110 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2111 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002112 */
2113 static int
2114ins_compl_has_preinsert(void)
2115{
glepnira2c55592025-02-28 17:43:42 +01002116 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002117 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2118 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002119}
2120
2121/*
2122 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2123 * the `compl_ins_end_col` range.
2124 */
2125 int
2126ins_compl_preinsert_effect(void)
2127{
2128 if (!ins_compl_has_preinsert())
2129 return FALSE;
2130
2131 return curwin->w_cursor.col < compl_ins_end_col;
2132}
2133
2134/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002135 * Delete one character before the cursor and show the subset of the matches
2136 * that match the word that is now before the cursor.
2137 * Returns the character to be used, NUL if the work is done and another char
2138 * to be got from the user.
2139 */
2140 int
2141ins_compl_bs(void)
2142{
2143 char_u *line;
2144 char_u *p;
2145
glepniredd4ac32025-01-29 18:53:51 +01002146 if (ins_compl_preinsert_effect())
2147 ins_compl_delete();
2148
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002149 line = ml_get_curline();
2150 p = line + curwin->w_cursor.col;
2151 MB_PTR_BACK(line, p);
2152
2153 // Stop completion when the whole word was deleted. For Omni completion
2154 // allow the word to be deleted, we won't match everything.
2155 // Respect the 'backspace' option.
2156 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002157 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2158 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002159 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2160 - compl_length < 0))
2161 return K_BS;
2162
2163 // Deleted more than what was used to find matches or didn't finish
2164 // finding all matches: need to look for matches all over again.
2165 if (curwin->w_cursor.col <= compl_col + compl_length
2166 || ins_compl_need_restart())
2167 ins_compl_restart();
2168
John Marriott5e6ea922024-11-23 14:01:57 +01002169 VIM_CLEAR_STRING(compl_leader);
2170 compl_leader.length = (size_t)((p - line) - compl_col);
2171 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2172 if (compl_leader.string == NULL)
2173 {
2174 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002175 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002176 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002177
2178 ins_compl_new_leader();
2179 if (compl_shown_match != NULL)
2180 // Make sure current match is not a hidden item.
2181 compl_curr_match = compl_shown_match;
2182 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002183}
2184
2185/*
2186 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2187 * be called.
2188 */
2189 static int
2190ins_compl_need_restart(void)
2191{
2192 // Return TRUE if we didn't complete finding matches or when the
2193 // 'completefunc' returned "always" in the "refresh" dictionary item.
2194 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002195 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002196 && compl_opt_refresh_always);
2197}
2198
2199/*
2200 * Called after changing "compl_leader".
2201 * Show the popup menu with a different set of matches.
2202 * May also search for matches again if the previous search was interrupted.
2203 */
2204 static void
2205ins_compl_new_leader(void)
2206{
2207 ins_compl_del_pum();
2208 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002209 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002210 compl_used_match = FALSE;
2211
2212 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002213 {
John Marriott5e6ea922024-11-23 14:01:57 +01002214 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002215 if (is_cpt_func_refresh_always())
2216 cpt_compl_refresh();
2217 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002218 else
2219 {
2220#ifdef FEAT_SPELL
2221 spell_bad_len = 0; // need to redetect bad word
2222#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002223 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002224 // the popup menu display the changed text before the cursor. Set
2225 // "compl_restarting" to avoid that the first match is inserted.
2226 pum_call_update_screen();
2227#ifdef FEAT_GUI
2228 if (gui.in_use)
2229 {
2230 // Show the cursor after the match, not after the redrawn text.
2231 setcursor();
2232 out_flush_cursor(FALSE, FALSE);
2233 }
2234#endif
2235 compl_restarting = TRUE;
2236 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2237 compl_cont_status = 0;
2238 compl_restarting = FALSE;
2239 }
2240
glepnir44180412025-02-20 22:09:48 +01002241 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002242
2243 // Show the popup menu with a different set of matches.
2244 ins_compl_show_pum();
2245
2246 // Don't let Enter select the original text when there is no popup menu.
2247 if (compl_match_array == NULL)
2248 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002249 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2250 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002251}
2252
2253/*
2254 * Return the length of the completion, from the completion start column to
2255 * the cursor column. Making sure it never goes below zero.
2256 */
2257 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002258get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002259{
2260 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002261 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002262}
2263
2264/*
2265 * Append one character to the match leader. May reduce the number of
2266 * matches.
2267 */
2268 void
2269ins_compl_addleader(int c)
2270{
2271 int cc;
2272
glepniredd4ac32025-01-29 18:53:51 +01002273 if (ins_compl_preinsert_effect())
2274 ins_compl_delete();
2275
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002276 if (stop_arrow() == FAIL)
2277 return;
2278 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2279 {
2280 char_u buf[MB_MAXBYTES + 1];
2281
2282 (*mb_char2bytes)(c, buf);
2283 buf[cc] = NUL;
2284 ins_char_bytes(buf, cc);
2285 if (compl_opt_refresh_always)
2286 AppendToRedobuff(buf);
2287 }
2288 else
2289 {
2290 ins_char(c);
2291 if (compl_opt_refresh_always)
2292 AppendCharToRedobuff(c);
2293 }
2294
2295 // If we didn't complete finding matches we must search again.
2296 if (ins_compl_need_restart())
2297 ins_compl_restart();
2298
2299 // When 'always' is set, don't reset compl_leader. While completing,
2300 // cursor doesn't point original position, changing compl_leader would
2301 // break redo.
2302 if (!compl_opt_refresh_always)
2303 {
John Marriott5e6ea922024-11-23 14:01:57 +01002304 VIM_CLEAR_STRING(compl_leader);
2305 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2306 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2307 compl_leader.length);
2308 if (compl_leader.string == NULL)
2309 {
2310 compl_leader.length = 0;
2311 return;
2312 }
2313
2314 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002315 }
2316}
2317
2318/*
2319 * Setup for finding completions again without leaving CTRL-X mode. Used when
2320 * BS or a key was typed while still searching for matches.
2321 */
2322 static void
2323ins_compl_restart(void)
2324{
2325 ins_compl_free();
2326 compl_started = FALSE;
2327 compl_matches = 0;
2328 compl_cont_status = 0;
2329 compl_cont_mode = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02002330 cpt_compl_src_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002331}
2332
2333/*
2334 * Set the first match, the original text.
2335 */
2336 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002337ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002338{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002339 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002340 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2341 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002342 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002343 {
John Marriott5e6ea922024-11-23 14:01:57 +01002344 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002345 if (p != NULL)
2346 {
John Marriott5e6ea922024-11-23 14:01:57 +01002347 VIM_CLEAR_STRING(compl_first_match->cp_str);
2348 compl_first_match->cp_str.string = p;
2349 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002350 }
2351 }
2352 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002353 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002354 {
John Marriott5e6ea922024-11-23 14:01:57 +01002355 char_u *p = vim_strnsave(str, len);
2356 if (p != NULL)
2357 {
2358 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2359 compl_first_match->cp_prev->cp_str.string = p;
2360 compl_first_match->cp_prev->cp_str.length = len;
2361 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002362 }
2363}
2364
2365/*
2366 * Append one character to the match leader. May reduce the number of
2367 * matches.
2368 */
2369 void
2370ins_compl_addfrommatch(void)
2371{
2372 char_u *p;
2373 int len = (int)curwin->w_cursor.col - (int)compl_col;
2374 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002375
John Marriott5e6ea922024-11-23 14:01:57 +01002376 p = compl_shown_match->cp_str.string;
2377 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002378 {
John Marriott5e6ea922024-11-23 14:01:57 +01002379 size_t plen;
2380 compl_T *cp;
2381
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002382 // When still at the original match use the first entry that matches
2383 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002384 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002385 return;
2386
2387 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002388 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002389 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002390 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002391 {
John Marriott5e6ea922024-11-23 14:01:57 +01002392 if (compl_leader.string == NULL
2393 || ins_compl_equal(cp, compl_leader.string,
2394 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002395 {
John Marriott5e6ea922024-11-23 14:01:57 +01002396 p = cp->cp_str.string;
2397 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002398 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002399 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002400 }
John Marriott5e6ea922024-11-23 14:01:57 +01002401 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002402 return;
2403 }
2404 p += len;
2405 c = PTR2CHAR(p);
2406 ins_compl_addleader(c);
2407}
2408
2409/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002410 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002411 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2412 * compl_cont_mode and compl_cont_status.
2413 * Returns TRUE when the character is not to be inserted.
2414 */
2415 static int
2416set_ctrl_x_mode(int c)
2417{
2418 int retval = FALSE;
2419
2420 switch (c)
2421 {
2422 case Ctrl_E:
2423 case Ctrl_Y:
2424 // scroll the window one line up or down
2425 ctrl_x_mode = CTRL_X_SCROLL;
2426 if (!(State & REPLACE_FLAG))
2427 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2428 else
2429 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2430 edit_submode_pre = NULL;
2431 showmode();
2432 break;
2433 case Ctrl_L:
2434 // complete whole line
2435 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2436 break;
2437 case Ctrl_F:
2438 // complete filenames
2439 ctrl_x_mode = CTRL_X_FILES;
2440 break;
2441 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002442 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002443 ctrl_x_mode = CTRL_X_DICTIONARY;
2444 break;
2445 case Ctrl_R:
2446 // Register insertion without exiting CTRL-X mode
2447 // Simply allow ^R to happen without affecting ^X mode
2448 break;
2449 case Ctrl_T:
2450 // complete words from a thesaurus
2451 ctrl_x_mode = CTRL_X_THESAURUS;
2452 break;
2453#ifdef FEAT_COMPL_FUNC
2454 case Ctrl_U:
2455 // user defined completion
2456 ctrl_x_mode = CTRL_X_FUNCTION;
2457 break;
2458 case Ctrl_O:
2459 // omni completion
2460 ctrl_x_mode = CTRL_X_OMNI;
2461 break;
2462#endif
2463 case 's':
2464 case Ctrl_S:
2465 // complete spelling suggestions
2466 ctrl_x_mode = CTRL_X_SPELL;
2467#ifdef FEAT_SPELL
2468 ++emsg_off; // Avoid getting the E756 error twice.
2469 spell_back_to_badword();
2470 --emsg_off;
2471#endif
2472 break;
2473 case Ctrl_RSB:
2474 // complete tag names
2475 ctrl_x_mode = CTRL_X_TAGS;
2476 break;
2477#ifdef FEAT_FIND_ID
2478 case Ctrl_I:
2479 case K_S_TAB:
2480 // complete keywords from included files
2481 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2482 break;
2483 case Ctrl_D:
2484 // complete definitions from included files
2485 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2486 break;
2487#endif
2488 case Ctrl_V:
2489 case Ctrl_Q:
2490 // complete vim commands
2491 ctrl_x_mode = CTRL_X_CMDLINE;
2492 break;
2493 case Ctrl_Z:
2494 // stop completion
2495 ctrl_x_mode = CTRL_X_NORMAL;
2496 edit_submode = NULL;
2497 showmode();
2498 retval = TRUE;
2499 break;
2500 case Ctrl_P:
2501 case Ctrl_N:
2502 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2503 // just started ^X mode, or there were enough ^X's to cancel
2504 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2505 // do normal expansion when interrupting a different mode (say
2506 // ^X^F^X^P or ^P^X^X^P, see below)
2507 // nothing changes if interrupting mode 0, (eg, the flag
2508 // doesn't change when going to ADDING mode -- Acevedo
2509 if (!(compl_cont_status & CONT_INTRPT))
2510 compl_cont_status |= CONT_LOCAL;
2511 else if (compl_cont_mode != 0)
2512 compl_cont_status &= ~CONT_LOCAL;
2513 // FALLTHROUGH
2514 default:
2515 // If we have typed at least 2 ^X's... for modes != 0, we set
2516 // compl_cont_status = 0 (eg, as if we had just started ^X
2517 // mode).
2518 // For mode 0, we set "compl_cont_mode" to an impossible
2519 // value, in both cases ^X^X can be used to restart the same
2520 // mode (avoiding ADDING mode).
2521 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2522 // 'complete' and local ^P expansions respectively.
2523 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2524 // mode -- Acevedo
2525 if (c == Ctrl_X)
2526 {
2527 if (compl_cont_mode != 0)
2528 compl_cont_status = 0;
2529 else
2530 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2531 }
2532 ctrl_x_mode = CTRL_X_NORMAL;
2533 edit_submode = NULL;
2534 showmode();
2535 break;
2536 }
2537
2538 return retval;
2539}
2540
2541/*
glepnir1c5a1202024-12-04 20:27:34 +01002542 * Trigger CompleteDone event and adds relevant information to v:event
2543 */
2544 static void
2545trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2546{
2547#if defined(FEAT_EVAL)
2548 save_v_event_T save_v_event;
2549 dict_T *v_event = get_v_event(&save_v_event);
2550 char_u *mode_str = NULL;
2551
2552 mode = mode & ~CTRL_X_WANT_IDENT;
2553 if (ctrl_x_mode_names[mode])
2554 mode_str = (char_u *)ctrl_x_mode_names[mode];
2555
2556 (void)dict_add_string(v_event, "complete_word",
2557 word == NULL ? (char_u *)"" : word);
2558 (void)dict_add_string(v_event, "complete_type",
2559 mode_str != NULL ? mode_str : (char_u *)"");
2560
2561 dict_set_items_ro(v_event);
2562#endif
2563 ins_apply_autocmds(EVENT_COMPLETEDONE);
2564
2565#if defined(FEAT_EVAL)
2566 restore_v_event(v_event, &save_v_event);
2567#endif
2568}
2569
2570/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002571 * Stop insert completion mode
2572 */
2573 static int
2574ins_compl_stop(int c, int prev_mode, int retval)
2575{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002576 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002577 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002578
glepnir84a75032025-03-15 09:59:22 +01002579 // Remove pre-inserted text when present.
2580 if (ins_compl_preinsert_effect())
2581 ins_compl_delete();
2582
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002583 // Get here when we have finished typing a sequence of ^N and
2584 // ^P or other completion characters in CTRL-X mode. Free up
2585 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002586 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002587 {
glepnir40891ba2025-02-10 22:18:00 +01002588 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002589
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002590 // If any of the original typed text has been changed, eg when
2591 // ignorecase is set, we must add back-spaces to the redo
2592 // buffer. We add as few as necessary to delete just the part
2593 // of the original text that has changed.
2594 // When using the longest match, edited the match or used
2595 // CTRL-E then don't use the current match.
2596 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002597 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002598 ins_compl_fixRedoBufForLeader(ptr);
2599 }
2600
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002601 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002602
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002603 // When completing whole lines: fix indent for 'cindent'.
2604 // Otherwise, break line if it's too long.
2605 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2606 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002607 // re-indent the current line
2608 if (want_cindent)
2609 {
2610 do_c_expr_indent();
2611 want_cindent = FALSE; // don't do it again
2612 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002613 }
2614 else
2615 {
2616 int prev_col = curwin->w_cursor.col;
2617
2618 // put the cursor on the last char, for 'tw' formatting
2619 if (prev_col > 0)
2620 dec_cursor();
2621 // only format when something was inserted
2622 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2623 insertchar(NUL, 0, -1);
2624 if (prev_col > 0
2625 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2626 inc_cursor();
2627 }
2628
2629 // If the popup menu is displayed pressing CTRL-Y means accepting
2630 // the selection without inserting anything. When
2631 // compl_enter_selects is set the Enter key does the same.
2632 if ((c == Ctrl_Y || (compl_enter_selects
2633 && (c == CAR || c == K_KENTER || c == NL)))
2634 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002635 {
2636 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002637 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002638 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002639
2640 // CTRL-E means completion is Ended, go back to the typed text.
2641 // but only do this, if the Popup is still visible
2642 if (c == Ctrl_E)
2643 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002644 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002645 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002646
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002647 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002648 if (compl_leader.string != NULL)
2649 {
2650 p = compl_leader.string;
2651 plen = compl_leader.length;
2652 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002653 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002654 {
2655 p = compl_orig_text.string;
2656 plen = compl_orig_text.length;
2657 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002658 if (p != NULL)
2659 {
2660 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002661
John Marriott5e6ea922024-11-23 14:01:57 +01002662 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002663 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002664 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002665 retval = TRUE;
2666 }
2667
glepnir001c26c2025-02-02 09:36:22 +01002668 if ((c == Ctrl_W || c == Ctrl_U) && ins_compl_preinsert_effect())
2669 ins_compl_delete();
2670
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002671 auto_format(FALSE, TRUE);
2672
2673 // Trigger the CompleteDonePre event to give scripts a chance to
2674 // act upon the completion before clearing the info, and restore
2675 // ctrl_x_mode, so that complete_info() can be used.
2676 ctrl_x_mode = prev_mode;
2677 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2678
2679 ins_compl_free();
2680 compl_started = FALSE;
2681 compl_matches = 0;
2682 if (!shortmess(SHM_COMPLETIONMENU))
2683 msg_clr_cmdline(); // necessary for "noshowmode"
2684 ctrl_x_mode = CTRL_X_NORMAL;
2685 compl_enter_selects = FALSE;
2686 if (edit_submode != NULL)
2687 {
2688 edit_submode = NULL;
2689 showmode();
2690 }
2691
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002692 if (c == Ctrl_C && cmdwin_type != 0)
2693 // Avoid the popup menu remains displayed when leaving the
2694 // command line window.
2695 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002696 // Indent now if a key was typed that is in 'cinkeys'.
2697 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2698 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002699 // Trigger the CompleteDone event to give scripts a chance to act
2700 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002701 trigger_complete_done_event(prev_mode, word);
2702 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002703
2704 return retval;
2705}
2706
2707/*
glepnircf7f0122025-04-15 19:02:00 +02002708 * Cancel completion.
2709 */
2710 int
2711ins_compl_cancel(void)
2712{
2713 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2714}
2715
2716/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002717 * Prepare for Insert mode completion, or stop it.
2718 * Called just after typing a character in Insert mode.
2719 * Returns TRUE when the character is not to be inserted;
2720 */
2721 int
2722ins_compl_prep(int c)
2723{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002724 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002725 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002726
2727 // Forget any previous 'special' messages if this is actually
2728 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2729 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2730 edit_submode_extra = NULL;
2731
zeertzjq440d4cb2023-03-02 17:51:32 +00002732 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002733 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002734 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002735 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002736 return retval;
2737
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002738#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002739 // Ignore mouse events in a popup window
2740 if (is_mouse_key(c))
2741 {
2742 // Ignore drag and release events, the position does not need to be in
2743 // the popup and it may have just closed.
2744 if (c == K_LEFTRELEASE
2745 || c == K_LEFTRELEASE_NM
2746 || c == K_MIDDLERELEASE
2747 || c == K_RIGHTRELEASE
2748 || c == K_X1RELEASE
2749 || c == K_X2RELEASE
2750 || c == K_LEFTDRAG
2751 || c == K_MIDDLEDRAG
2752 || c == K_RIGHTDRAG
2753 || c == K_X1DRAG
2754 || c == K_X2DRAG)
2755 return retval;
2756 if (popup_visible)
2757 {
2758 int row = mouse_row;
2759 int col = mouse_col;
2760 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2761
2762 if (wp != NULL && WIN_IS_POPUP(wp))
2763 return retval;
2764 }
2765 }
2766#endif
2767
zeertzjqdca29d92021-08-31 19:12:51 +02002768 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2769 {
2770 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2771 || !vim_is_ctrl_x_key(c))
2772 {
2773 // Not starting another completion mode.
2774 ctrl_x_mode = CTRL_X_CMDLINE;
2775
2776 // CTRL-X CTRL-Z should stop completion without inserting anything
2777 if (c == Ctrl_Z)
2778 retval = TRUE;
2779 }
2780 else
2781 {
2782 ctrl_x_mode = CTRL_X_CMDLINE;
2783
2784 // Other CTRL-X keys first stop completion, then start another
2785 // completion mode.
2786 ins_compl_prep(' ');
2787 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2788 }
2789 }
2790
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002791 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002792 if (ctrl_x_mode_not_defined_yet()
2793 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002794 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002795 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002796 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002797 }
2798
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002799 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002800 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2801 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002802 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002803 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002804 {
2805 // We're already in CTRL-X mode, do we stay in it?
2806 if (!vim_is_ctrl_x_key(c))
2807 {
glepnir40891ba2025-02-10 22:18:00 +01002808 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002809 edit_submode = NULL;
2810 }
2811 showmode();
2812 }
2813
2814 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2815 {
2816 // Show error message from attempted keyword completion (probably
2817 // 'Pattern not found') until another key is hit, then go back to
2818 // showing what mode we are in.
2819 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002820 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002821 && c != Ctrl_R && !ins_compl_pum_key(c))
2822 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002823 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002824 }
2825 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2826 // Trigger the CompleteDone event to give scripts a chance to act
2827 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002828 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002829
LemonBoy2bf52dd2022-04-09 18:17:34 +01002830 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002831
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002832 // reset continue_* if we left expansion-mode, if we stay they'll be
2833 // (re)set properly in ins_complete()
2834 if (!vim_is_ctrl_x_key(c))
2835 {
2836 compl_cont_status = 0;
2837 compl_cont_mode = 0;
2838 }
2839
2840 return retval;
2841}
2842
2843/*
2844 * Fix the redo buffer for the completion leader replacing some of the typed
2845 * text. This inserts backspaces and appends the changed text.
2846 * "ptr" is the known leader text or NUL.
2847 */
2848 static void
2849ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2850{
John Marriott5e6ea922024-11-23 14:01:57 +01002851 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002852 char_u *p;
2853 char_u *ptr = ptr_arg;
2854
2855 if (ptr == NULL)
2856 {
John Marriott5e6ea922024-11-23 14:01:57 +01002857 if (compl_leader.string != NULL)
2858 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002859 else
2860 return; // nothing to do
2861 }
John Marriott5e6ea922024-11-23 14:01:57 +01002862 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002863 {
John Marriott5e6ea922024-11-23 14:01:57 +01002864 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002865 // Find length of common prefix between original text and new completion
2866 while (p[len] != NUL && p[len] == ptr[len])
2867 len++;
2868 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002869 if (len > 0)
2870 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002871 // Add backspace characters for each remaining character in
2872 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002873 for (p += len; *p != NUL; MB_PTR_ADV(p))
2874 AppendCharToRedobuff(K_BS);
2875 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002876 if (ptr != NULL)
2877 AppendToRedobuffLit(ptr + len, -1);
2878}
2879
2880/*
2881 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2882 * (depending on flag) starting from buf and looking for a non-scanned
2883 * buffer (other than curbuf). curbuf is special, if it is called with
2884 * buf=curbuf then it has to be the first call for a given flag/expansion.
2885 *
2886 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2887 */
2888 static buf_T *
2889ins_compl_next_buf(buf_T *buf, int flag)
2890{
2891 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01002892 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002893
2894 if (flag == 'w') // just windows
2895 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002896 if (buf == curbuf || !win_valid(wp))
2897 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002898 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01002899
2900 while (TRUE)
2901 {
2902 // Move to next window (wrap to first window if at the end)
2903 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
2904 // Break if we're back at start or found an unscanned buffer
2905 if (wp == curwin || !wp->w_buffer->b_scanned)
2906 break;
2907 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002908 buf = wp->w_buffer;
2909 }
2910 else
glepnir40891ba2025-02-10 22:18:00 +01002911 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002912 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2913 // (unlisted buffers)
2914 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01002915 while (TRUE)
2916 {
2917 // Move to next buffer (wrap to first buffer if at the end)
2918 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
2919 // Break if we're back at start buffer
2920 if (buf == curbuf)
2921 break;
2922
2923 // Check buffer conditions based on flag
2924 if (flag == 'U')
2925 skip_buffer = buf->b_p_bl;
2926 else
2927 skip_buffer = !buf->b_p_bl ||
2928 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
2929
2930 // Break if we found a buffer that matches our criteria
2931 if (!skip_buffer && !buf->b_scanned)
2932 break;
2933 }
2934 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002935 return buf;
2936}
2937
2938#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002939
2940# ifdef FEAT_EVAL
2941static callback_T cfu_cb; // 'completefunc' callback function
2942static callback_T ofu_cb; // 'omnifunc' callback function
2943static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2944# endif
2945
2946/*
2947 * Copy a global callback function to a buffer local callback.
2948 */
2949 static void
2950copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2951{
2952 free_callback(bufcb);
2953 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2954 copy_callback(bufcb, globcb);
2955}
2956
2957/*
2958 * Parse the 'completefunc' option value and set the callback function.
2959 * Invoked when the 'completefunc' option is set. The option value can be a
2960 * name of a function (string), or function(<name>) or funcref(<name>) or a
2961 * lambda expression.
2962 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002963 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002964did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002965{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002966 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2967 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002968
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002969 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002970
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002971 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002972}
2973
2974/*
2975 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002976 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002977 */
2978 void
2979set_buflocal_cfu_callback(buf_T *buf UNUSED)
2980{
2981# ifdef FEAT_EVAL
2982 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2983# endif
2984}
2985
2986/*
2987 * Parse the 'omnifunc' option value and set the callback function.
2988 * Invoked when the 'omnifunc' option is set. The option value can be a
2989 * name of a function (string), or function(<name>) or funcref(<name>) or a
2990 * lambda expression.
2991 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002992 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002993did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002994{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002995 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2996 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002997
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002998 set_buflocal_ofu_callback(curbuf);
2999 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003000}
3001
3002/*
3003 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003004 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003005 */
3006 void
3007set_buflocal_ofu_callback(buf_T *buf UNUSED)
3008{
3009# ifdef FEAT_EVAL
3010 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3011# endif
3012}
3013
3014/*
3015 * Parse the 'thesaurusfunc' option value and set the callback function.
3016 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3017 * name of a function (string), or function(<name>) or funcref(<name>) or a
3018 * lambda expression.
3019 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003020 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003021did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003022{
3023 int retval;
3024
zeertzjq6eda2692024-11-03 09:23:33 +01003025 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003026 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003027 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3028 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003029 else
3030 {
3031 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003032 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003033 // when using :set, free the local callback
3034 if (!(args->os_flags & OPT_GLOBAL))
3035 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003036 }
3037
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003038 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003039}
3040
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003041/*
3042 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003043 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003044 */
3045 int
3046set_ref_in_insexpand_funcs(int copyID)
3047{
3048 int abort = FALSE;
3049
3050 abort = set_ref_in_callback(&cfu_cb, copyID);
3051 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3052 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3053
3054 return abort;
3055}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003056
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003057/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003058 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003059 */
3060 static char_u *
3061get_complete_funcname(int type)
3062{
3063 switch (type)
3064 {
3065 case CTRL_X_FUNCTION:
3066 return curbuf->b_p_cfu;
3067 case CTRL_X_OMNI:
3068 return curbuf->b_p_ofu;
3069 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003070 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003071 default:
3072 return (char_u *)"";
3073 }
3074}
3075
3076/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003077 * Get the callback to use for insert mode completion.
3078 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003079 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003080get_insert_callback(int type)
3081{
3082 if (type == CTRL_X_FUNCTION)
3083 return &curbuf->b_cfu_cb;
3084 if (type == CTRL_X_OMNI)
3085 return &curbuf->b_ofu_cb;
3086 // CTRL_X_THESAURUS
3087 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3088}
3089
3090/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003091 * Execute user defined complete function 'completefunc', 'omnifunc' or
3092 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003093 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3094 * Callback function "cb" is set if triggered by a function in the 'cpt'
3095 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003096 */
3097 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003098expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003099{
3100 list_T *matchlist = NULL;
3101 dict_T *matchdict = NULL;
3102 typval_T args[3];
3103 char_u *funcname;
3104 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003105 typval_T rettv;
3106 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003107 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003108 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003109
Girish Palyacbe53192025-04-14 22:13:15 +02003110 if (!is_cpt_function)
3111 {
3112 funcname = get_complete_funcname(type);
3113 if (*funcname == NUL)
3114 return;
3115 cb = get_insert_callback(type);
3116 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003117
3118 // Call 'completefunc' to obtain the list of matches.
3119 args[0].v_type = VAR_NUMBER;
3120 args[0].vval.v_number = 0;
3121 args[1].v_type = VAR_STRING;
3122 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3123 args[2].v_type = VAR_UNKNOWN;
3124
3125 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003126 // Lock the text to avoid weird things from happening. Also disallow
3127 // switching to another window, it should not be needed and may end up in
3128 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003129 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003130
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003131 retval = call_callback(cb, 0, &rettv, 2, args);
3132
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003133 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003134 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003135 {
3136 switch (rettv.v_type)
3137 {
3138 case VAR_LIST:
3139 matchlist = rettv.vval.v_list;
3140 break;
3141 case VAR_DICT:
3142 matchdict = rettv.vval.v_dict;
3143 break;
3144 case VAR_SPECIAL:
3145 if (rettv.vval.v_number == VVAL_NONE)
3146 compl_opt_suppress_empty = TRUE;
3147 // FALLTHROUGH
3148 default:
3149 // TODO: Give error message?
3150 clear_tv(&rettv);
3151 break;
3152 }
3153 }
zeertzjqcfe45652022-05-27 17:26:55 +01003154 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003155
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003156 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003157 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003158 validate_cursor();
3159 if (!EQUAL_POS(curwin->w_cursor, pos))
3160 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003161 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003162 goto theend;
3163 }
3164
3165 if (matchlist != NULL)
3166 ins_compl_add_list(matchlist);
3167 else if (matchdict != NULL)
3168 ins_compl_add_dict(matchdict);
3169
3170theend:
3171 // Restore State, it might have been changed.
3172 State = save_State;
3173
3174 if (matchdict != NULL)
3175 dict_unref(matchdict);
3176 if (matchlist != NULL)
3177 list_unref(matchlist);
3178}
3179#endif // FEAT_COMPL_FUNC
3180
3181#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003182
3183 static inline int
3184get_user_highlight_attr(char_u *hlname)
3185{
3186 if (hlname != NULL && *hlname != NUL)
3187 return syn_name2attr(hlname);
3188 return -1;
3189}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003190/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003191 * Add a match to the list of matches from a typeval_T.
3192 * If the given string is already in the list of completions, then return
3193 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3194 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003195 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003196 */
3197 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003198ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003199{
3200 char_u *word;
3201 int dup = FALSE;
3202 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003203 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003204 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003205 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003206 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003207 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003208 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003209 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003210
Bram Moolenaar08928322020-01-04 14:32:48 +01003211 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003212 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3213 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003214 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3215 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3216 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3217 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3218 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003219
glepnir0fe17f82024-10-08 22:26:44 +02003220 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003221 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003222
3223 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003224 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003225
Bram Moolenaard61efa52022-07-23 09:52:04 +01003226 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3227 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3228 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003229 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003230 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3231 dup = dict_get_number(tv->vval.v_dict, "dup");
3232 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3233 empty = dict_get_number(tv->vval.v_dict, "empty");
3234 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3235 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003236 flags |= CP_EQUAL;
3237 }
3238 else
3239 {
3240 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003241 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003242 }
3243 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003244 {
3245 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003246 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003247 }
glepnir508e7852024-07-25 21:39:08 +02003248 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003249 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003250 if (status != OK)
3251 clear_tv(&user_data);
3252 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003253}
3254
3255/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003256 * Add completions from a list.
3257 */
3258 static void
3259ins_compl_add_list(list_T *list)
3260{
3261 listitem_T *li;
3262 int dir = compl_direction;
3263
3264 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003265 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003266 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003267 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003268 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003269 // if dir was BACKWARD then honor it just once
3270 dir = FORWARD;
3271 else if (did_emsg)
3272 break;
3273 }
3274}
3275
3276/*
3277 * Add completions from a dict.
3278 */
3279 static void
3280ins_compl_add_dict(dict_T *dict)
3281{
3282 dictitem_T *di_refresh;
3283 dictitem_T *di_words;
3284
3285 // Check for optional "refresh" item.
3286 compl_opt_refresh_always = FALSE;
3287 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3288 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3289 {
3290 char_u *v = di_refresh->di_tv.vval.v_string;
3291
3292 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3293 compl_opt_refresh_always = TRUE;
3294 }
3295
3296 // Add completions from a "words" list.
3297 di_words = dict_find(dict, (char_u *)"words", 5);
3298 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3299 ins_compl_add_list(di_words->di_tv.vval.v_list);
3300}
3301
3302/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003303 * Start completion for the complete() function.
3304 * "startcol" is where the matched text starts (1 is first column).
3305 * "list" is the list of matches.
3306 */
3307 static void
3308set_completion(colnr_T startcol, list_T *list)
3309{
3310 int save_w_wrow = curwin->w_wrow;
3311 int save_w_leftcol = curwin->w_leftcol;
3312 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003313 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003314 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3315 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3316 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003317
3318 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003319 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003320 ins_compl_prep(' ');
3321 ins_compl_clear();
3322 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003323 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003324
3325 compl_direction = FORWARD;
3326 if (startcol > curwin->w_cursor.col)
3327 startcol = curwin->w_cursor.col;
3328 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003329 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003330 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3331 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003332 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3333 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003334 if (p_ic)
3335 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003336 if (compl_orig_text.string == NULL)
3337 {
3338 compl_orig_text.length = 0;
3339 return;
3340 }
3341 compl_orig_text.length = (size_t)compl_length;
3342 if (ins_compl_add(compl_orig_text.string,
3343 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
glepnirf31cfa22025-03-06 21:59:13 +01003344 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003345 return;
3346
3347 ctrl_x_mode = CTRL_X_EVAL;
3348
3349 ins_compl_add_list(list);
3350 compl_matches = ins_compl_make_cyclic();
3351 compl_started = TRUE;
3352 compl_used_match = TRUE;
3353 compl_cont_status = 0;
3354
3355 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003356 int no_select = compl_no_select || compl_longest;
3357 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003358 {
3359 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003360 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003361 // Down/Up has no real effect.
3362 ins_complete(K_UP, FALSE);
3363 }
3364 else
3365 ins_complete(Ctrl_N, FALSE);
3366 compl_enter_selects = compl_no_insert;
3367
3368 // Lazily show the popup menu, unless we got interrupted.
3369 if (!compl_interrupted)
3370 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003371 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003372 out_flush();
3373}
3374
3375/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003376 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003377 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003378 void
3379f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003380{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003381 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003382
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003383 if (in_vim9script()
3384 && (check_for_number_arg(argvars, 0) == FAIL
3385 || check_for_list_arg(argvars, 1) == FAIL))
3386 return;
3387
Bram Moolenaar24959102022-05-07 20:01:16 +01003388 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003389 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003390 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003391 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003392 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003393
3394 // Check for undo allowed here, because if something was already inserted
3395 // the line was already saved for undo and this check isn't done.
3396 if (!undo_allowed())
3397 return;
3398
Bram Moolenaard83392a2022-09-01 12:22:46 +01003399 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003400 {
3401 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3402 if (startcol > 0)
3403 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003404 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003405}
3406
3407/*
3408 * "complete_add()" function
3409 */
3410 void
3411f_complete_add(typval_T *argvars, typval_T *rettv)
3412{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003413 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003414 return;
3415
Bram Moolenaar440cf092021-04-03 20:13:30 +02003416 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003417}
3418
3419/*
3420 * "complete_check()" function
3421 */
3422 void
3423f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3424{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003425 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003426 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003427
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003428 ins_compl_check_keys(0, TRUE);
3429 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003430
3431 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003432}
3433
3434/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003435 * Return Insert completion mode name string
3436 */
3437 static char_u *
3438ins_compl_mode(void)
3439{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003440 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003441 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3442
3443 return (char_u *)"";
3444}
3445
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003446/*
3447 * Assign the sequence number to all the completion matches which don't have
3448 * one assigned yet.
3449 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003450 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003451ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003452{
3453 int number = 0;
3454 compl_T *match;
3455
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003456 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003457 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003458 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003459 // This should normally succeed already at the first loop
3460 // cycle, so it's fast!
3461 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003462 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003463 if (match->cp_number != -1)
3464 {
3465 number = match->cp_number;
3466 break;
3467 }
3468 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003469 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003470 for (match = match->cp_next;
3471 match != NULL && match->cp_number == -1;
3472 match = match->cp_next)
3473 match->cp_number = ++number;
3474 }
3475 else // BACKWARD
3476 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003477 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003478 // number. This should normally succeed already at the
3479 // first loop cycle, so it's fast!
3480 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003481 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003482 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003483 if (match->cp_number != -1)
3484 {
3485 number = match->cp_number;
3486 break;
3487 }
glepnir40891ba2025-02-10 22:18:00 +01003488 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003489 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003490 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003491 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003492 for (match = match->cp_prev; match
3493 && match->cp_number == -1;
3494 match = match->cp_prev)
3495 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003496 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003497 }
3498}
3499
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003500/*
glepnir037b0282025-01-16 14:37:44 +01003501 * Fill the dict of complete_info
3502 */
3503 static void
3504fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3505{
3506 dict_add_string(di, "word", match->cp_str.string);
3507 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3508 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3509 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3510 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3511 if (add_match)
3512 dict_add_bool(di, "match", match->cp_in_match_array);
3513 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3514 // Add an empty string for backwards compatibility
3515 dict_add_string(di, "user_data", (char_u *)"");
3516 else
3517 dict_add_tv(di, "user_data", &match->cp_user_data);
3518}
3519
3520/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003521 * Get complete information
3522 */
3523 static void
3524get_complete_info(list_T *what_list, dict_T *retdict)
3525{
3526 int ret = OK;
3527 listitem_T *item;
3528#define CI_WHAT_MODE 0x01
3529#define CI_WHAT_PUM_VISIBLE 0x02
3530#define CI_WHAT_ITEMS 0x04
3531#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003532#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003533#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003534#define CI_WHAT_ALL 0xff
3535 int what_flag;
3536
3537 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003538 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003539 else
3540 {
3541 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003542 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003543 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003544 {
3545 char_u *what = tv_get_string(&item->li_tv);
3546
3547 if (STRCMP(what, "mode") == 0)
3548 what_flag |= CI_WHAT_MODE;
3549 else if (STRCMP(what, "pum_visible") == 0)
3550 what_flag |= CI_WHAT_PUM_VISIBLE;
3551 else if (STRCMP(what, "items") == 0)
3552 what_flag |= CI_WHAT_ITEMS;
3553 else if (STRCMP(what, "selected") == 0)
3554 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003555 else if (STRCMP(what, "completed") == 0)
3556 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003557 else if (STRCMP(what, "matches") == 0)
3558 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003559 }
3560 }
3561
3562 if (ret == OK && (what_flag & CI_WHAT_MODE))
3563 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3564
3565 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3566 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3567
glepnir037b0282025-01-16 14:37:44 +01003568 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3569 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003570 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003571 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003572 dict_T *di;
3573 compl_T *match;
3574 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003575 int has_items = what_flag & CI_WHAT_ITEMS;
3576 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003577 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003578
glepnird4088ed2024-12-31 10:55:22 +01003579 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003580 {
3581 li = list_alloc();
3582 if (li == NULL)
3583 return;
glepnird4088ed2024-12-31 10:55:22 +01003584 ret = dict_add_list(retdict, (has_matches && !has_items)
3585 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003586 }
3587 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3588 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3589 ins_compl_update_sequence_numbers();
3590 if (ret == OK && compl_first_match != NULL)
3591 {
3592 int list_idx = 0;
3593 match = compl_first_match;
3594 do
3595 {
3596 if (!match_at_original_text(match))
3597 {
glepnird4088ed2024-12-31 10:55:22 +01003598 if (has_items
3599 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003600 {
3601 di = dict_alloc();
3602 if (di == NULL)
3603 return;
3604 ret = list_append_dict(li, di);
3605 if (ret != OK)
3606 return;
glepnir037b0282025-01-16 14:37:44 +01003607 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003608 }
glepnird4088ed2024-12-31 10:55:22 +01003609 if (compl_curr_match != NULL
3610 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003611 selected_idx = list_idx;
3612 list_idx += 1;
3613 }
3614 match = match->cp_next;
3615 }
3616 while (match != NULL && !is_first_match(match));
3617 }
3618 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3619 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003620
glepnir037b0282025-01-16 14:37:44 +01003621 if (ret == OK && selected_idx != -1 && has_completed)
3622 {
3623 di = dict_alloc();
3624 if (di == NULL)
3625 return;
3626 fill_complete_info_dict(di, compl_curr_match, FALSE);
3627 ret = dict_add_dict(retdict, "completed", di);
3628 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003629 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003630}
3631
3632/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003633 * "complete_info()" function
3634 */
3635 void
3636f_complete_info(typval_T *argvars, typval_T *rettv)
3637{
3638 list_T *what_list = NULL;
3639
Bram Moolenaar93a10962022-06-16 11:42:09 +01003640 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003641 return;
3642
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003643 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3644 return;
3645
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003646 if (argvars[0].v_type != VAR_UNKNOWN)
3647 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003648 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003649 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003650 what_list = argvars[0].vval.v_list;
3651 }
3652 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003653}
3654#endif
3655
3656/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003657 * Returns TRUE when using a user-defined function for thesaurus completion.
3658 */
3659 static int
3660thesaurus_func_complete(int type UNUSED)
3661{
3662#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003663 return type == CTRL_X_THESAURUS
3664 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003665#else
3666 return FALSE;
3667#endif
3668}
3669
3670/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003671 * Return value of process_next_cpt_value()
3672 */
3673enum
3674{
3675 INS_COMPL_CPT_OK = 1,
3676 INS_COMPL_CPT_CONT,
3677 INS_COMPL_CPT_END
3678};
3679
3680/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003681 * state information used for getting the next set of insert completion
3682 * matches.
3683 */
3684typedef struct
3685{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003686 char_u *e_cpt_copy; // copy of 'complete'
3687 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003688 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003689 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003690 pos_T prev_match_pos; // previous match position
3691 int set_match_pos; // save first_match_pos/last_match_pos
3692 pos_T first_match_pos; // first match position
3693 pos_T last_match_pos; // last match position
3694 int found_all; // found all matches of a certain type.
3695 char_u *dict; // dictionary file to search
3696 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003697 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003698} ins_compl_next_state_T;
3699
3700/*
3701 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003702 *
3703 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003704 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003705 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003706 * st->found_all - all matches of this type are found
3707 * st->ins_buf - search for completions in this buffer
3708 * st->first_match_pos - position of the first completion match
3709 * st->last_match_pos - position of the last completion match
3710 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003711 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003712 * st->dict - name of the dictionary or thesaurus file to search
3713 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003714 *
3715 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003716 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3717 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003718 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003719 */
3720 static int
3721process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003722 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003723 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003724 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003725 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003726{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003727 int compl_type = -1;
3728 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003729
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003730 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003731
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003732 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3733 st->e_cpt++;
3734
3735 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003736 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003737 st->ins_buf = curbuf;
3738 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003739 // Move the cursor back one character so that ^N can match the
3740 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003741 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003742 {
3743 // Move the cursor to after the last character in the
3744 // buffer, so that word at start of buffer is found
3745 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003746 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003747 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003748 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003749 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003750 compl_type = 0;
3751
3752 // Remember the first match so that the loop stops when we
3753 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003754 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003755 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003756 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003757 && (st->ins_buf = ins_compl_next_buf(
3758 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003759 {
3760 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003761 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003762 {
3763 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003764 st->first_match_pos.col = st->last_match_pos.col = 0;
3765 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3766 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003767 compl_type = 0;
3768 }
3769 else // unloaded buffer, scan like dictionary
3770 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003771 st->found_all = TRUE;
3772 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003773 {
3774 status = INS_COMPL_CPT_CONT;
3775 goto done;
3776 }
3777 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003778 st->dict = st->ins_buf->b_fname;
3779 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003780 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003781 if (!shortmess(SHM_COMPLETIONSCAN))
3782 {
3783 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3784 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3785 st->ins_buf->b_fname == NULL
3786 ? buf_spname(st->ins_buf)
3787 : st->ins_buf->b_sfname == NULL
3788 ? st->ins_buf->b_fname
3789 : st->ins_buf->b_sfname);
3790 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3791 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003792 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003793 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003794 status = INS_COMPL_CPT_END;
3795 else
3796 {
3797 if (ctrl_x_mode_line_or_eval())
3798 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003799 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003800 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003801 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003802 compl_type = CTRL_X_DICTIONARY;
3803 else
3804 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003805 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003806 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003807 st->dict = st->e_cpt;
3808 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003809 }
3810 }
Girish Palyacbe53192025-04-14 22:13:15 +02003811#ifdef FEAT_COMPL_FUNC
3812 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
3813 {
3814 compl_type = CTRL_X_FUNCTION;
3815 if (*st->e_cpt == 'o')
3816 st->func_cb = &curbuf->b_ofu_cb;
3817 else
3818 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
3819 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
3820 if (!st->func_cb)
3821 compl_type = -1;
3822 }
3823#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003824#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003825 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003826 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003827 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003828 compl_type = CTRL_X_PATH_DEFINES;
3829#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003830 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003831 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003832 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003833 if (!shortmess(SHM_COMPLETIONSCAN))
3834 {
3835 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3836 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3837 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3838 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003839 }
3840 else
3841 compl_type = -1;
3842
3843 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003844 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003845
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003846 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003847 if (compl_type == -1)
3848 status = INS_COMPL_CPT_CONT;
3849 }
3850
3851done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003852 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003853 return status;
3854}
3855
3856#ifdef FEAT_FIND_ID
3857/*
3858 * Get the next set of identifiers or defines matching "compl_pattern" in
3859 * included files.
3860 */
3861 static void
3862get_next_include_file_completion(int compl_type)
3863{
John Marriott5e6ea922024-11-23 14:01:57 +01003864 find_pattern_in_path(compl_pattern.string, compl_direction,
3865 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003866 (compl_type == CTRL_X_PATH_DEFINES
3867 && !(compl_cont_status & CONT_SOL))
3868 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003869 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003870}
3871#endif
3872
3873/*
3874 * Get the next set of words matching "compl_pattern" in dictionary or
3875 * thesaurus files.
3876 */
3877 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003878get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003879{
3880#ifdef FEAT_COMPL_FUNC
3881 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02003882 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003883 else
3884#endif
3885 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003886 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003887 : (compl_type == CTRL_X_THESAURUS
3888 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3889 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003890 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003891 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003892 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003893}
3894
3895/*
3896 * Get the next set of tag names matching "compl_pattern".
3897 */
3898 static void
3899get_next_tag_completion(void)
3900{
3901 int save_p_ic;
3902 char_u **matches;
3903 int num_matches;
3904
3905 // set p_ic according to p_ic, p_scs and pat for find_tags().
3906 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003907 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003908
3909 // Find up to TAG_MANY matches. Avoids that an enormous number
3910 // of matches is found when compl_pattern is empty
3911 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003912 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003913 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003914 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003915 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3916 ins_compl_add_matches(num_matches, matches, p_ic);
3917 g_tag_at_cursor = FALSE;
3918 p_ic = save_p_ic;
3919}
3920
3921/*
glepnir8159fb12024-07-17 20:32:54 +02003922 * Compare function for qsort
3923 */
glepnirf31cfa22025-03-06 21:59:13 +01003924 static int
3925compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02003926{
3927 int idx_a = *(const int *)a;
3928 int idx_b = *(const int *)b;
3929 int score_a = compl_fuzzy_scores[idx_a];
3930 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003931 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3932 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003933}
3934
3935/*
glepnirf31cfa22025-03-06 21:59:13 +01003936 * insert prefix with redraw
3937 */
3938 static void
3939ins_compl_longest_insert(char_u *prefix)
3940{
3941 ins_compl_delete();
3942 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
3943 ins_redraw(FALSE);
3944}
3945
3946/*
3947 * Calculate the longest common prefix among the best fuzzy matches
3948 * stored in compl_best_matches, and insert it as the longest.
3949 */
3950 static void
3951fuzzy_longest_match(void)
3952{
3953 char_u *prefix = NULL;
3954 int prefix_len = 0;
3955 int i = 0;
3956 int j = 0;
3957 char_u *match_str = NULL;
3958 char_u *prefix_ptr = NULL;
3959 char_u *match_ptr = NULL;
3960 char_u *leader = NULL;
3961 size_t leader_len = 0;
3962 compl_T *compl = NULL;
3963 int more_candidates = FALSE;
3964 compl_T *nn_compl = NULL;
3965
3966 if (compl_num_bests == 0)
3967 return;
3968
3969 nn_compl = compl_first_match->cp_next->cp_next;
3970 if (nn_compl && nn_compl != compl_first_match)
3971 more_candidates = TRUE;
3972
3973 compl = ctrl_x_mode_whole_line() ? compl_first_match
3974 : compl_first_match->cp_next;
3975 if (compl_num_bests == 1)
3976 {
3977 // no more candidates insert the match str
3978 if (!more_candidates)
3979 {
3980 ins_compl_longest_insert(compl->cp_str.string);
3981 compl_num_bests = 0;
3982 }
3983 compl_num_bests = 0;
3984 return;
3985 }
3986
3987 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
3988 if (compl_best_matches == NULL)
3989 return;
3990 while (compl != NULL && i < compl_num_bests)
3991 {
3992 compl_best_matches[i] = compl;
3993 compl = compl->cp_next;
3994 i++;
3995 }
3996
3997 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01003998 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01003999
4000 for (i = 1; i < compl_num_bests; i++)
4001 {
4002 match_str = compl_best_matches[i]->cp_str.string;
4003 prefix_ptr = prefix;
4004 match_ptr = match_str;
4005 j = 0;
4006
4007 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4008 {
4009 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4010 break;
4011
4012 MB_PTR_ADV(prefix_ptr);
4013 MB_PTR_ADV(match_ptr);
4014 j++;
4015 }
4016
4017 if (j > 0)
4018 prefix_len = j;
4019 }
4020
4021 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004022 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004023
4024 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004025 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004026 goto end;
4027
zeertzjq4422de62025-03-07 19:06:02 +01004028 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004029 if (prefix != NULL)
4030 {
4031 ins_compl_longest_insert(prefix);
4032 compl_cfc_longest_ins = TRUE;
4033 vim_free(prefix);
4034 }
4035
4036end:
4037 vim_free(compl_best_matches);
4038 compl_best_matches = NULL;
4039 compl_num_bests = 0;
4040}
4041
4042/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004043 * Get the next set of filename matching "compl_pattern".
4044 */
4045 static void
4046get_next_filename_completion(void)
4047{
4048 char_u **matches;
4049 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004050 char_u *ptr;
4051 garray_T fuzzy_indices;
4052 int i;
4053 int score;
4054 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004055 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004056 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004057 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004058 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004059 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4060 int max_score = 0;
4061 int current_score = 0;
4062 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004063
glepnirb9de1a02024-08-02 19:14:38 +02004064#ifdef BACKSLASH_IN_FILENAME
4065 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4066 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4067#else
4068 char pathsep = PATHSEP;
4069#endif
4070
glepnirf31cfa22025-03-06 21:59:13 +01004071 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004072 {
glepnirb9de1a02024-08-02 19:14:38 +02004073#ifdef BACKSLASH_IN_FILENAME
4074 if (curbuf->b_p_csl[0] == 's')
4075 {
John Marriott5e6ea922024-11-23 14:01:57 +01004076 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004077 {
4078 if (leader[i] == '\\')
4079 leader[i] = '/';
4080 }
4081 }
4082 else if (curbuf->b_p_csl[0] == 'b')
4083 {
John Marriott5e6ea922024-11-23 14:01:57 +01004084 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004085 {
4086 if (leader[i] == '/')
4087 leader[i] = '\\';
4088 }
4089 }
4090#endif
4091 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004092 if (last_sep == NULL)
4093 {
4094 // No path separator or separator is the last character,
4095 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004096 VIM_CLEAR_STRING(compl_pattern);
4097 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4098 if (compl_pattern.string == NULL)
4099 return;
4100 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004101 }
4102 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004103 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004104 else
4105 {
4106 // Split leader into path and file parts
4107 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004108 char_u *path_with_wildcard;
4109
4110 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004111 if (path_with_wildcard != NULL)
4112 {
John Marriott5e6ea922024-11-23 14:01:57 +01004113 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4114 VIM_CLEAR_STRING(compl_pattern);
4115 compl_pattern.string = path_with_wildcard;
4116 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004117
4118 // Move leader to the file part
4119 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004120 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004121 }
4122 }
glepnir8159fb12024-07-17 20:32:54 +02004123 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124
John Marriott5e6ea922024-11-23 14:01:57 +01004125 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004126 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4127 return;
4128
4129 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004130 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004131#ifdef BACKSLASH_IN_FILENAME
4132 if (curbuf->b_p_csl[0] != NUL)
4133 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004134 for (i = 0; i < num_matches; ++i)
4135 {
glepnir8159fb12024-07-17 20:32:54 +02004136 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004137 while (*ptr != NUL)
4138 {
4139 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4140 *ptr = '/';
4141 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4142 *ptr = '\\';
4143 ptr += (*mb_ptr2len)(ptr);
4144 }
4145 }
4146 }
4147#endif
glepnir8159fb12024-07-17 20:32:54 +02004148
glepnirf31cfa22025-03-06 21:59:13 +01004149 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004150 {
4151 ga_init2(&fuzzy_indices, sizeof(int), 10);
4152 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4153
4154 for (i = 0; i < num_matches; i++)
4155 {
4156 ptr = matches[i];
4157 score = fuzzy_match_str(ptr, leader);
4158 if (score > 0)
4159 {
4160 if (ga_grow(&fuzzy_indices, 1) == OK)
4161 {
4162 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4163 compl_fuzzy_scores[i] = score;
4164 fuzzy_indices.ga_len++;
4165 }
4166 }
4167 }
4168
Christian Brabandt220474d2024-07-20 13:26:44 +02004169 // prevent qsort from deref NULL pointer
4170 if (fuzzy_indices.ga_len > 0)
4171 {
glepnirf31cfa22025-03-06 21:59:13 +01004172 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004173 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4174 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004175
Christian Brabandt220474d2024-07-20 13:26:44 +02004176 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004177 {
4178 match = matches[fuzzy_indices_data[i]];
4179 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4180 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
4181 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4182 FALSE, NULL, current_score) == OK)
4183 dir = FORWARD;
4184
4185 if (need_collect_bests)
4186 {
4187 if (i == 0 || current_score == max_score)
4188 {
4189 compl_num_bests++;
4190 max_score = current_score;
4191 }
4192 }
4193 }
glepnir8159fb12024-07-17 20:32:54 +02004194
Christian Brabandt220474d2024-07-20 13:26:44 +02004195 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004196 }
glepnir6b6280c2024-07-27 16:25:45 +02004197 else if (leader_len > 0)
4198 {
4199 FreeWild(num_matches, matches);
4200 num_matches = 0;
4201 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004202
glepnir8159fb12024-07-17 20:32:54 +02004203 vim_free(compl_fuzzy_scores);
4204 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004205
4206 if (compl_num_bests > 0 && compl_get_longest)
4207 fuzzy_longest_match();
4208 return;
glepnir8159fb12024-07-17 20:32:54 +02004209 }
4210
glepnir6b6280c2024-07-27 16:25:45 +02004211 if (num_matches > 0)
4212 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004213}
4214
4215/*
4216 * Get the next set of command-line completions matching "compl_pattern".
4217 */
4218 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004219get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004220{
4221 char_u **matches;
4222 int num_matches;
4223
John Marriott5e6ea922024-11-23 14:01:57 +01004224 if (expand_cmdline(&compl_xp, compl_pattern.string,
4225 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004226 ins_compl_add_matches(num_matches, matches, FALSE);
4227}
4228
4229/*
4230 * Get the next set of spell suggestions matching "compl_pattern".
4231 */
4232 static void
4233get_next_spell_completion(linenr_T lnum UNUSED)
4234{
4235#ifdef FEAT_SPELL
4236 char_u **matches;
4237 int num_matches;
4238
John Marriott5e6ea922024-11-23 14:01:57 +01004239 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004240 if (num_matches > 0)
4241 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004242 else
4243 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004244#endif
4245}
4246
4247/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004248 * Return the next word or line from buffer "ins_buf" at position
4249 * "cur_match_pos" for completion. The length of the match is set in "len".
4250 */
4251 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004252ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004253 buf_T *ins_buf, // buffer being scanned
4254 pos_T *cur_match_pos, // current match position
4255 int *match_len,
4256 int *cont_s_ipos) // next ^X<> will set initial_pos
4257{
4258 char_u *ptr;
4259 int len;
4260
4261 *match_len = 0;
4262 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4263 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004264 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004265 if (ctrl_x_mode_line_or_eval())
4266 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004267 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004268 {
4269 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4270 return NULL;
4271 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004272 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004273 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004274 {
4275 char_u *tmp_ptr = ptr;
4276
4277 ptr = skipwhite(tmp_ptr);
4278 len -= (int)(ptr - tmp_ptr);
4279 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004280 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004281 }
4282 else
4283 {
4284 char_u *tmp_ptr = ptr;
4285
John Marriott5e6ea922024-11-23 14:01:57 +01004286 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004287 {
4288 tmp_ptr += compl_length;
4289 // Skip if already inside a word.
4290 if (vim_iswordp(tmp_ptr))
4291 return NULL;
4292 // Find start of next word.
4293 tmp_ptr = find_word_start(tmp_ptr);
4294 }
4295 // Find end of this word.
4296 tmp_ptr = find_word_end(tmp_ptr);
4297 len = (int)(tmp_ptr - ptr);
4298
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004299 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004300 {
4301 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4302 {
4303 // Try next line, if any. the new word will be
4304 // "join" as if the normal command "J" was used.
4305 // IOSIZE is always greater than
4306 // compl_length, so the next STRNCPY always
4307 // works -- Acevedo
4308 STRNCPY(IObuff, ptr, len);
4309 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4310 tmp_ptr = ptr = skipwhite(ptr);
4311 // Find start of next word.
4312 tmp_ptr = find_word_start(tmp_ptr);
4313 // Find end of next word.
4314 tmp_ptr = find_word_end(tmp_ptr);
4315 if (tmp_ptr > ptr)
4316 {
4317 if (*ptr != ')' && IObuff[len - 1] != TAB)
4318 {
4319 if (IObuff[len - 1] != ' ')
4320 IObuff[len++] = ' ';
4321 // IObuf =~ "\k.* ", thus len >= 2
4322 if (p_js
4323 && (IObuff[len - 2] == '.'
4324 || (vim_strchr(p_cpo, CPO_JOINSP)
4325 == NULL
4326 && (IObuff[len - 2] == '?'
4327 || IObuff[len - 2] == '!'))))
4328 IObuff[len++] = ' ';
4329 }
4330 // copy as much as possible of the new word
4331 if (tmp_ptr - ptr >= IOSIZE - len)
4332 tmp_ptr = ptr + IOSIZE - len - 1;
4333 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4334 len += (int)(tmp_ptr - ptr);
4335 *cont_s_ipos = TRUE;
4336 }
4337 IObuff[len] = NUL;
4338 ptr = IObuff;
4339 }
4340 if (len == compl_length)
4341 return NULL;
4342 }
4343 }
4344
4345 *match_len = len;
4346 return ptr;
4347}
4348
4349/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004350 * Get the next set of words matching "compl_pattern" for default completion(s)
4351 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004352 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4353 * position "st->start_pos" in the "compl_direction" direction. If
4354 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4355 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004356 * Returns OK if a new next match is found, otherwise returns FAIL.
4357 */
4358 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004359get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004360{
4361 int found_new_match = FAIL;
4362 int save_p_scs;
4363 int save_p_ws;
4364 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004365 char_u *ptr = NULL;
4366 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004367 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004368 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004369 int score = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004370
4371 // If 'infercase' is set, don't use 'smartcase' here
4372 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004373 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004374 p_scs = FALSE;
4375
4376 // Buffers other than curbuf are scanned from the beginning or the
4377 // end but never from the middle, thus setting nowrapscan in this
4378 // buffer is a good idea, on the other hand, we always set
4379 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4380 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004381 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004382 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004383 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004384 p_ws = TRUE;
4385 looped_around = FALSE;
4386 for (;;)
4387 {
4388 int cont_s_ipos = FALSE;
4389
4390 ++msg_silent; // Don't want messages for wrapscan.
4391
glepnirf31cfa22025-03-06 21:59:13 +01004392 if (in_collect)
4393 {
glepnir8159fb12024-07-17 20:32:54 +02004394 found_new_match = search_for_fuzzy_match(st->ins_buf,
4395 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004396 start_pos, &len, &ptr, &score);
4397 }
4398 // ctrl_x_mode_line_or_eval() || word-wise search that
4399 // has added a word that was at the beginning of the line
4400 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4401 found_new_match = search_for_exact_line(st->ins_buf,
4402 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004403 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004404 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004405 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004406 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004407 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004408 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004409 {
4410 // set "compl_started" even on fail
4411 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004412 st->first_match_pos = *st->cur_match_pos;
4413 st->last_match_pos = *st->cur_match_pos;
4414 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004415 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004416 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4417 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004418 {
4419 found_new_match = FAIL;
4420 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004421 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004422 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4423 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4424 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004425 {
4426 if (looped_around)
4427 found_new_match = FAIL;
4428 else
4429 looped_around = TRUE;
4430 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004431 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004432 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4433 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4434 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004435 {
4436 if (looped_around)
4437 found_new_match = FAIL;
4438 else
4439 looped_around = TRUE;
4440 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004441 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004442 if (found_new_match == FAIL)
4443 break;
4444
4445 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004446 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004447 && start_pos->lnum == st->cur_match_pos->lnum
4448 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004449 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004450
glepnirf31cfa22025-03-06 21:59:13 +01004451 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004452 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4453 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004454 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004455 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004456
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004457 if (ins_compl_add_infercase(ptr, len, p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01004458 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
4459 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004460 {
glepnirf31cfa22025-03-06 21:59:13 +01004461 if (in_collect && score == compl_first_match->cp_next->cp_score)
4462 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004463 found_new_match = OK;
4464 break;
4465 }
4466 }
4467 p_scs = save_p_scs;
4468 p_ws = save_p_ws;
4469
4470 return found_new_match;
4471}
4472
4473/*
Girish Palyacbe53192025-04-14 22:13:15 +02004474 * Return the callback function associated with "funcname".
4475 */
4476#ifdef FEAT_COMPL_FUNC
4477 static callback_T *
4478get_cpt_func_callback(char_u *funcname)
4479{
4480 static callback_T cb;
4481 char_u buf[LSIZE];
4482 int slen;
4483
4484 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4485 if (slen > 0 && option_set_callback_func(buf, &cb))
4486 return &cb;
4487 return NULL;
4488}
4489
4490/*
4491 * Retrieve new completion matches by invoking callback "cb".
4492 */
4493 static void
4494expand_cpt_function(callback_T *cb)
4495{
4496 // Re-insert the text removed by ins_compl_delete().
4497 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4498 // Get matches
4499 get_cpt_func_completion_matches(cb);
4500 // Undo insertion
4501 ins_compl_delete();
4502}
4503#endif
4504
4505/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004506 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004507 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004508 */
4509 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004510get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004511{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004512 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004513
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004514 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004515 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004516 case -1:
4517 break;
4518#ifdef FEAT_FIND_ID
4519 case CTRL_X_PATH_PATTERNS:
4520 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004521 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004522 break;
4523#endif
4524
4525 case CTRL_X_DICTIONARY:
4526 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004527 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4528 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004529 break;
4530
4531 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004532 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004533 break;
4534
4535 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004536 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004537 break;
4538
4539 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004540 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004541 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004542 break;
4543
4544#ifdef FEAT_COMPL_FUNC
4545 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004546 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4547 expand_cpt_function(st->func_cb);
4548 else
4549 expand_by_function(type, compl_pattern.string, NULL);
4550 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004551 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004552 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004553 break;
4554#endif
4555
4556 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004557 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004558 break;
4559
4560 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004561 found_new_match = get_next_default_completion(st, ini);
4562 if (found_new_match == FAIL && st->ins_buf == curbuf)
4563 st->found_all = TRUE;
4564 }
4565
4566 // check if compl_curr_match has changed, (e.g. other type of
4567 // expansion added something)
4568 if (type != 0 && compl_curr_match != compl_old_match)
4569 found_new_match = OK;
4570
4571 return found_new_match;
4572}
4573
4574/*
4575 * Get the next expansion(s), using "compl_pattern".
4576 * The search starts at position "ini" in curbuf and in the direction
4577 * compl_direction.
4578 * When "compl_started" is FALSE start at that position, otherwise continue
4579 * where we stopped searching before.
4580 * This may return before finding all the matches.
4581 * Return the total number of matches or -1 if still unknown -- Acevedo
4582 */
4583 static int
4584ins_compl_get_exp(pos_T *ini)
4585{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004586 static ins_compl_next_state_T st;
4587 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004588 int i;
4589 int found_new_match;
4590 int type = ctrl_x_mode;
4591
4592 if (!compl_started)
4593 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004594 buf_T *buf;
4595
4596 FOR_ALL_BUFFERS(buf)
4597 buf->b_scanned = 0;
4598 if (!st_cleared)
4599 {
4600 CLEAR_FIELD(st);
4601 st_cleared = TRUE;
4602 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004603 st.found_all = FALSE;
4604 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004605 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004606 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004607 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4608 ? (char_u *)"." : curbuf->b_p_cpt);
4609 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004610 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004611
4612 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
4613 && !cpt_compl_src_init(st.e_cpt))
4614 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004615 }
4616 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4617 st.ins_buf = curbuf; // In case the buffer was wiped out.
4618
4619 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004620 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004621 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004622
4623 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palyacbe53192025-04-14 22:13:15 +02004624 for (cpt_value_idx = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004625 {
4626 found_new_match = FAIL;
4627 st.set_match_pos = FALSE;
4628
4629 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4630 // or if found_all says this entry is done. For ^X^L only use the
4631 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004632 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004633 && (!compl_started || st.found_all))
4634 {
glepnir53b14572025-03-12 21:28:39 +01004635 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004636
4637 if (status == INS_COMPL_CPT_END)
4638 break;
4639 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004640 {
4641 cpt_value_idx++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004642 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004643 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004644 }
4645
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004646 // If complete() was called then compl_pattern has been reset. The
4647 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004648 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004649 break;
4650
4651 // get the next set of completion matches
4652 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004653
Girish Palyacbe53192025-04-14 22:13:15 +02004654 if (type > 0)
4655 cpt_value_idx++;
4656
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004657 // break the loop for specialized modes (use 'complete' just for the
4658 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4659 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004660 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4661 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004662 {
4663 if (got_int)
4664 break;
4665 // Fill the popup menu as soon as possible.
4666 if (type != -1)
4667 ins_compl_check_keys(0, FALSE);
4668
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004669 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004670 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4671 break;
4672 compl_started = TRUE;
4673 }
4674 else
4675 {
4676 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004677 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004678 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004679
4680 compl_started = FALSE;
4681 }
4682 }
Girish Palyacbe53192025-04-14 22:13:15 +02004683 cpt_value_idx = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004684 compl_started = TRUE;
4685
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004686 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004687 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004688 found_new_match = FAIL;
4689
4690 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004691 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004692 && !ctrl_x_mode_line_or_eval()))
4693 i = ins_compl_make_cyclic();
4694
glepnirf31cfa22025-03-06 21:59:13 +01004695 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4696 fuzzy_longest_match();
4697
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004698 if (compl_old_match != NULL)
4699 {
4700 // If several matches were added (FORWARD) or the search failed and has
4701 // just been made cyclic then we have to move compl_curr_match to the
4702 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004703 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004704 : compl_old_match->cp_prev;
4705 if (compl_curr_match == NULL)
4706 compl_curr_match = compl_old_match;
4707 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004708 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004709
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004710 return i;
4711}
4712
4713/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004714 * Update "compl_shown_match" to the actually shown match, it may differ when
4715 * "compl_leader" is used to omit some of the matches.
4716 */
4717 static void
4718ins_compl_update_shown_match(void)
4719{
4720 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004721 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004722 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004723 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004724 compl_shown_match = compl_shown_match->cp_next;
4725
4726 // If we didn't find it searching forward, and compl_shows_dir is
4727 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004728 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004729 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004730 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004731 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004732 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004733 {
4734 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004735 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004736 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004737 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004738 compl_shown_match = compl_shown_match->cp_prev;
4739 }
4740}
4741
4742/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004743 * Delete the old text being completed.
4744 */
4745 void
4746ins_compl_delete(void)
4747{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004748 // In insert mode: Delete the typed part.
4749 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004750 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01004751 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01004752 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004753 int has_preinsert = ins_compl_preinsert_effect();
4754 if (has_preinsert)
4755 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02004756 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004757 curwin->w_cursor.col = compl_ins_end_col;
4758 }
4759
glepnir76bdb822025-02-08 19:04:51 +01004760 if (curwin->w_cursor.lnum > compl_lnum)
4761 {
4762 if (curwin->w_cursor.col < ml_get_curline_len())
4763 {
John Marriottf4b36412025-02-23 09:09:59 +01004764 char_u *line = ml_get_cursor();
4765 remaining.length = ml_get_cursor_len();
4766 remaining.string = vim_strnsave(line, remaining.length);
4767 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01004768 return;
4769 }
4770 while (curwin->w_cursor.lnum > compl_lnum)
4771 {
4772 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4773 {
John Marriottf4b36412025-02-23 09:09:59 +01004774 if (remaining.string)
4775 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004776 return;
4777 }
zeertzjq060e6552025-02-21 20:06:26 +01004778 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01004779 curwin->w_cursor.lnum--;
4780 }
4781 // move cursor to end of line
4782 curwin->w_cursor.col = ml_get_curline_len();
4783 }
4784
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004785 if ((int)curwin->w_cursor.col > col)
4786 {
4787 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004788 {
John Marriottf4b36412025-02-23 09:09:59 +01004789 if (remaining.string)
4790 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004791 return;
glepnire3647c82025-02-10 21:16:32 +01004792 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004793 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004794 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004795 }
4796
John Marriottf4b36412025-02-23 09:09:59 +01004797 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01004798 {
4799 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01004800 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01004801 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01004802 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004803 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004804 // TODO: is this sufficient for redrawing? Redrawing everything causes
4805 // flicker, thus we can't do that.
4806 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004807#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004808 // clear v:completed_item
4809 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004810#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004811}
4812
4813/*
glepnir76bdb822025-02-08 19:04:51 +01004814 * Insert a completion string that contains newlines.
4815 * The string is split and inserted line by line.
4816 */
4817 static void
4818ins_compl_expand_multiple(char_u *str)
4819{
4820 char_u *start = str;
4821 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01004822 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01004823
4824 while (*curr != NUL)
4825 {
4826 if (*curr == '\n')
4827 {
4828 // Insert the text chunk before newline
4829 if (curr > start)
4830 ins_char_bytes(start, (int)(curr - start));
4831
4832 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01004833 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01004834 start = curr + 1;
4835 }
4836 curr++;
4837 }
4838
4839 // Handle remaining text after last newline (if any)
4840 if (curr > start)
4841 ins_char_bytes(start, (int)(curr - start));
4842
4843 compl_ins_end_col = curwin->w_cursor.col;
4844}
4845
4846/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004847 * Insert the new text being completed.
4848 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004849 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4850 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004851 */
4852 void
glepniredd4ac32025-01-29 18:53:51 +01004853ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004854{
glepnir76bdb822025-02-08 19:04:51 +01004855 int compl_len = get_compl_len();
4856 int preinsert = ins_compl_has_preinsert();
4857 char_u *cp_str = compl_shown_match->cp_str.string;
4858 size_t cp_str_len = compl_shown_match->cp_str.length;
4859 size_t leader_len = ins_compl_leader_len();
4860 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004861
4862 // Make sure we don't go over the end of the string, this can happen with
4863 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004864 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004865 {
glepnir76bdb822025-02-08 19:04:51 +01004866 if (has_multiple)
4867 ins_compl_expand_multiple(cp_str + compl_len);
4868 else
4869 {
4870 ins_compl_insert_bytes(cp_str + compl_len, -1);
4871 if (preinsert && move_cursor)
4872 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4873 }
glepniredd4ac32025-01-29 18:53:51 +01004874 }
4875 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004876 compl_used_match = FALSE;
4877 else
4878 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004879#ifdef FEAT_EVAL
4880 {
4881 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4882
4883 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4884 }
4885#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004886 if (!in_compl_func)
4887 compl_curr_match = compl_shown_match;
4888}
4889
4890/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004891 * show the file name for the completion match (if any). Truncate the file
4892 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004893 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004894 static void
4895ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004896{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004897 char *lead = _("match in file");
4898 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4899 char_u *s;
4900 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004901
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004902 if (space <= 0)
4903 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004904
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004905 // We need the tail that fits. With double-byte encoding going
4906 // back from the end is very slow, thus go from the start and keep
4907 // the text that fits in "space" between "s" and "e".
4908 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004909 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004910 space -= ptr2cells(e);
4911 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004912 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004913 space += ptr2cells(s);
4914 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004915 }
4916 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004917 msg_hist_off = TRUE;
4918 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4919 s > compl_shown_match->cp_fname ? "<" : "", s);
4920 msg((char *)IObuff);
4921 msg_hist_off = FALSE;
4922 redraw_cmdline = FALSE; // don't overwrite!
4923}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004924
glepnirdca57fb2024-06-04 22:01:21 +02004925/*
zeertzjq551d8c32024-06-05 19:53:32 +02004926 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004927 */
glepnira218cc62024-06-03 19:32:39 +02004928 static compl_T *
4929find_comp_when_fuzzy(void)
4930{
4931 int score;
4932 char_u* str;
4933 int target_idx = -1;
4934 int is_forward = compl_shows_dir_forward();
4935 int is_backward = compl_shows_dir_backward();
4936 compl_T *comp = NULL;
4937
glepnir43eef882024-06-19 20:20:48 +02004938 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004939 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02004940 return compl_first_match != compl_shown_match ?
4941 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02004942 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004943
4944 if (is_forward)
4945 target_idx = compl_selected_item + 1;
4946 else if (is_backward)
4947 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004948 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004949
4950 score = compl_match_array[target_idx].pum_score;
4951 str = compl_match_array[target_idx].pum_text;
4952
4953 comp = compl_first_match;
4954 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004955 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004956 return comp;
4957 comp = comp->cp_next;
4958 } while (comp != NULL && !is_first_match(comp));
4959
4960 return NULL;
4961}
4962
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004963/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004964 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004965 * times. The number of matches found is returned in 'num_matches'.
4966 *
4967 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4968 * get more completions. If it is FALSE, then do nothing when there are no more
4969 * completions in the given direction.
4970 *
4971 * If "advance" is TRUE, then completion will move to the first match.
4972 * Otherwise, the original text will be shown.
4973 *
4974 * Returns OK on success and -1 if the number of matches are unknown.
4975 */
4976 static int
4977find_next_completion_match(
4978 int allow_get_expansion,
4979 int todo, // repeat completion this many times
4980 int advance,
4981 int *num_matches)
4982{
4983 int found_end = FALSE;
4984 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004985 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004986 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4987 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004988
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004989 while (--todo >= 0)
4990 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004991 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004992 {
glepniraced8c22024-06-15 15:13:05 +02004993 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4994 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004995 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004996 && (is_first_match(compl_shown_match->cp_next)
4997 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004998 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004999 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005000 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005001 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005002 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02005003 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
5004 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005005 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005006 }
5007 else
5008 {
5009 if (!allow_get_expansion)
5010 {
5011 if (advance)
5012 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005013 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005014 compl_pending -= todo + 1;
5015 else
5016 compl_pending += todo + 1;
5017 }
5018 return -1;
5019 }
5020
5021 if (!compl_no_select && advance)
5022 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005023 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005024 --compl_pending;
5025 else
5026 ++compl_pending;
5027 }
5028
5029 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005030 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005031
5032 // handle any pending completions
5033 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005034 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005035 {
5036 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5037 {
5038 compl_shown_match = compl_shown_match->cp_next;
5039 --compl_pending;
5040 }
5041 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5042 {
5043 compl_shown_match = compl_shown_match->cp_prev;
5044 ++compl_pending;
5045 }
5046 else
5047 break;
5048 }
5049 found_end = FALSE;
5050 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005051 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005052 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005053 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005054 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005055 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005056 ++todo;
5057 else
5058 // Remember a matching item.
5059 found_compl = compl_shown_match;
5060
5061 // Stop at the end of the list when we found a usable match.
5062 if (found_end)
5063 {
5064 if (found_compl != NULL)
5065 {
5066 compl_shown_match = found_compl;
5067 break;
5068 }
5069 todo = 1; // use first usable match after wrapping around
5070 }
5071 }
5072
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005073 return OK;
5074}
5075
5076/*
5077 * Fill in the next completion in the current direction.
5078 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5079 * get more completions. If it is FALSE, then we just do nothing when there
5080 * are no more completions in a given direction. The latter case is used when
5081 * we are still in the middle of finding completions, to allow browsing
5082 * through the ones found so far.
5083 * Return the total number of matches, or -1 if still unknown -- webb.
5084 *
5085 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5086 * compl_shown_match here.
5087 *
5088 * Note that this function may be called recursively once only. First with
5089 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5090 * calls this function with "allow_get_expansion" FALSE.
5091 */
5092 static int
5093ins_compl_next(
5094 int allow_get_expansion,
5095 int count, // repeat completion this many times; should
5096 // be at least 1
5097 int insert_match, // Insert the newly selected match
5098 int in_compl_func) // called from complete_check()
5099{
5100 int num_matches = -1;
5101 int todo = count;
5102 int advance;
5103 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005104 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005105 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005106 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5107 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005108 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005109
5110 // When user complete function return -1 for findstart which is next
5111 // time of 'always', compl_shown_match become NULL.
5112 if (compl_shown_match == NULL)
5113 return -1;
5114
John Marriott5e6ea922024-11-23 14:01:57 +01005115 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005116 && !match_at_original_text(compl_shown_match)
5117 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005118 // Update "compl_shown_match" to the actually shown match
5119 ins_compl_update_shown_match();
5120
5121 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005122 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005123 // Delete old text to be replaced
5124 ins_compl_delete();
5125
5126 // When finding the longest common text we stick at the original text,
5127 // don't let CTRL-N or CTRL-P move to the first match.
5128 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5129
5130 // When restarting the search don't insert the first match either.
5131 if (compl_restarting)
5132 {
5133 advance = FALSE;
5134 compl_restarting = FALSE;
5135 }
5136
5137 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5138 // around.
5139 if (find_next_completion_match(allow_get_expansion, todo, advance,
5140 &num_matches) == -1)
5141 return -1;
5142
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005143 if (curbuf != orig_curbuf)
5144 {
5145 // In case some completion function switched buffer, don't want to
5146 // insert the completion elsewhere.
5147 return -1;
5148 }
5149
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005150 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005151 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005152 {
glepnir6a38aff2024-12-16 21:56:16 +01005153 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005154 compl_used_match = FALSE;
5155 }
5156 else if (insert_match)
5157 {
5158 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005159 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005160 else
glepnir6a38aff2024-12-16 21:56:16 +01005161 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005162 }
5163 else
5164 compl_used_match = FALSE;
5165
5166 if (!allow_get_expansion)
5167 {
5168 // may undisplay the popup menu first
5169 ins_compl_upd_pum();
5170
5171 if (pum_enough_matches())
5172 // Will display the popup menu, don't redraw yet to avoid flicker.
5173 pum_call_update_screen();
5174 else
5175 // Not showing the popup menu yet, redraw to show the user what was
5176 // inserted.
5177 update_screen(0);
5178
5179 // display the updated popup menu
5180 ins_compl_show_pum();
5181#ifdef FEAT_GUI
5182 if (gui.in_use)
5183 {
5184 // Show the cursor after the match, not after the redrawn text.
5185 setcursor();
5186 out_flush_cursor(FALSE, FALSE);
5187 }
5188#endif
5189
5190 // Delete old text to be replaced, since we're still searching and
5191 // don't want to match ourselves!
5192 ins_compl_delete();
5193 }
5194
5195 // Enter will select a match when the match wasn't inserted and the popup
5196 // menu is visible.
5197 if (compl_no_insert && !started)
5198 compl_enter_selects = TRUE;
5199 else
5200 compl_enter_selects = !insert_match && compl_match_array != NULL;
5201
5202 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005203 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005204 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005205
5206 return num_matches;
5207}
5208
5209/*
5210 * Call this while finding completions, to check whether the user has hit a key
5211 * that should change the currently displayed completion, or exit completion
5212 * mode. Also, when compl_pending is not zero, show a completion as soon as
5213 * possible. -- webb
5214 * "frequency" specifies out of how many calls we actually check.
5215 * "in_compl_func" is TRUE when called from complete_check(), don't set
5216 * compl_curr_match.
5217 */
5218 void
5219ins_compl_check_keys(int frequency, int in_compl_func)
5220{
5221 static int count = 0;
5222 int c;
5223
5224 // Don't check when reading keys from a script, :normal or feedkeys().
5225 // That would break the test scripts. But do check for keys when called
5226 // from complete_check().
5227 if (!in_compl_func && (using_script() || ex_normal_busy))
5228 return;
5229
5230 // Only do this at regular intervals
5231 if (++count < frequency)
5232 return;
5233 count = 0;
5234
5235 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5236 // can't do its work correctly.
5237 c = vpeekc_any();
5238 if (c != NUL)
5239 {
5240 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5241 {
5242 c = safe_vgetc(); // Eat the character
5243 compl_shows_dir = ins_compl_key2dir(c);
5244 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5245 c != K_UP && c != K_DOWN, in_compl_func);
5246 }
5247 else
5248 {
5249 // Need to get the character to have KeyTyped set. We'll put it
5250 // back with vungetc() below. But skip K_IGNORE.
5251 c = safe_vgetc();
5252 if (c != K_IGNORE)
5253 {
5254 // Don't interrupt completion when the character wasn't typed,
5255 // e.g., when doing @q to replay keys.
5256 if (c != Ctrl_R && KeyTyped)
5257 compl_interrupted = TRUE;
5258
5259 vungetc(c);
5260 }
5261 }
5262 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005263 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005264 {
5265 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5266
5267 compl_pending = 0;
5268 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5269 }
5270}
5271
5272/*
5273 * Decide the direction of Insert mode complete from the key typed.
5274 * Returns BACKWARD or FORWARD.
5275 */
5276 static int
5277ins_compl_key2dir(int c)
5278{
5279 if (c == Ctrl_P || c == Ctrl_L
5280 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5281 return BACKWARD;
5282 return FORWARD;
5283}
5284
5285/*
5286 * Return TRUE for keys that are used for completion only when the popup menu
5287 * is visible.
5288 */
5289 static int
5290ins_compl_pum_key(int c)
5291{
5292 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5293 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5294 || c == K_UP || c == K_DOWN);
5295}
5296
5297/*
5298 * Decide the number of completions to move forward.
5299 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5300 */
5301 static int
5302ins_compl_key2count(int c)
5303{
5304 int h;
5305
5306 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5307 {
5308 h = pum_get_height();
5309 if (h > 3)
5310 h -= 2; // keep some context
5311 return h;
5312 }
5313 return 1;
5314}
5315
5316/*
5317 * Return TRUE if completion with "c" should insert the match, FALSE if only
5318 * to change the currently selected completion.
5319 */
5320 static int
5321ins_compl_use_match(int c)
5322{
5323 switch (c)
5324 {
5325 case K_UP:
5326 case K_DOWN:
5327 case K_PAGEDOWN:
5328 case K_KPAGEDOWN:
5329 case K_S_DOWN:
5330 case K_PAGEUP:
5331 case K_KPAGEUP:
5332 case K_S_UP:
5333 return FALSE;
5334 }
5335 return TRUE;
5336}
5337
5338/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005339 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5340 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005341 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005342 * Uses the global variables: compl_cont_status and ctrl_x_mode
5343 */
5344 static int
5345get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5346{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005347 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005348 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005349 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005350 {
5351 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5352 ;
5353 compl_col += ++startcol;
5354 compl_length = curs_col - startcol;
5355 }
5356 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005357 {
John Marriott5e6ea922024-11-23 14:01:57 +01005358 compl_pattern.string = str_foldcase(line + compl_col,
5359 compl_length, NULL, 0);
5360 if (compl_pattern.string == NULL)
5361 {
5362 compl_pattern.length = 0;
5363 return FAIL;
5364 }
5365 compl_pattern.length = STRLEN(compl_pattern.string);
5366 }
5367 else
5368 {
5369 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5370 if (compl_pattern.string == NULL)
5371 {
5372 compl_pattern.length = 0;
5373 return FAIL;
5374 }
5375 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005376 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005377 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005378 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005379 {
5380 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005381 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005382 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005383
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005384 if (!vim_iswordp(line + compl_col)
5385 || (compl_col > 0
5386 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005387 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005388 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005389 prefixlen = 0;
5390 }
John Marriott5e6ea922024-11-23 14:01:57 +01005391
5392 // we need up to 2 extra chars for the prefix
5393 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5394 compl_pattern.string = alloc(n);
5395 if (compl_pattern.string == NULL)
5396 {
5397 compl_pattern.length = 0;
5398 return FAIL;
5399 }
5400 STRCPY((char *)compl_pattern.string, prefix);
5401 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005402 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005403 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005404 }
5405 else if (--startcol < 0
5406 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5407 {
John Marriott5e6ea922024-11-23 14:01:57 +01005408 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5409
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005410 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005411 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5412 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005413 {
John Marriott5e6ea922024-11-23 14:01:57 +01005414 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005415 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005416 }
John Marriott5e6ea922024-11-23 14:01:57 +01005417 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005418 compl_col += curs_col;
5419 compl_length = 0;
5420 }
5421 else
5422 {
5423 // Search the point of change class of multibyte character
5424 // or not a word single byte character backward.
5425 if (has_mbyte)
5426 {
5427 int base_class;
5428 int head_off;
5429
5430 startcol -= (*mb_head_off)(line, line + startcol);
5431 base_class = mb_get_class(line + startcol);
5432 while (--startcol >= 0)
5433 {
5434 head_off = (*mb_head_off)(line, line + startcol);
5435 if (base_class != mb_get_class(line + startcol
5436 - head_off))
5437 break;
5438 startcol -= head_off;
5439 }
5440 }
5441 else
5442 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5443 ;
5444 compl_col += ++startcol;
5445 compl_length = (int)curs_col - startcol;
5446 if (compl_length == 1)
5447 {
5448 // Only match word with at least two chars -- webb
5449 // there's no need to call quote_meta,
5450 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005451 compl_pattern.string = alloc(7);
5452 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005453 {
John Marriott5e6ea922024-11-23 14:01:57 +01005454 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005455 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005456 }
John Marriott5e6ea922024-11-23 14:01:57 +01005457 STRCPY((char *)compl_pattern.string, "\\<");
5458 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5459 STRCAT((char *)compl_pattern.string, "\\k");
5460 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005461 }
5462 else
5463 {
John Marriott5e6ea922024-11-23 14:01:57 +01005464 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5465
5466 compl_pattern.string = alloc(n);
5467 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005468 {
John Marriott5e6ea922024-11-23 14:01:57 +01005469 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005470 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005471 }
John Marriott5e6ea922024-11-23 14:01:57 +01005472 STRCPY((char *)compl_pattern.string, "\\<");
5473 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005474 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005475 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005476 }
5477 }
5478
5479 return OK;
5480}
5481
5482/*
5483 * Get the pattern, column and length for whole line completion or for the
5484 * complete() function.
5485 * Sets the global variables: compl_col, compl_length and compl_pattern.
5486 */
5487 static int
5488get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5489{
5490 compl_col = (colnr_T)getwhitecols(line);
5491 compl_length = (int)curs_col - (int)compl_col;
5492 if (compl_length < 0) // cursor in indent: empty pattern
5493 compl_length = 0;
5494 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005495 {
John Marriott5e6ea922024-11-23 14:01:57 +01005496 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5497 NULL, 0);
5498 if (compl_pattern.string == NULL)
5499 {
5500 compl_pattern.length = 0;
5501 return FAIL;
5502 }
5503 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005504 }
John Marriott5e6ea922024-11-23 14:01:57 +01005505 else
5506 {
5507 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5508 if (compl_pattern.string == NULL)
5509 {
5510 compl_pattern.length = 0;
5511 return FAIL;
5512 }
5513 compl_pattern.length = (size_t)compl_length;
5514 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005515
5516 return OK;
5517}
5518
5519/*
5520 * Get the pattern, column and length for filename completion.
5521 * Sets the global variables: compl_col, compl_length and compl_pattern.
5522 */
5523 static int
5524get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5525{
5526 // Go back to just before the first filename character.
5527 if (startcol > 0)
5528 {
5529 char_u *p = line + startcol;
5530
5531 MB_PTR_BACK(line, p);
5532 while (p > line && vim_isfilec(PTR2CHAR(p)))
5533 MB_PTR_BACK(line, p);
5534 if (p == line && vim_isfilec(PTR2CHAR(p)))
5535 startcol = 0;
5536 else
5537 startcol = (int)(p - line) + 1;
5538 }
5539
5540 compl_col += startcol;
5541 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005542 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5543 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005544 {
John Marriott5e6ea922024-11-23 14:01:57 +01005545 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005546 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005547 }
5548
John Marriott5e6ea922024-11-23 14:01:57 +01005549 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005550
5551 return OK;
5552}
5553
5554/*
5555 * Get the pattern, column and length for command-line completion.
5556 * Sets the global variables: compl_col, compl_length and compl_pattern.
5557 */
5558 static int
5559get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5560{
John Marriott5e6ea922024-11-23 14:01:57 +01005561 compl_pattern.string = vim_strnsave(line, curs_col);
5562 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005563 {
John Marriott5e6ea922024-11-23 14:01:57 +01005564 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005565 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005566 }
John Marriott5e6ea922024-11-23 14:01:57 +01005567 compl_pattern.length = curs_col;
5568 set_cmd_context(&compl_xp, compl_pattern.string,
5569 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005570 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5571 || compl_xp.xp_context == EXPAND_NOTHING)
5572 // No completion possible, use an empty pattern to get a
5573 // "pattern not found" message.
5574 compl_col = curs_col;
5575 else
John Marriott5e6ea922024-11-23 14:01:57 +01005576 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005577 compl_length = curs_col - compl_col;
5578
5579 return OK;
5580}
5581
5582/*
5583 * Get the pattern, column and length for user defined completion ('omnifunc',
5584 * 'completefunc' and 'thesaurusfunc')
5585 * Sets the global variables: compl_col, compl_length and compl_pattern.
5586 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005587 * Callback function "cb" is set if triggered by a function in the 'cpt'
5588 * option; otherwise, it is NULL.
5589 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005590 */
5591 static int
Girish Palyacbe53192025-04-14 22:13:15 +02005592get_userdefined_compl_info(colnr_T curs_col UNUSED, callback_T *cb UNUSED,
5593 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005594{
5595 int ret = FAIL;
5596
5597#ifdef FEAT_COMPL_FUNC
5598 // Call user defined function 'completefunc' with "a:findstart"
5599 // set to 1 to obtain the length of text to use for completion.
5600 char_u *line;
5601 typval_T args[3];
5602 int col;
5603 char_u *funcname;
5604 pos_T pos;
5605 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005606 int len;
5607 string_T *compl_pat;
5608 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005609
Girish Palyacbe53192025-04-14 22:13:15 +02005610 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005611 {
Girish Palyacbe53192025-04-14 22:13:15 +02005612 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5613 // length as a string
5614 funcname = get_complete_funcname(ctrl_x_mode);
5615 if (*funcname == NUL)
5616 {
5617 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5618 ? "completefunc" : "omnifunc");
5619 return FAIL;
5620 }
5621 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005622 }
5623
5624 args[0].v_type = VAR_NUMBER;
5625 args[0].vval.v_number = 1;
5626 args[1].v_type = VAR_STRING;
5627 args[1].vval.v_string = (char_u *)"";
5628 args[2].v_type = VAR_UNKNOWN;
5629 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005630 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005631 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005632 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005633
5634 State = save_State;
5635 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005636 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005637 validate_cursor();
5638 if (!EQUAL_POS(curwin->w_cursor, pos))
5639 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005640 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005641 return FAIL;
5642 }
5643
Girish Palyacbe53192025-04-14 22:13:15 +02005644 if (startcol != NULL)
5645 *startcol = col;
5646
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005647 // Return value -2 means the user complete function wants to cancel the
5648 // complete without an error, do the same if the function did not execute
5649 // successfully.
5650 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005651 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005652 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005653 if (col == -3)
5654 {
Girish Palyacbe53192025-04-14 22:13:15 +02005655 if (is_cpt_function)
5656 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005657 ctrl_x_mode = CTRL_X_NORMAL;
5658 edit_submode = NULL;
5659 if (!shortmess(SHM_COMPLETIONMENU))
5660 msg_clr_cmdline();
5661 return FAIL;
5662 }
5663
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005664 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005665 // completion.
5666 compl_opt_refresh_always = FALSE;
5667 compl_opt_suppress_empty = FALSE;
5668
Girish Palyacbe53192025-04-14 22:13:15 +02005669 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005670 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005671
5672 // Setup variables for completion. Need to obtain "line" again,
5673 // it may have become invalid.
5674 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02005675 len = curs_col - col;
5676 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
5677 compl_pat->string = vim_strnsave(line + col, (size_t)len);
5678 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005679 {
Girish Palyacbe53192025-04-14 22:13:15 +02005680 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005681 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005682 }
Girish Palyacbe53192025-04-14 22:13:15 +02005683 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005684
Girish Palyacbe53192025-04-14 22:13:15 +02005685 if (!is_cpt_function)
5686 {
5687 compl_col = col;
5688 compl_length = len;
5689 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005690 ret = OK;
5691#endif
5692
5693 return ret;
5694}
5695
5696/*
5697 * Get the pattern, column and length for spell completion.
5698 * Sets the global variables: compl_col, compl_length and compl_pattern.
5699 * Uses the global variable: spell_bad_len
5700 */
5701 static int
5702get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5703{
5704 int ret = FAIL;
5705#ifdef FEAT_SPELL
5706 char_u *line;
5707
5708 if (spell_bad_len > 0)
5709 compl_col = curs_col - spell_bad_len;
5710 else
5711 compl_col = spell_word_start(startcol);
5712 if (compl_col >= (colnr_T)startcol)
5713 {
5714 compl_length = 0;
5715 compl_col = curs_col;
5716 }
5717 else
5718 {
5719 spell_expand_check_cap(compl_col);
5720 compl_length = (int)curs_col - compl_col;
5721 }
5722 // Need to obtain "line" again, it may have become invalid.
5723 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005724 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5725 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005726 {
John Marriott5e6ea922024-11-23 14:01:57 +01005727 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005728 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005729 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005730
John Marriott5e6ea922024-11-23 14:01:57 +01005731 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005732 ret = OK;
5733#endif
5734
5735 return ret;
5736}
5737
5738/*
5739 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005740 * "startcol" - start column number of the completion pattern/text
5741 * "cur_col" - current cursor column
5742 * On return, "line_invalid" is set to TRUE, if the current line may have
5743 * become invalid and needs to be fetched again.
5744 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005745 */
5746 static int
5747compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5748{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005749 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005750 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5751 && !thesaurus_func_complete(ctrl_x_mode)))
5752 {
5753 return get_normal_compl_info(line, startcol, curs_col);
5754 }
5755 else if (ctrl_x_mode_line_or_eval())
5756 {
5757 return get_wholeline_compl_info(line, curs_col);
5758 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005759 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005760 {
5761 return get_filename_compl_info(line, startcol, curs_col);
5762 }
5763 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5764 {
5765 return get_cmdline_compl_info(line, curs_col);
5766 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005767 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005768 || thesaurus_func_complete(ctrl_x_mode))
5769 {
Girish Palyacbe53192025-04-14 22:13:15 +02005770 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005771 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005772 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005773 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005774 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005775 {
5776 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5777 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005778 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005779 }
5780 else
5781 {
5782 internal_error("ins_complete()");
5783 return FAIL;
5784 }
5785
5786 return OK;
5787}
5788
5789/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005790 * Continue an interrupted completion mode search in "line".
5791 *
5792 * If this same ctrl_x_mode has been interrupted use the text from
5793 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5794 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5795 * the same line as the cursor then fix it (the line has been split because it
5796 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5797 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005798 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005799 static void
5800ins_compl_continue_search(char_u *line)
5801{
5802 // it is a continued search
5803 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005804 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5805 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005806 {
5807 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5808 {
5809 // line (probably) wrapped, set compl_startpos to the
5810 // first non_blank in the line, if it is not a wordchar
5811 // include it to get a better pattern, but then we don't
5812 // want the "\\<" prefix, check it below
5813 compl_col = (colnr_T)getwhitecols(line);
5814 compl_startpos.col = compl_col;
5815 compl_startpos.lnum = curwin->w_cursor.lnum;
5816 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5817 }
5818 else
5819 {
5820 // S_IPOS was set when we inserted a word that was at the
5821 // beginning of the line, which means that we'll go to SOL
5822 // mode but first we need to redefine compl_startpos
5823 if (compl_cont_status & CONT_S_IPOS)
5824 {
5825 compl_cont_status |= CONT_SOL;
5826 compl_startpos.col = (colnr_T)(skipwhite(
5827 line + compl_length
5828 + compl_startpos.col) - line);
5829 }
5830 compl_col = compl_startpos.col;
5831 }
5832 compl_length = curwin->w_cursor.col - (int)compl_col;
5833 // IObuff is used to add a "word from the next line" would we
5834 // have enough space? just being paranoid
5835#define MIN_SPACE 75
5836 if (compl_length > (IOSIZE - MIN_SPACE))
5837 {
5838 compl_cont_status &= ~CONT_SOL;
5839 compl_length = (IOSIZE - MIN_SPACE);
5840 compl_col = curwin->w_cursor.col - compl_length;
5841 }
5842 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5843 if (compl_length < 1)
5844 compl_cont_status &= CONT_LOCAL;
5845 }
5846 else if (ctrl_x_mode_line_or_eval())
5847 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5848 else
5849 compl_cont_status = 0;
5850}
5851
5852/*
5853 * start insert mode completion
5854 */
5855 static int
5856ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005857{
5858 char_u *line;
5859 int startcol = 0; // column where searched text starts
5860 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005861 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005862 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005863 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005864
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005865 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005866
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005867 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005868 did_si = FALSE;
5869 can_si = FALSE;
5870 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005871 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005872 return FAIL;
5873
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005874 line = ml_get(curwin->w_cursor.lnum);
5875 curs_col = curwin->w_cursor.col;
5876 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005877 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005878
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005879 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5880 && compl_cont_mode == ctrl_x_mode)
5881 // this same ctrl-x_mode was interrupted previously. Continue the
5882 // completion.
5883 ins_compl_continue_search(line);
5884 else
5885 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005886
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005887 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005888 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005889 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005890 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005891 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5892 compl_cont_status = 0;
5893 compl_cont_status |= CONT_N_ADDS;
5894 compl_startpos = curwin->w_cursor;
5895 startcol = (int)curs_col;
5896 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005897 }
5898
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005899 // Work out completion pattern and original text -- webb
5900 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5901 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005902 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5903 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005904 // restore did_ai, so that adding comment leader works
5905 did_ai = save_did_ai;
5906 return FAIL;
5907 }
5908 // If "line" was changed while getting completion info get it again.
5909 if (line_invalid)
5910 line = ml_get(curwin->w_cursor.lnum);
5911
glepnir7cfe6932024-09-15 20:06:28 +02005912 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005913 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005914 {
5915 edit_submode_pre = (char_u *)_(" Adding");
5916 if (ctrl_x_mode_line_or_eval())
5917 {
5918 // Insert a new line, keep indentation but ignore 'comments'.
5919 char_u *old = curbuf->b_p_com;
5920
5921 curbuf->b_p_com = (char_u *)"";
5922 compl_startpos.lnum = curwin->w_cursor.lnum;
5923 compl_startpos.col = compl_col;
5924 ins_eol('\r');
5925 curbuf->b_p_com = old;
5926 compl_length = 0;
5927 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01005928 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005929 }
glepnir7cfe6932024-09-15 20:06:28 +02005930 else if (ctrl_x_mode_normal() && in_fuzzy)
5931 {
5932 compl_startpos = curwin->w_cursor;
5933 compl_cont_status &= CONT_S_IPOS;
5934 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005935 }
5936 else
5937 {
5938 edit_submode_pre = NULL;
5939 compl_startpos.col = compl_col;
5940 }
5941
5942 if (compl_cont_status & CONT_LOCAL)
5943 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5944 else
5945 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5946
5947 // If any of the original typed text has been changed we need to fix
5948 // the redo buffer.
5949 ins_compl_fixRedoBufForLeader(NULL);
5950
5951 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005952 VIM_CLEAR_STRING(compl_orig_text);
5953 compl_orig_text.length = (size_t)compl_length;
5954 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005955 if (p_ic)
5956 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01005957 if (compl_orig_text.string == NULL
5958 || ins_compl_add(compl_orig_text.string,
5959 (int)compl_orig_text.length,
5960 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005961 {
John Marriott5e6ea922024-11-23 14:01:57 +01005962 VIM_CLEAR_STRING(compl_pattern);
5963 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005964 return FAIL;
5965 }
5966
5967 // showmode might reset the internal line pointers, so it must
5968 // be called before line = ml_get(), or when this address is no
5969 // longer needed. -- Acevedo.
5970 edit_submode_extra = (char_u *)_("-- Searching...");
5971 edit_submode_highl = HLF_COUNT;
5972 showmode();
5973 edit_submode_extra = NULL;
5974 out_flush();
5975
5976 return OK;
5977}
5978
5979/*
5980 * display the completion status message
5981 */
5982 static void
5983ins_compl_show_statusmsg(void)
5984{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005985 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005986 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005987 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005988 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005989 ? (char_u *)_("Hit end of paragraph")
5990 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005991 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005992 }
5993
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005994 if (edit_submode_extra == NULL)
5995 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005996 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005997 {
5998 edit_submode_extra = (char_u *)_("Back at original");
5999 edit_submode_highl = HLF_W;
6000 }
6001 else if (compl_cont_status & CONT_S_IPOS)
6002 {
6003 edit_submode_extra = (char_u *)_("Word from other line");
6004 edit_submode_highl = HLF_COUNT;
6005 }
6006 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6007 {
6008 edit_submode_extra = (char_u *)_("The only match");
6009 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006010 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006011 }
6012 else
6013 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006014#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006015 // Update completion sequence number when needed.
6016 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006017 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006018#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006019 // The match should always have a sequence number now, this is
6020 // just a safety check.
6021 if (compl_curr_match->cp_number != -1)
6022 {
6023 // Space for 10 text chars. + 2x10-digit no.s = 31.
6024 // Translations may need more than twice that.
6025 static char_u match_ref[81];
6026
6027 if (compl_matches > 0)
6028 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006029 _("match %d of %d"),
6030 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006031 else
6032 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006033 _("match %d"),
6034 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006035 edit_submode_extra = match_ref;
6036 edit_submode_highl = HLF_R;
6037 if (dollar_vcol >= 0)
6038 curs_columns(FALSE);
6039 }
6040 }
6041 }
6042
6043 // Show a message about what (completion) mode we're in.
6044 if (!compl_opt_suppress_empty)
6045 {
6046 showmode();
6047 if (!shortmess(SHM_COMPLETIONMENU))
6048 {
6049 if (edit_submode_extra != NULL)
6050 {
6051 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006052 {
6053 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006054 msg_attr((char *)edit_submode_extra,
6055 edit_submode_highl < HLF_COUNT
6056 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006057 msg_hist_off = FALSE;
6058 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006059 }
6060 else
6061 msg_clr_cmdline(); // necessary for "noshowmode"
6062 }
6063 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006064}
6065
6066/*
6067 * Do Insert mode completion.
6068 * Called when character "c" was typed, which has a meaning for completion.
6069 * Returns OK if completion was done, FAIL if something failed (out of mem).
6070 */
6071 int
6072ins_complete(int c, int enable_pum)
6073{
6074 int n;
6075 int save_w_wrow;
6076 int save_w_leftcol;
6077 int insert_match;
6078
6079 compl_direction = ins_compl_key2dir(c);
6080 insert_match = ins_compl_use_match(c);
6081
6082 if (!compl_started)
6083 {
6084 if (ins_compl_start() == FAIL)
6085 return FAIL;
6086 }
6087 else if (insert_match && stop_arrow() == FAIL)
6088 return FAIL;
6089
glepnircf7f0122025-04-15 19:02:00 +02006090 compl_curr_win = curwin;
6091 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006092 compl_shown_match = compl_curr_match;
6093 compl_shows_dir = compl_direction;
6094
6095 // Find next match (and following matches).
6096 save_w_wrow = curwin->w_wrow;
6097 save_w_leftcol = curwin->w_leftcol;
6098 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6099
6100 // may undisplay the popup menu
6101 ins_compl_upd_pum();
6102
6103 if (n > 1) // all matches have been found
6104 compl_matches = n;
6105 compl_curr_match = compl_shown_match;
6106 compl_direction = compl_shows_dir;
6107
6108 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6109 // mode.
6110 if (got_int && !global_busy)
6111 {
6112 (void)vgetc();
6113 got_int = FALSE;
6114 }
6115
6116 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006117 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006118 {
6119 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6120 // because we couldn't expand anything at first place, but if we used
6121 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6122 // (such as M in M'exico) if not tried already. -- Acevedo
6123 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006124 || compl_status_adding()
6125 || (ctrl_x_mode_not_default()
6126 && !ctrl_x_mode_path_patterns()
6127 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006128 compl_cont_status &= ~CONT_N_ADDS;
6129 }
6130
6131 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6132 compl_cont_status |= CONT_S_IPOS;
6133 else
6134 compl_cont_status &= ~CONT_S_IPOS;
6135
6136 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006137
6138 // Show the popup menu, unless we got interrupted.
6139 if (enable_pum && !compl_interrupted)
6140 show_pum(save_w_wrow, save_w_leftcol);
6141
6142 compl_was_interrupted = compl_interrupted;
6143 compl_interrupted = FALSE;
6144
6145 return OK;
6146}
6147
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006148/*
6149 * Remove (if needed) and show the popup menu
6150 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006151 static void
6152show_pum(int prev_w_wrow, int prev_w_leftcol)
6153{
6154 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006155 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006156 RedrawingDisabled = 0;
6157
6158 // If the cursor moved or the display scrolled we need to remove the pum
6159 // first.
6160 setcursor();
6161 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6162 ins_compl_del_pum();
6163
6164 ins_compl_show_pum();
6165 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006166
6167 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006168}
6169
6170/*
6171 * Looks in the first "len" chars. of "src" for search-metachars.
6172 * If dest is not NULL the chars. are copied there quoting (with
6173 * a backslash) the metachars, and dest would be NUL terminated.
6174 * Returns the length (needed) of dest
6175 */
6176 static unsigned
6177quote_meta(char_u *dest, char_u *src, int len)
6178{
6179 unsigned m = (unsigned)len + 1; // one extra for the NUL
6180
6181 for ( ; --len >= 0; src++)
6182 {
6183 switch (*src)
6184 {
6185 case '.':
6186 case '*':
6187 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006188 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006189 break;
6190 // FALLTHROUGH
6191 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006192 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006193 break;
6194 // FALLTHROUGH
6195 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006196 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006197 break;
6198 // FALLTHROUGH
6199 case '^': // currently it's not needed.
6200 case '$':
6201 m++;
6202 if (dest != NULL)
6203 *dest++ = '\\';
6204 break;
6205 }
6206 if (dest != NULL)
6207 *dest++ = *src;
6208 // Copy remaining bytes of a multibyte character.
6209 if (has_mbyte)
6210 {
6211 int i, mb_len;
6212
6213 mb_len = (*mb_ptr2len)(src) - 1;
6214 if (mb_len > 0 && len >= mb_len)
6215 for (i = 0; i < mb_len; ++i)
6216 {
6217 --len;
6218 ++src;
6219 if (dest != NULL)
6220 *dest++ = *src;
6221 }
6222 }
6223 }
6224 if (dest != NULL)
6225 *dest = NUL;
6226
6227 return m;
6228}
6229
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006230#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006231 void
6232free_insexpand_stuff(void)
6233{
John Marriott5e6ea922024-11-23 14:01:57 +01006234 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006235# ifdef FEAT_EVAL
6236 free_callback(&cfu_cb);
6237 free_callback(&ofu_cb);
6238 free_callback(&tsrfu_cb);
6239# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006240}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006241#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006242
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006243#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006244/*
6245 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6246 * spelled word, if there is one.
6247 */
6248 static void
6249spell_back_to_badword(void)
6250{
6251 pos_T tpos = curwin->w_cursor;
6252
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006253 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006254 if (curwin->w_cursor.col != tpos.col)
6255 start_arrow(&tpos);
6256}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006257#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006258
6259/*
6260 * Reset the info associated with completion sources.
6261 */
6262 static void
6263cpt_compl_src_clear(void)
6264{
6265 VIM_CLEAR(cpt_func_refresh_always);
6266 cpt_value_idx = -1;
6267 cpt_value_count = 0;
6268}
6269
6270/*
6271 * Initialize the info associated with completion sources.
6272 */
6273 static int
6274cpt_compl_src_init(char_u *cpt_str)
6275{
6276 int count = 0;
6277 char_u *p = cpt_str;
6278
6279 while (*p)
6280 {
6281 while (*p == ',' || *p == ' ') // Skip delimiters
6282 p++;
6283 if (*p) // If not end of string, count this segment
6284 {
6285 count++;
6286 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6287 }
6288 }
6289 cpt_compl_src_clear();
6290 cpt_value_count = count;
6291 if (count > 0)
6292 {
6293 cpt_func_refresh_always = ALLOC_CLEAR_MULT(int, count);
6294 if (cpt_func_refresh_always == NULL)
6295 {
6296 cpt_value_count = 0;
6297 return FAIL;
6298 }
6299 }
6300 return OK;
6301}
6302
6303/*
6304 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6305 */
6306 static int
6307is_cpt_func_refresh_always(void)
6308{
6309#ifdef FEAT_COMPL_FUNC
6310 int i;
6311
6312 for (i = 0; i < cpt_value_count; i++)
6313 if (cpt_func_refresh_always[i])
6314 return TRUE;
6315#endif
6316 return FALSE;
6317}
6318
6319/*
6320 * Make the completion list non-cyclic.
6321 */
6322#ifdef FEAT_COMPL_FUNC
6323 static void
6324ins_compl_make_linear(void)
6325{
6326 compl_T *m;
6327
6328 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6329 return;
6330 m = compl_first_match->cp_prev;
6331 m->cp_next = NULL;
6332 compl_first_match->cp_prev = NULL;
6333}
6334#endif
6335
6336/*
6337 * Remove the matches linked to the current completion source (as indicated by
6338 * cpt_value_idx) from the completion list.
6339 */
6340#ifdef FEAT_COMPL_FUNC
6341 static compl_T *
6342remove_old_matches(void)
6343{
6344 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6345 compl_T *current, *next;
6346 int compl_shown_removed = FALSE;
6347 int forward = compl_dir_forward();
6348
6349 // Identify the sublist of old matches that needs removal
6350 for (current = compl_first_match; current != NULL; current = current->cp_next)
6351 {
6352 if (current->cp_cpt_value_idx < cpt_value_idx && (forward || (!forward && !insert_at)))
6353 insert_at = current;
6354
6355 if (current->cp_cpt_value_idx == cpt_value_idx)
6356 {
6357 if (!sublist_start)
6358 sublist_start = current;
6359 sublist_end = current;
6360 if (!compl_shown_removed && compl_shown_match == current)
6361 compl_shown_removed = TRUE;
6362 }
6363
6364 if ((forward && current->cp_cpt_value_idx > cpt_value_idx) || (!forward && insert_at))
6365 break;
6366 }
6367
6368 // Re-assign compl_shown_match if necessary
6369 if (compl_shown_removed)
6370 {
6371 if (forward)
6372 compl_shown_match = compl_first_match;
6373 else
6374 { // Last node will have the prefix that is being completed
6375 for (current = compl_first_match; current->cp_next != NULL; current = current->cp_next)
6376 ;
6377 compl_shown_match = current;
6378 }
6379 }
6380
6381 if (!sublist_start) // No nodes to remove
6382 return insert_at;
6383
6384 // Update links to remove sublist
6385 if (sublist_start->cp_prev)
6386 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6387 else
6388 compl_first_match = sublist_end->cp_next;
6389
6390 if (sublist_end->cp_next)
6391 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6392
6393 // Free all nodes in the sublist
6394 sublist_end->cp_next = NULL;
6395 for (current = sublist_start; current != NULL; current = next)
6396 {
6397 next = current->cp_next;
6398 ins_compl_item_free(current);
6399 }
6400
6401 return insert_at;
6402}
6403#endif
6404
6405/*
6406 * Retrieve completion matches using the callback function "cb" and store the
6407 * 'refresh:always' flag.
6408 */
6409#ifdef FEAT_COMPL_FUNC
6410 static void
6411get_cpt_func_completion_matches(callback_T *cb UNUSED)
6412{
6413 int ret;
6414 int startcol;
6415
6416 VIM_CLEAR_STRING(cpt_compl_pattern);
6417 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6418 if (ret == FAIL && startcol == -3)
6419 cpt_func_refresh_always[cpt_value_idx] = FALSE;
6420 else if (ret == OK)
6421 {
6422 expand_by_function(0, cpt_compl_pattern.string, cb);
6423 cpt_func_refresh_always[cpt_value_idx] = compl_opt_refresh_always;
6424 compl_opt_refresh_always = FALSE;
6425 }
6426}
6427#endif
6428
6429/*
6430 * Retrieve completion matches from functions in the 'cpt' option where the
6431 * 'refresh:always' flag is set.
6432 */
6433 static void
6434cpt_compl_refresh(void)
6435{
6436#ifdef FEAT_COMPL_FUNC
6437 char_u *cpt;
6438 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006439 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006440
6441 // Make the completion list linear (non-cyclic)
6442 ins_compl_make_linear();
6443 // Make a copy of 'cpt' in case the buffer gets wiped out
6444 cpt = vim_strsave(curbuf->b_p_cpt);
6445
6446 cpt_value_idx = 0;
6447 for (p = cpt; *p; cpt_value_idx++)
6448 {
6449 while (*p == ',' || *p == ' ') // Skip delimiters
6450 p++;
6451
6452 if (cpt_func_refresh_always[cpt_value_idx])
6453 {
6454 if (*p == 'o')
6455 cb = &curbuf->b_ofu_cb;
6456 else if (*p == 'f')
6457 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6458 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6459 if (cb)
6460 {
6461 compl_curr_match = remove_old_matches();
6462 get_cpt_func_completion_matches(cb);
6463 }
6464 }
6465
6466 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6467 }
6468 cpt_value_idx = -1;
6469
6470 vim_free(cpt);
6471 // Make the list cyclic
6472 compl_matches = ins_compl_make_cyclic();
6473#endif
6474}