blob: f4449c0bfe954bc90ef08d25e9eef3930e1c906f [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
Girish Palyab1565882025-04-15 20:16:00 +0200108 int cp_score; // fuzzy match score or proximity 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/*
Girish Palyab1565882025-04-15 20:16:00 +0200796 * Returns TRUE if matches should be sorted based on proximity to the cursor.
797 */
798 static int
799is_nearest_active(void)
800{
801 unsigned int flags = get_cot_flags();
802
803 return (flags & COT_NEAREST) && !(flags & COT_FUZZY);
804}
805
806/*
807 * Repositions a match in the completion list based on its proximity score.
808 * If the match is at the head and has a higher score than the next node,
809 * or if it's in the middle/tail and has a lower score than the previous node,
810 * it is moved to the correct position while maintaining ascending order.
811 */
812 static void
813reposition_match(compl_T *match)
814{
815 compl_T *insert_before = NULL;
816 compl_T *insert_after = NULL;
817
818 // Node is at head and score is too big
819 if (!match->cp_prev)
820 {
821 if (match->cp_next && match->cp_next->cp_score > 0 &&
822 match->cp_next->cp_score < match->cp_score)
823 {
824 // <c-p>: compl_first_match is at head and newly inserted node
825 compl_first_match = compl_curr_match = match->cp_next;
826 // Find the correct position in ascending order
827 insert_before = match->cp_next;
828 do
829 {
830 insert_after = insert_before;
831 insert_before = insert_before->cp_next;
832 } while (insert_before && insert_before->cp_score > 0 &&
833 insert_before->cp_score < match->cp_score);
834 }
835 else
836 return;
837 }
838 // Node is at tail or in the middle but score is too small
839 else
840 {
841 if (match->cp_prev->cp_score > 0 && match->cp_prev->cp_score > match->cp_score)
842 {
843 // <c-n>: compl_curr_match (and newly inserted match) is at tail
844 if (!match->cp_next)
845 compl_curr_match = compl_curr_match->cp_prev;
846 // Find the correct position in ascending order
847 insert_after = match->cp_prev;
848 do
849 {
850 insert_before = insert_after;
851 insert_after = insert_after->cp_prev;
852 } while (insert_after && insert_after->cp_score > 0 &&
853 insert_after->cp_score > match->cp_score);
854 }
855 else
856 return;
857 }
858
859 if (insert_after)
860 {
861 // Remove the match from its current position
862 if (match->cp_prev)
863 match->cp_prev->cp_next = match->cp_next;
864 else
865 compl_first_match = match->cp_next;
866 if (match->cp_next)
867 match->cp_next->cp_prev = match->cp_prev;
868
869 // Insert the match at the correct position
870 match->cp_next = insert_before;
871 match->cp_prev = insert_after;
872 insert_after->cp_next = match;
873 insert_before->cp_prev = match;
874 }
875}
876
877/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000878 * Add a match to the list of matches. The arguments are:
879 * str - text of the match to add
880 * len - length of "str". If -1, then the length of "str" is
881 * computed.
882 * fname - file name to associate with this match.
883 * cptext - list of strings to use with this match (for abbr, menu, info
884 * and kind)
885 * user_data - user supplied data (any vim type) for this match
886 * cdir - match direction. If 0, use "compl_direction".
887 * flags_arg - match flags (cp_flags)
888 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100889 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000890 * If "cdir" is FORWARD, then the match is added after the current match.
891 * Otherwise, it is added before the current match.
892 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100893 * If the given string is already in the list of completions, then return
894 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
895 * maybe because alloc() returns NULL, then FAIL is returned.
896 */
897 static int
898ins_compl_add(
899 char_u *str,
900 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100901 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100902 char_u **cptext, // extra text for popup menu or NULL
903 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100904 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200905 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200906 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100907 int *user_hl, // user abbr/kind hlattr
908 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100909{
glepnirf31cfa22025-03-06 21:59:13 +0100910 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100911 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200912 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100913 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100914
Bram Moolenaarceb06192021-04-04 15:05:22 +0200915 if (flags & CP_FAST)
916 fast_breakcheck();
917 else
918 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100919 if (got_int)
920 return FAIL;
921 if (len < 0)
922 len = (int)STRLEN(str);
923
924 // If the same match is already present, don't add it.
925 if (compl_first_match != NULL && !adup)
926 {
927 match = compl_first_match;
928 do
929 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000930 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100931 && STRNCMP(match->cp_str.string, str, len) == 0
932 && ((int)match->cp_str.length <= len
933 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200934 {
935 if (is_nearest_active() && score > 0 && score < match->cp_score)
936 {
937 match->cp_score = score;
938 reposition_match(match);
939 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100940 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200941 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100942 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000943 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100944 }
945
946 // Remove any popup menu before changing the list of matches.
947 ins_compl_del_pum();
948
949 // Allocate a new match structure.
950 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200951 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100952 if (match == NULL)
953 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100954 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100955 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100956 {
957 vim_free(match);
958 return FAIL;
959 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100960
John Marriott5e6ea922024-11-23 14:01:57 +0100961 match->cp_str.length = len;
962
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100963 // match-fname is:
964 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200965 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100966 // - NULL otherwise. --Acevedo
967 if (fname != NULL
968 && compl_curr_match != NULL
969 && compl_curr_match->cp_fname != NULL
970 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
971 match->cp_fname = compl_curr_match->cp_fname;
972 else if (fname != NULL)
973 {
974 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200975 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100976 }
977 else
978 match->cp_fname = NULL;
979 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100980 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
981 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100982 match->cp_score = score;
Girish Palyacbe53192025-04-14 22:13:15 +0200983 match->cp_cpt_value_idx = cpt_value_idx;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100984
985 if (cptext != NULL)
986 {
987 int i;
988
989 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100990 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100991 if (cptext[i] != NULL && *cptext[i] != NUL)
992 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100993 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100994 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100995#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100996 if (user_data != NULL)
997 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100998#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100999
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00001000 // Link the new match structure after (FORWARD) or before (BACKWARD) the
1001 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002 if (compl_first_match == NULL)
1003 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01001004 else if (cfc_has_mode() && score > 0 && compl_get_longest)
1005 {
1006 current = compl_first_match->cp_next;
1007 prev = compl_first_match;
1008 inserted = FALSE;
1009 // The direction is ignored when using longest and
1010 // completefuzzycollect, because matches are inserted
1011 // and sorted by score.
1012 while (current != NULL && current != compl_first_match)
1013 {
1014 if (current->cp_score < score)
1015 {
1016 match->cp_next = current;
1017 match->cp_prev = current->cp_prev;
1018 if (current->cp_prev)
1019 current->cp_prev->cp_next = match;
1020 current->cp_prev = match;
1021 inserted = TRUE;
1022 break;
1023 }
1024 prev = current;
1025 current = current->cp_next;
1026 }
1027 if (!inserted)
1028 {
1029 prev->cp_next = match;
1030 match->cp_prev = prev;
1031 match->cp_next = compl_first_match;
1032 compl_first_match->cp_prev = match;
1033 }
1034 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001035 else if (dir == FORWARD)
1036 {
1037 match->cp_next = compl_curr_match->cp_next;
1038 match->cp_prev = compl_curr_match;
1039 }
1040 else // BACKWARD
1041 {
1042 match->cp_next = compl_curr_match;
1043 match->cp_prev = compl_curr_match->cp_prev;
1044 }
1045 if (match->cp_next)
1046 match->cp_next->cp_prev = match;
1047 if (match->cp_prev)
1048 match->cp_prev->cp_next = match;
1049 else // if there's nothing before, it is the first match
1050 compl_first_match = match;
1051 compl_curr_match = match;
1052
Girish Palyab1565882025-04-15 20:16:00 +02001053 if (is_nearest_active() && score > 0)
1054 reposition_match(match);
1055
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001056 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +01001057 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001058 ins_compl_longest_match(match);
1059
1060 return OK;
1061}
1062
1063/*
1064 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001065 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001066 */
1067 static int
1068ins_compl_equal(compl_T *match, char_u *str, int len)
1069{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001070 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001071 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001072 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001073 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1074 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001075}
1076
1077/*
glepnir6a38aff2024-12-16 21:56:16 +01001078 * when len is -1 mean use whole length of p otherwise part of p
1079 */
1080 static void
1081ins_compl_insert_bytes(char_u *p, int len)
1082{
1083 if (len == -1)
1084 len = (int)STRLEN(p);
1085 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001086 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001087}
1088
1089/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001090 * Checks if the column is within the currently inserted completion text
1091 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001092 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001093 */
1094 int
glepnir76bdb822025-02-08 19:04:51 +01001095ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001096{
glepnir76bdb822025-02-08 19:04:51 +01001097 int start_col;
1098 int attr;
1099
1100 if ((get_cot_flags() & COT_FUZZY)
1101 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001102 return -1;
1103
glepnir76bdb822025-02-08 19:04:51 +01001104 start_col = compl_col + (int)ins_compl_leader_len();
1105 if (!ins_compl_has_multiple())
1106 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1107
1108 // Multiple lines
1109 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1110 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1111 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1112 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001113
1114 return -1;
1115}
1116
1117/*
glepnir76bdb822025-02-08 19:04:51 +01001118 * Returns TRUE if the current completion string contains newline characters,
1119 * indicating it's a multi-line completion.
1120 */
1121 static int
1122ins_compl_has_multiple(void)
1123{
1124 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1125}
1126
1127/*
1128 * Returns TRUE if the given line number falls within the range of a multi-line
1129 * completion, i.e. between the starting line (compl_lnum) and current cursor
1130 * line. Always returns FALSE for single-line completions.
1131 */
1132 int
1133ins_compl_lnum_in_range(linenr_T lnum)
1134{
1135 if (!ins_compl_has_multiple())
1136 return FALSE;
1137 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1138}
1139
1140/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001141 * Reduce the longest common string for match "match".
1142 */
1143 static void
1144ins_compl_longest_match(compl_T *match)
1145{
1146 char_u *p, *s;
1147 int c1, c2;
1148 int had_match;
1149
John Marriott5e6ea922024-11-23 14:01:57 +01001150 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001151 {
1152 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001153 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1154 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001155 return;
1156
John Marriott5e6ea922024-11-23 14:01:57 +01001157 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001159 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001160
1161 // When the match isn't there (to avoid matching itself) remove it
1162 // again after redrawing.
1163 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001164 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001165 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001166
1167 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001168 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001169
1170 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001171 p = compl_leader.string;
1172 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001173 while (*p != NUL)
1174 {
1175 if (has_mbyte)
1176 {
1177 c1 = mb_ptr2char(p);
1178 c2 = mb_ptr2char(s);
1179 }
1180 else
1181 {
1182 c1 = *p;
1183 c2 = *s;
1184 }
1185 if ((match->cp_flags & CP_ICASE)
1186 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1187 break;
1188 if (has_mbyte)
1189 {
1190 MB_PTR_ADV(p);
1191 MB_PTR_ADV(s);
1192 }
1193 else
1194 {
1195 ++p;
1196 ++s;
1197 }
1198 }
1199
1200 if (*p != NUL)
1201 {
1202 // Leader was shortened, need to change the inserted text.
1203 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001204 compl_leader.length = (size_t)(p - compl_leader.string);
1205
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001206 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001207 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001208
1209 // When the match isn't there (to avoid matching itself) remove it
1210 // again after redrawing.
1211 if (!had_match)
1212 ins_compl_delete();
1213 }
1214
1215 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001216}
1217
1218/*
1219 * Add an array of matches to the list of matches.
1220 * Frees matches[].
1221 */
1222 static void
1223ins_compl_add_matches(
1224 int num_matches,
1225 char_u **matches,
1226 int icase)
1227{
1228 int i;
1229 int add_r = OK;
1230 int dir = compl_direction;
1231
1232 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001233 {
1234 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001235 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001236 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001237 // if dir was BACKWARD then honor it just once
1238 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001239 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001240 FreeWild(num_matches, matches);
1241}
1242
1243/*
1244 * Make the completion list cyclic.
1245 * Return the number of matches (excluding the original).
1246 */
1247 static int
1248ins_compl_make_cyclic(void)
1249{
1250 compl_T *match;
1251 int count = 0;
1252
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001253 if (compl_first_match == NULL)
1254 return 0;
1255
1256 // Find the end of the list.
1257 match = compl_first_match;
1258 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001259 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001260 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001261 match = match->cp_next;
1262 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001263 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001264 match->cp_next = compl_first_match;
1265 compl_first_match->cp_prev = match;
1266
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001267 return count;
1268}
1269
1270/*
1271 * Return whether there currently is a shown match.
1272 */
1273 int
1274ins_compl_has_shown_match(void)
1275{
1276 return compl_shown_match == NULL
1277 || compl_shown_match != compl_shown_match->cp_next;
1278}
1279
1280/*
1281 * Return whether the shown match is long enough.
1282 */
1283 int
1284ins_compl_long_shown_match(void)
1285{
John Marriott5e6ea922024-11-23 14:01:57 +01001286 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001287 > curwin->w_cursor.col - compl_col;
1288}
1289
1290/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001291 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001292 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001293 unsigned int
1294get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001295{
zeertzjq529b9ad2024-06-05 20:27:06 +02001296 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001297}
1298
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001299/*
1300 * Update the screen and when there is any scrolling remove the popup menu.
1301 */
1302 static void
1303ins_compl_upd_pum(void)
1304{
1305 int h;
1306
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001307 if (compl_match_array == NULL)
1308 return;
1309
1310 h = curwin->w_cline_height;
1311 // Update the screen later, before drawing the popup menu over it.
1312 pum_call_update_screen();
1313 if (h != curwin->w_cline_height)
1314 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001315}
1316
1317/*
1318 * Remove any popup menu.
1319 */
1320 static void
1321ins_compl_del_pum(void)
1322{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001323 if (compl_match_array == NULL)
1324 return;
1325
1326 pum_undisplay();
1327 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001328}
1329
1330/*
1331 * Return TRUE if the popup menu should be displayed.
1332 */
1333 int
1334pum_wanted(void)
1335{
1336 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001337 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001338 return FALSE;
1339
1340 // The display looks bad on a B&W display.
1341 if (t_colors < 8
1342#ifdef FEAT_GUI
1343 && !gui.in_use
1344#endif
1345 )
1346 return FALSE;
1347 return TRUE;
1348}
1349
1350/*
1351 * Return TRUE if there are two or more matches to be shown in the popup menu.
1352 * One if 'completopt' contains "menuone".
1353 */
1354 static int
1355pum_enough_matches(void)
1356{
1357 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001358 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001359
1360 // Don't display the popup menu if there are no matches or there is only
1361 // one (ignoring the original text).
1362 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001363 do
1364 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001365 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001366 break;
1367 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001368 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001369
zeertzjq529b9ad2024-06-05 20:27:06 +02001370 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001371 return (i >= 1);
1372 return (i >= 2);
1373}
1374
Bram Moolenaar3075a452021-11-17 15:51:52 +00001375#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001376/*
1377 * Allocate Dict for the completed item.
1378 * { word, abbr, menu, kind, info }
1379 */
1380 static dict_T *
1381ins_compl_dict_alloc(compl_T *match)
1382{
1383 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1384
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001385 if (dict == NULL)
1386 return NULL;
1387
John Marriott5e6ea922024-11-23 14:01:57 +01001388 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001389 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1390 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1391 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1392 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1393 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1394 dict_add_string(dict, "user_data", (char_u *)"");
1395 else
1396 dict_add_tv(dict, "user_data", &match->cp_user_data);
1397
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001398 return dict;
1399}
1400
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001401/*
1402 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1403 * completion menu is changed.
1404 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001405 static void
1406trigger_complete_changed_event(int cur)
1407{
1408 dict_T *v_event;
1409 dict_T *item;
1410 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001411 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001412
1413 if (recursive)
1414 return;
1415
glepnir40891ba2025-02-10 22:18:00 +01001416 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001417 if (item == NULL)
1418 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001419 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001420 dict_add_dict(v_event, "completed_item", item);
1421 pum_set_event_info(v_event);
1422 dict_set_items_ro(v_event);
1423
1424 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001425 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001426 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001427 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001428 recursive = FALSE;
1429
Bram Moolenaar3075a452021-11-17 15:51:52 +00001430 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001431}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001432#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001433
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001434/*
glepnira218cc62024-06-03 19:32:39 +02001435 * pumitem qsort compare func
1436 */
1437 static int
zeertzjq8e567472024-06-14 20:04:42 +02001438ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001439{
1440 const int sa = (*(pumitem_T *)a).pum_score;
1441 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001442 const int ia = (*(pumitem_T *)a).pum_idx;
1443 const int ib = (*(pumitem_T *)b).pum_idx;
1444 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001445}
1446
1447/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001448 * Build a popup menu to show the completion matches.
1449 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1450 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001451 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001452 static int
1453ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001454{
1455 compl_T *compl;
1456 compl_T *shown_compl = NULL;
1457 int did_find_shown_match = FALSE;
1458 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001459 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001460 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001461 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001462 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001463 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001464 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1465 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001466 compl_T *match_head = NULL;
1467 compl_T *match_tail = NULL;
1468 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001469 int update_shown_match = fuzzy_filter;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001470
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001471 // Need to build the popup menu list.
1472 compl_match_arraysize = 0;
1473 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001474
glepnira49c0772024-11-30 10:56:30 +01001475 // If the current match is the original text don't find the first
1476 // match after it, don't highlight anything.
1477 if (match_at_original_text(compl_shown_match))
1478 shown_match_ok = TRUE;
1479
glepnire4e4d1c2025-04-02 20:18:25 +02001480 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1481 && compl_shown_match->cp_score > 0)
1482 update_shown_match = FALSE;
1483
glepnira49c0772024-11-30 10:56:30 +01001484 if (compl_leader.string != NULL
1485 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1486 && shown_match_ok == FALSE)
1487 compl_shown_match = compl_no_select ? compl_first_match
1488 : compl_first_match->cp_next;
1489
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001490 do
1491 {
glepnird4088ed2024-12-31 10:55:22 +01001492 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001493 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1494 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001495 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001496 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001497
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001498 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001499 && (compl_leader.string == NULL
1500 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001501 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001502 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001503 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001504 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001505 if (match_head == NULL)
1506 match_head = compl;
1507 else
glepnira49c0772024-11-30 10:56:30 +01001508 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001509 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001510
glepnirf400a0c2025-01-23 19:55:14 +01001511 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001512 {
1513 if (compl == compl_shown_match || did_find_shown_match)
1514 {
1515 // This item is the shown match or this is the
1516 // first displayed item after the shown match.
1517 compl_shown_match = compl;
1518 did_find_shown_match = TRUE;
1519 shown_match_ok = TRUE;
1520 }
1521 else
1522 // Remember this displayed match for when the
1523 // shown match is just below it.
1524 shown_compl = compl;
1525 cur = i;
1526 }
glepnirf400a0c2025-01-23 19:55:14 +01001527 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001528 {
1529 if (i == 0)
1530 shown_compl = compl;
1531 // Update the maximum fuzzy score and the shown match
1532 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001533 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1534 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001535 {
1536 did_find_shown_match = TRUE;
1537 max_fuzzy_score = compl->cp_score;
1538 if (!compl_no_select)
1539 compl_shown_match = compl;
1540 }
1541
glepnir3af0a8d2025-02-20 22:06:16 +01001542 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001543 {
1544 cur = i;
1545 shown_match_ok = TRUE;
1546 }
1547 }
1548 i++;
glepnir80b66202024-11-27 21:53:53 +01001549 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001550
glepnirf400a0c2025-01-23 19:55:14 +01001551 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001552 {
1553 did_find_shown_match = TRUE;
1554
1555 // When the original text is the shown match don't set
1556 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001557 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001558 shown_match_ok = TRUE;
1559
1560 if (!shown_match_ok && shown_compl != NULL)
1561 {
1562 // The shown match isn't displayed, set it to the
1563 // previously displayed match.
1564 compl_shown_match = shown_compl;
1565 shown_match_ok = TRUE;
1566 }
1567 }
glepnira49c0772024-11-30 10:56:30 +01001568 compl = compl->cp_next;
1569 } while (compl != NULL && !is_first_match(compl));
1570
1571 if (compl_match_arraysize == 0)
1572 return -1;
1573
glepnirc0b7ca42025-02-13 20:27:44 +01001574 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1575 {
1576 compl_shown_match = shown_compl;
1577 shown_match_ok = TRUE;
1578 cur = 0;
1579 }
1580
glepnira49c0772024-11-30 10:56:30 +01001581 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1582 if (compl_match_array == NULL)
1583 return -1;
1584
1585 compl = match_head;
1586 i = 0;
1587 while (compl != NULL)
1588 {
glepnir6e199932024-12-14 21:13:27 +01001589 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1590 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001591 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1592 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1593 compl_match_array[i].pum_score = compl->cp_score;
1594 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1595 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001596 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1597 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001598 match_next = compl->cp_match_next;
1599 compl->cp_match_next = NULL;
1600 compl = match_next;
1601 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001602
zeertzjqd65aa1b2025-01-25 15:29:03 +01001603 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001604 {
1605 for (i = 0; i < compl_match_arraysize; i++)
1606 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001607 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001608 qsort(compl_match_array, (size_t)compl_match_arraysize,
1609 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001610 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001611 }
glepnira218cc62024-06-03 19:32:39 +02001612
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001613 if (!shown_match_ok) // no displayed match at all
1614 cur = -1;
1615
1616 return cur;
1617}
1618
1619/*
1620 * Show the popup menu for the list of matches.
1621 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1622 */
1623 void
1624ins_compl_show_pum(void)
1625{
1626 int i;
1627 int cur = -1;
1628 colnr_T col;
1629
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001630 if (!pum_wanted() || !pum_enough_matches())
1631 return;
1632
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001633 // Update the screen later, before drawing the popup menu over it.
1634 pum_call_update_screen();
1635
1636 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001637 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001638 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001639 else
1640 {
1641 // popup menu already exists, only need to find the current item.
1642 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001643 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001644 || compl_match_array[i].pum_text
1645 == compl_shown_match->cp_text[CPT_ABBR])
1646 {
1647 cur = i;
1648 break;
1649 }
1650 }
1651
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001652 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001653 {
1654#ifdef FEAT_EVAL
1655 if (compl_started && has_completechanged())
1656 trigger_complete_changed_event(cur);
1657#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001658 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001659 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001660
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001661 // In Replace mode when a $ is displayed at the end of the line only
1662 // part of the screen would be updated. We do need to redraw here.
1663 dollar_vcol = -1;
1664
1665 // Compute the screen column of the start of the completed text.
1666 // Use the cursor to get all wrapping and other settings right.
1667 col = curwin->w_cursor.col;
1668 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001669 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001670 pum_display(compl_match_array, compl_match_arraysize, cur);
1671 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001672
glepnircbb46b42024-02-03 18:11:13 +01001673 // After adding leader, set the current match to shown match.
1674 if (compl_started && compl_curr_match != compl_shown_match)
1675 compl_curr_match = compl_shown_match;
1676
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001677#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001678 if (has_completechanged())
1679 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001680#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001681}
1682
1683#define DICT_FIRST (1) // use just first element in "dict"
1684#define DICT_EXACT (2) // "dict" is the exact name of a file
1685
1686/*
glepnir40c1c332024-06-11 19:37:04 +02001687 * Get current completion leader
1688 */
1689 char_u *
1690ins_compl_leader(void)
1691{
John Marriott5e6ea922024-11-23 14:01:57 +01001692 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1693}
1694
1695/*
1696 * Get current completion leader length
1697 */
1698 size_t
1699ins_compl_leader_len(void)
1700{
1701 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001702}
1703
1704/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001705 * Add any identifiers that match the given pattern "pat" in the list of
1706 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001707 */
1708 static void
1709ins_compl_dictionaries(
1710 char_u *dict_start,
1711 char_u *pat,
1712 int flags, // DICT_FIRST and/or DICT_EXACT
1713 int thesaurus) // Thesaurus completion
1714{
1715 char_u *dict = dict_start;
1716 char_u *ptr;
1717 char_u *buf;
1718 regmatch_T regmatch;
1719 char_u **files;
1720 int count;
1721 int save_p_scs;
1722 int dir = compl_direction;
1723
1724 if (*dict == NUL)
1725 {
1726#ifdef FEAT_SPELL
1727 // When 'dictionary' is empty and spell checking is enabled use
1728 // "spell".
1729 if (!thesaurus && curwin->w_p_spell)
1730 dict = (char_u *)"spell";
1731 else
1732#endif
1733 return;
1734 }
1735
1736 buf = alloc(LSIZE);
1737 if (buf == NULL)
1738 return;
1739 regmatch.regprog = NULL; // so that we can goto theend
1740
1741 // If 'infercase' is set, don't use 'smartcase' here
1742 save_p_scs = p_scs;
1743 if (curbuf->b_p_inf)
1744 p_scs = FALSE;
1745
1746 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1747 // to only match at the start of a line. Otherwise just match the
1748 // pattern. Also need to double backslashes.
1749 if (ctrl_x_mode_line_or_eval())
1750 {
1751 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1752 size_t len;
1753
1754 if (pat_esc == NULL)
1755 goto theend;
1756 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001757 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001758 if (ptr == NULL)
1759 {
1760 vim_free(pat_esc);
1761 goto theend;
1762 }
1763 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1764 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1765 vim_free(pat_esc);
1766 vim_free(ptr);
1767 }
1768 else
1769 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001770 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001771 if (regmatch.regprog == NULL)
1772 goto theend;
1773 }
1774
1775 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1776 regmatch.rm_ic = ignorecase(pat);
1777 while (*dict != NUL && !got_int && !compl_interrupted)
1778 {
1779 // copy one dictionary file name into buf
1780 if (flags == DICT_EXACT)
1781 {
1782 count = 1;
1783 files = &dict;
1784 }
1785 else
1786 {
1787 // Expand wildcards in the dictionary name, but do not allow
1788 // backticks (for security, the 'dict' option may have been set in
1789 // a modeline).
1790 copy_option_part(&dict, buf, LSIZE, ",");
1791# ifdef FEAT_SPELL
1792 if (!thesaurus && STRCMP(buf, "spell") == 0)
1793 count = -1;
1794 else
1795# endif
1796 if (vim_strchr(buf, '`') != NULL
1797 || expand_wildcards(1, &buf, &count, &files,
1798 EW_FILE|EW_SILENT) != OK)
1799 count = 0;
1800 }
1801
1802# ifdef FEAT_SPELL
1803 if (count == -1)
1804 {
1805 // Complete from active spelling. Skip "\<" in the pattern, we
1806 // don't use it as a RE.
1807 if (pat[0] == '\\' && pat[1] == '<')
1808 ptr = pat + 2;
1809 else
1810 ptr = pat;
1811 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1812 }
1813 else
1814# endif
1815 if (count > 0) // avoid warning for using "files" uninit
1816 {
1817 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001818 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001819 if (flags != DICT_EXACT)
1820 FreeWild(count, files);
1821 }
1822 if (flags != 0)
1823 break;
1824 }
1825
1826theend:
1827 p_scs = save_p_scs;
1828 vim_regfree(regmatch.regprog);
1829 vim_free(buf);
1830}
1831
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001832/*
1833 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1834 * skipping the word at 'skip_word'. Returns OK on success.
1835 */
1836 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001837thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001838 char_u *fname,
1839 char_u **buf_arg,
1840 int dir,
1841 char_u *skip_word)
1842{
1843 int status = OK;
1844 char_u *ptr;
1845 char_u *wstart;
1846
1847 // Add the other matches on the line
1848 ptr = *buf_arg;
1849 while (!got_int)
1850 {
1851 // Find start of the next word. Skip white
1852 // space and punctuation.
1853 ptr = find_word_start(ptr);
1854 if (*ptr == NUL || *ptr == NL)
1855 break;
1856 wstart = ptr;
1857
1858 // Find end of the word.
1859 if (has_mbyte)
1860 // Japanese words may have characters in
1861 // different classes, only separate words
1862 // with single-byte non-word characters.
1863 while (*ptr != NUL)
1864 {
1865 int l = (*mb_ptr2len)(ptr);
1866
1867 if (l < 2 && !vim_iswordc(*ptr))
1868 break;
1869 ptr += l;
1870 }
1871 else
1872 ptr = find_word_end(ptr);
1873
1874 // Add the word. Skip the regexp match.
1875 if (wstart != skip_word)
1876 {
1877 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001878 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001879 if (status == FAIL)
1880 break;
1881 }
1882 }
1883
1884 *buf_arg = ptr;
1885 return status;
1886}
1887
1888/*
1889 * Process "count" dictionary/thesaurus "files" and add the text matching
1890 * "regmatch".
1891 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001892 static void
1893ins_compl_files(
1894 int count,
1895 char_u **files,
1896 int thesaurus,
1897 int flags,
1898 regmatch_T *regmatch,
1899 char_u *buf,
1900 int *dir)
1901{
1902 char_u *ptr;
1903 int i;
1904 FILE *fp;
1905 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001906 char_u *leader = NULL;
1907 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001908 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001909 int score = 0;
1910 int len = 0;
1911 char_u *line_end = NULL;
1912
1913 if (in_fuzzy_collect)
1914 {
1915 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001916 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001917 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001918
1919 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1920 {
1921 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001922 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001923 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001924 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001925 vim_snprintf((char *)IObuff, IOSIZE,
1926 _("Scanning dictionary: %s"), (char *)files[i]);
1927 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1928 }
1929
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001930 if (fp == NULL)
1931 continue;
1932
1933 // Read dictionary file line by line.
1934 // Check each line for a match.
1935 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001936 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001937 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001938 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001939 {
glepnirf31cfa22025-03-06 21:59:13 +01001940 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001941 {
glepnirf31cfa22025-03-06 21:59:13 +01001942 ptr = regmatch->startp[0];
1943 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1944 : find_word_end(ptr);
1945 add_r = ins_compl_add_infercase(regmatch->startp[0],
1946 (int)(ptr - regmatch->startp[0]),
1947 p_ic, files[i], *dir, FALSE, 0);
1948 if (thesaurus)
1949 {
1950 // For a thesaurus, add all the words in the line
1951 ptr = buf;
1952 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1953 regmatch->startp[0]);
1954 }
1955 if (add_r == OK)
1956 // if dir was BACKWARD then honor it just once
1957 *dir = FORWARD;
1958 else if (add_r == FAIL)
1959 break;
1960 // avoid expensive call to vim_regexec() when at end
1961 // of line
1962 if (*ptr == '\n' || got_int)
1963 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001964 }
glepnirf31cfa22025-03-06 21:59:13 +01001965 }
1966 else if (in_fuzzy_collect && leader_len > 0)
1967 {
1968 line_end = find_line_end(ptr);
1969 while (ptr < line_end)
1970 {
1971 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1972 {
1973 char_u *end_ptr = ctrl_x_mode_line_or_eval()
1974 ? find_line_end(ptr) : find_word_end(ptr);
1975 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
1976 p_ic, files[i], *dir, FALSE, score);
1977 if (add_r == FAIL)
1978 break;
1979 ptr = end_ptr; // start from next word
1980 if (compl_get_longest && ctrl_x_mode_normal()
1981 && compl_first_match->cp_next
1982 && score == compl_first_match->cp_next->cp_score)
1983 compl_num_bests++;
1984 }
glepnirf31cfa22025-03-06 21:59:13 +01001985 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001986 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001987 line_breakcheck();
1988 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001989 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001990 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001991 }
1992}
1993
1994/*
1995 * Find the start of the next word.
1996 * Returns a pointer to the first char of the word. Also stops at a NUL.
1997 */
1998 char_u *
1999find_word_start(char_u *ptr)
2000{
2001 if (has_mbyte)
2002 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2003 ptr += (*mb_ptr2len)(ptr);
2004 else
2005 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2006 ++ptr;
2007 return ptr;
2008}
2009
2010/*
2011 * Find the end of the word. Assumes it starts inside a word.
2012 * Returns a pointer to just after the word.
2013 */
2014 char_u *
2015find_word_end(char_u *ptr)
2016{
2017 int start_class;
2018
2019 if (has_mbyte)
2020 {
2021 start_class = mb_get_class(ptr);
2022 if (start_class > 1)
2023 while (*ptr != NUL)
2024 {
2025 ptr += (*mb_ptr2len)(ptr);
2026 if (mb_get_class(ptr) != start_class)
2027 break;
2028 }
2029 }
2030 else
2031 while (vim_iswordc(*ptr))
2032 ++ptr;
2033 return ptr;
2034}
2035
2036/*
2037 * Find the end of the line, omitting CR and NL at the end.
2038 * Returns a pointer to just after the line.
2039 */
glepnirdd42b052025-03-08 16:52:55 +01002040 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002041find_line_end(char_u *ptr)
2042{
2043 char_u *s;
2044
2045 s = ptr + STRLEN(ptr);
2046 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2047 --s;
2048 return s;
2049}
2050
2051/*
Girish Palyacbe53192025-04-14 22:13:15 +02002052 * Free a completion item in the list
2053 */
2054 static void
2055ins_compl_item_free(compl_T *match)
2056{
2057 int i;
2058
2059 VIM_CLEAR_STRING(match->cp_str);
2060 // several entries may use the same fname, free it just once.
2061 if (match->cp_flags & CP_FREE_FNAME)
2062 vim_free(match->cp_fname);
2063 for (i = 0; i < CPT_COUNT; ++i)
2064 vim_free(match->cp_text[i]);
2065#ifdef FEAT_EVAL
2066 clear_tv(&match->cp_user_data);
2067#endif
2068 vim_free(match);
2069}
2070
2071/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002072 * Free the list of completions
2073 */
2074 static void
2075ins_compl_free(void)
2076{
2077 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002078
John Marriott5e6ea922024-11-23 14:01:57 +01002079 VIM_CLEAR_STRING(compl_pattern);
2080 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002081
2082 if (compl_first_match == NULL)
2083 return;
2084
2085 ins_compl_del_pum();
2086 pum_clear();
2087
2088 compl_curr_match = compl_first_match;
2089 do
2090 {
2091 match = compl_curr_match;
2092 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002093 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002094 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002095 compl_first_match = compl_curr_match = NULL;
2096 compl_shown_match = NULL;
2097 compl_old_match = NULL;
2098}
2099
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002100/*
2101 * Reset/clear the completion state.
2102 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002103 void
2104ins_compl_clear(void)
2105{
2106 compl_cont_status = 0;
2107 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002108 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002109 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002110 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002111 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002112 compl_curr_win = NULL;
2113 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002114 VIM_CLEAR_STRING(compl_pattern);
2115 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002116 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002117 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002118 compl_enter_selects = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02002119 cpt_compl_src_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002120#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002121 // clear v:completed_item
2122 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002123#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002124}
2125
2126/*
2127 * Return TRUE when Insert completion is active.
2128 */
2129 int
2130ins_compl_active(void)
2131{
2132 return compl_started;
2133}
2134
2135/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002136 * Return True when wp is the actual completion window
2137 */
2138 int
glepnircf7f0122025-04-15 19:02:00 +02002139ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002140{
glepnircf7f0122025-04-15 19:02:00 +02002141 return ins_compl_active() && wp == compl_curr_win
2142 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002143}
2144
2145/*
Girish Palyacbe53192025-04-14 22:13:15 +02002146 * Selected one of the matches. When FALSE, the match was either edited or
2147 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002148 */
2149 int
2150ins_compl_used_match(void)
2151{
2152 return compl_used_match;
2153}
2154
2155/*
2156 * Initialize get longest common string.
2157 */
2158 void
2159ins_compl_init_get_longest(void)
2160{
2161 compl_get_longest = FALSE;
2162}
2163
2164/*
2165 * Returns TRUE when insert completion is interrupted.
2166 */
2167 int
2168ins_compl_interrupted(void)
2169{
2170 return compl_interrupted;
2171}
2172
2173/*
2174 * Returns TRUE if the <Enter> key selects a match in the completion popup
2175 * menu.
2176 */
2177 int
2178ins_compl_enter_selects(void)
2179{
2180 return compl_enter_selects;
2181}
2182
2183/*
2184 * Return the column where the text starts that is being completed
2185 */
2186 colnr_T
2187ins_compl_col(void)
2188{
2189 return compl_col;
2190}
2191
2192/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002193 * Return the length in bytes of the text being completed
2194 */
2195 int
2196ins_compl_len(void)
2197{
2198 return compl_length;
2199}
2200
2201/*
glepnir94a045e2025-03-01 16:12:23 +01002202 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2203 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002204 */
2205 static int
2206ins_compl_has_preinsert(void)
2207{
glepnira2c55592025-02-28 17:43:42 +01002208 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002209 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2210 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002211}
2212
2213/*
2214 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2215 * the `compl_ins_end_col` range.
2216 */
2217 int
2218ins_compl_preinsert_effect(void)
2219{
2220 if (!ins_compl_has_preinsert())
2221 return FALSE;
2222
2223 return curwin->w_cursor.col < compl_ins_end_col;
2224}
2225
2226/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002227 * Delete one character before the cursor and show the subset of the matches
2228 * that match the word that is now before the cursor.
2229 * Returns the character to be used, NUL if the work is done and another char
2230 * to be got from the user.
2231 */
2232 int
2233ins_compl_bs(void)
2234{
2235 char_u *line;
2236 char_u *p;
2237
glepniredd4ac32025-01-29 18:53:51 +01002238 if (ins_compl_preinsert_effect())
2239 ins_compl_delete();
2240
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002241 line = ml_get_curline();
2242 p = line + curwin->w_cursor.col;
2243 MB_PTR_BACK(line, p);
2244
2245 // Stop completion when the whole word was deleted. For Omni completion
2246 // allow the word to be deleted, we won't match everything.
2247 // Respect the 'backspace' option.
2248 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002249 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2250 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002251 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2252 - compl_length < 0))
2253 return K_BS;
2254
2255 // Deleted more than what was used to find matches or didn't finish
2256 // finding all matches: need to look for matches all over again.
2257 if (curwin->w_cursor.col <= compl_col + compl_length
2258 || ins_compl_need_restart())
2259 ins_compl_restart();
2260
John Marriott5e6ea922024-11-23 14:01:57 +01002261 VIM_CLEAR_STRING(compl_leader);
2262 compl_leader.length = (size_t)((p - line) - compl_col);
2263 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2264 if (compl_leader.string == NULL)
2265 {
2266 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002267 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002268 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002269
2270 ins_compl_new_leader();
2271 if (compl_shown_match != NULL)
2272 // Make sure current match is not a hidden item.
2273 compl_curr_match = compl_shown_match;
2274 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002275}
2276
2277/*
2278 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2279 * be called.
2280 */
2281 static int
2282ins_compl_need_restart(void)
2283{
2284 // Return TRUE if we didn't complete finding matches or when the
2285 // 'completefunc' returned "always" in the "refresh" dictionary item.
2286 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002287 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002288 && compl_opt_refresh_always);
2289}
2290
2291/*
2292 * Called after changing "compl_leader".
2293 * Show the popup menu with a different set of matches.
2294 * May also search for matches again if the previous search was interrupted.
2295 */
2296 static void
2297ins_compl_new_leader(void)
2298{
2299 ins_compl_del_pum();
2300 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002301 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002302 compl_used_match = FALSE;
2303
2304 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002305 {
John Marriott5e6ea922024-11-23 14:01:57 +01002306 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002307 if (is_cpt_func_refresh_always())
2308 cpt_compl_refresh();
2309 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002310 else
2311 {
2312#ifdef FEAT_SPELL
2313 spell_bad_len = 0; // need to redetect bad word
2314#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002315 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002316 // the popup menu display the changed text before the cursor. Set
2317 // "compl_restarting" to avoid that the first match is inserted.
2318 pum_call_update_screen();
2319#ifdef FEAT_GUI
2320 if (gui.in_use)
2321 {
2322 // Show the cursor after the match, not after the redrawn text.
2323 setcursor();
2324 out_flush_cursor(FALSE, FALSE);
2325 }
2326#endif
2327 compl_restarting = TRUE;
2328 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2329 compl_cont_status = 0;
2330 compl_restarting = FALSE;
2331 }
2332
glepnir44180412025-02-20 22:09:48 +01002333 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002334
2335 // Show the popup menu with a different set of matches.
2336 ins_compl_show_pum();
2337
2338 // Don't let Enter select the original text when there is no popup menu.
2339 if (compl_match_array == NULL)
2340 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002341 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2342 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002343}
2344
2345/*
2346 * Return the length of the completion, from the completion start column to
2347 * the cursor column. Making sure it never goes below zero.
2348 */
2349 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002350get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002351{
2352 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002353 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002354}
2355
2356/*
2357 * Append one character to the match leader. May reduce the number of
2358 * matches.
2359 */
2360 void
2361ins_compl_addleader(int c)
2362{
2363 int cc;
2364
glepniredd4ac32025-01-29 18:53:51 +01002365 if (ins_compl_preinsert_effect())
2366 ins_compl_delete();
2367
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002368 if (stop_arrow() == FAIL)
2369 return;
2370 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2371 {
2372 char_u buf[MB_MAXBYTES + 1];
2373
2374 (*mb_char2bytes)(c, buf);
2375 buf[cc] = NUL;
2376 ins_char_bytes(buf, cc);
2377 if (compl_opt_refresh_always)
2378 AppendToRedobuff(buf);
2379 }
2380 else
2381 {
2382 ins_char(c);
2383 if (compl_opt_refresh_always)
2384 AppendCharToRedobuff(c);
2385 }
2386
2387 // If we didn't complete finding matches we must search again.
2388 if (ins_compl_need_restart())
2389 ins_compl_restart();
2390
2391 // When 'always' is set, don't reset compl_leader. While completing,
2392 // cursor doesn't point original position, changing compl_leader would
2393 // break redo.
2394 if (!compl_opt_refresh_always)
2395 {
John Marriott5e6ea922024-11-23 14:01:57 +01002396 VIM_CLEAR_STRING(compl_leader);
2397 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2398 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2399 compl_leader.length);
2400 if (compl_leader.string == NULL)
2401 {
2402 compl_leader.length = 0;
2403 return;
2404 }
2405
2406 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002407 }
2408}
2409
2410/*
2411 * Setup for finding completions again without leaving CTRL-X mode. Used when
2412 * BS or a key was typed while still searching for matches.
2413 */
2414 static void
2415ins_compl_restart(void)
2416{
2417 ins_compl_free();
2418 compl_started = FALSE;
2419 compl_matches = 0;
2420 compl_cont_status = 0;
2421 compl_cont_mode = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02002422 cpt_compl_src_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002423}
2424
2425/*
2426 * Set the first match, the original text.
2427 */
2428 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002429ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002430{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002431 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002432 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2433 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002434 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002435 {
John Marriott5e6ea922024-11-23 14:01:57 +01002436 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002437 if (p != NULL)
2438 {
John Marriott5e6ea922024-11-23 14:01:57 +01002439 VIM_CLEAR_STRING(compl_first_match->cp_str);
2440 compl_first_match->cp_str.string = p;
2441 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002442 }
2443 }
2444 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002445 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002446 {
John Marriott5e6ea922024-11-23 14:01:57 +01002447 char_u *p = vim_strnsave(str, len);
2448 if (p != NULL)
2449 {
2450 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2451 compl_first_match->cp_prev->cp_str.string = p;
2452 compl_first_match->cp_prev->cp_str.length = len;
2453 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002454 }
2455}
2456
2457/*
2458 * Append one character to the match leader. May reduce the number of
2459 * matches.
2460 */
2461 void
2462ins_compl_addfrommatch(void)
2463{
2464 char_u *p;
2465 int len = (int)curwin->w_cursor.col - (int)compl_col;
2466 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002467
John Marriott5e6ea922024-11-23 14:01:57 +01002468 p = compl_shown_match->cp_str.string;
2469 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002470 {
John Marriott5e6ea922024-11-23 14:01:57 +01002471 size_t plen;
2472 compl_T *cp;
2473
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002474 // When still at the original match use the first entry that matches
2475 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002476 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002477 return;
2478
2479 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002480 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002481 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002482 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002483 {
John Marriott5e6ea922024-11-23 14:01:57 +01002484 if (compl_leader.string == NULL
2485 || ins_compl_equal(cp, compl_leader.string,
2486 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002487 {
John Marriott5e6ea922024-11-23 14:01:57 +01002488 p = cp->cp_str.string;
2489 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002490 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002491 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002492 }
John Marriott5e6ea922024-11-23 14:01:57 +01002493 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002494 return;
2495 }
2496 p += len;
2497 c = PTR2CHAR(p);
2498 ins_compl_addleader(c);
2499}
2500
2501/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002502 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002503 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2504 * compl_cont_mode and compl_cont_status.
2505 * Returns TRUE when the character is not to be inserted.
2506 */
2507 static int
2508set_ctrl_x_mode(int c)
2509{
2510 int retval = FALSE;
2511
2512 switch (c)
2513 {
2514 case Ctrl_E:
2515 case Ctrl_Y:
2516 // scroll the window one line up or down
2517 ctrl_x_mode = CTRL_X_SCROLL;
2518 if (!(State & REPLACE_FLAG))
2519 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2520 else
2521 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2522 edit_submode_pre = NULL;
2523 showmode();
2524 break;
2525 case Ctrl_L:
2526 // complete whole line
2527 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2528 break;
2529 case Ctrl_F:
2530 // complete filenames
2531 ctrl_x_mode = CTRL_X_FILES;
2532 break;
2533 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002534 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002535 ctrl_x_mode = CTRL_X_DICTIONARY;
2536 break;
2537 case Ctrl_R:
2538 // Register insertion without exiting CTRL-X mode
2539 // Simply allow ^R to happen without affecting ^X mode
2540 break;
2541 case Ctrl_T:
2542 // complete words from a thesaurus
2543 ctrl_x_mode = CTRL_X_THESAURUS;
2544 break;
2545#ifdef FEAT_COMPL_FUNC
2546 case Ctrl_U:
2547 // user defined completion
2548 ctrl_x_mode = CTRL_X_FUNCTION;
2549 break;
2550 case Ctrl_O:
2551 // omni completion
2552 ctrl_x_mode = CTRL_X_OMNI;
2553 break;
2554#endif
2555 case 's':
2556 case Ctrl_S:
2557 // complete spelling suggestions
2558 ctrl_x_mode = CTRL_X_SPELL;
2559#ifdef FEAT_SPELL
2560 ++emsg_off; // Avoid getting the E756 error twice.
2561 spell_back_to_badword();
2562 --emsg_off;
2563#endif
2564 break;
2565 case Ctrl_RSB:
2566 // complete tag names
2567 ctrl_x_mode = CTRL_X_TAGS;
2568 break;
2569#ifdef FEAT_FIND_ID
2570 case Ctrl_I:
2571 case K_S_TAB:
2572 // complete keywords from included files
2573 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2574 break;
2575 case Ctrl_D:
2576 // complete definitions from included files
2577 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2578 break;
2579#endif
2580 case Ctrl_V:
2581 case Ctrl_Q:
2582 // complete vim commands
2583 ctrl_x_mode = CTRL_X_CMDLINE;
2584 break;
2585 case Ctrl_Z:
2586 // stop completion
2587 ctrl_x_mode = CTRL_X_NORMAL;
2588 edit_submode = NULL;
2589 showmode();
2590 retval = TRUE;
2591 break;
2592 case Ctrl_P:
2593 case Ctrl_N:
2594 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2595 // just started ^X mode, or there were enough ^X's to cancel
2596 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2597 // do normal expansion when interrupting a different mode (say
2598 // ^X^F^X^P or ^P^X^X^P, see below)
2599 // nothing changes if interrupting mode 0, (eg, the flag
2600 // doesn't change when going to ADDING mode -- Acevedo
2601 if (!(compl_cont_status & CONT_INTRPT))
2602 compl_cont_status |= CONT_LOCAL;
2603 else if (compl_cont_mode != 0)
2604 compl_cont_status &= ~CONT_LOCAL;
2605 // FALLTHROUGH
2606 default:
2607 // If we have typed at least 2 ^X's... for modes != 0, we set
2608 // compl_cont_status = 0 (eg, as if we had just started ^X
2609 // mode).
2610 // For mode 0, we set "compl_cont_mode" to an impossible
2611 // value, in both cases ^X^X can be used to restart the same
2612 // mode (avoiding ADDING mode).
2613 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2614 // 'complete' and local ^P expansions respectively.
2615 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2616 // mode -- Acevedo
2617 if (c == Ctrl_X)
2618 {
2619 if (compl_cont_mode != 0)
2620 compl_cont_status = 0;
2621 else
2622 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2623 }
2624 ctrl_x_mode = CTRL_X_NORMAL;
2625 edit_submode = NULL;
2626 showmode();
2627 break;
2628 }
2629
2630 return retval;
2631}
2632
2633/*
glepnir1c5a1202024-12-04 20:27:34 +01002634 * Trigger CompleteDone event and adds relevant information to v:event
2635 */
2636 static void
2637trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2638{
2639#if defined(FEAT_EVAL)
2640 save_v_event_T save_v_event;
2641 dict_T *v_event = get_v_event(&save_v_event);
2642 char_u *mode_str = NULL;
2643
2644 mode = mode & ~CTRL_X_WANT_IDENT;
2645 if (ctrl_x_mode_names[mode])
2646 mode_str = (char_u *)ctrl_x_mode_names[mode];
2647
2648 (void)dict_add_string(v_event, "complete_word",
2649 word == NULL ? (char_u *)"" : word);
2650 (void)dict_add_string(v_event, "complete_type",
2651 mode_str != NULL ? mode_str : (char_u *)"");
2652
2653 dict_set_items_ro(v_event);
2654#endif
2655 ins_apply_autocmds(EVENT_COMPLETEDONE);
2656
2657#if defined(FEAT_EVAL)
2658 restore_v_event(v_event, &save_v_event);
2659#endif
2660}
2661
2662/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002663 * Stop insert completion mode
2664 */
2665 static int
2666ins_compl_stop(int c, int prev_mode, int retval)
2667{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002668 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002669 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002670
glepnir84a75032025-03-15 09:59:22 +01002671 // Remove pre-inserted text when present.
2672 if (ins_compl_preinsert_effect())
2673 ins_compl_delete();
2674
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002675 // Get here when we have finished typing a sequence of ^N and
2676 // ^P or other completion characters in CTRL-X mode. Free up
2677 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002678 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002679 {
glepnir40891ba2025-02-10 22:18:00 +01002680 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002681
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002682 // If any of the original typed text has been changed, eg when
2683 // ignorecase is set, we must add back-spaces to the redo
2684 // buffer. We add as few as necessary to delete just the part
2685 // of the original text that has changed.
2686 // When using the longest match, edited the match or used
2687 // CTRL-E then don't use the current match.
2688 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002689 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002690 ins_compl_fixRedoBufForLeader(ptr);
2691 }
2692
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002693 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002694
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002695 // When completing whole lines: fix indent for 'cindent'.
2696 // Otherwise, break line if it's too long.
2697 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2698 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002699 // re-indent the current line
2700 if (want_cindent)
2701 {
2702 do_c_expr_indent();
2703 want_cindent = FALSE; // don't do it again
2704 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002705 }
2706 else
2707 {
2708 int prev_col = curwin->w_cursor.col;
2709
2710 // put the cursor on the last char, for 'tw' formatting
2711 if (prev_col > 0)
2712 dec_cursor();
2713 // only format when something was inserted
2714 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2715 insertchar(NUL, 0, -1);
2716 if (prev_col > 0
2717 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2718 inc_cursor();
2719 }
2720
2721 // If the popup menu is displayed pressing CTRL-Y means accepting
2722 // the selection without inserting anything. When
2723 // compl_enter_selects is set the Enter key does the same.
2724 if ((c == Ctrl_Y || (compl_enter_selects
2725 && (c == CAR || c == K_KENTER || c == NL)))
2726 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002727 {
2728 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002729 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002730 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002731
2732 // CTRL-E means completion is Ended, go back to the typed text.
2733 // but only do this, if the Popup is still visible
2734 if (c == Ctrl_E)
2735 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002736 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002737 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002738
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002739 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002740 if (compl_leader.string != NULL)
2741 {
2742 p = compl_leader.string;
2743 plen = compl_leader.length;
2744 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002745 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002746 {
2747 p = compl_orig_text.string;
2748 plen = compl_orig_text.length;
2749 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002750 if (p != NULL)
2751 {
2752 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002753
John Marriott5e6ea922024-11-23 14:01:57 +01002754 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002755 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002756 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002757 retval = TRUE;
2758 }
2759
2760 auto_format(FALSE, TRUE);
2761
2762 // Trigger the CompleteDonePre event to give scripts a chance to
2763 // act upon the completion before clearing the info, and restore
2764 // ctrl_x_mode, so that complete_info() can be used.
2765 ctrl_x_mode = prev_mode;
2766 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2767
2768 ins_compl_free();
2769 compl_started = FALSE;
2770 compl_matches = 0;
2771 if (!shortmess(SHM_COMPLETIONMENU))
2772 msg_clr_cmdline(); // necessary for "noshowmode"
2773 ctrl_x_mode = CTRL_X_NORMAL;
2774 compl_enter_selects = FALSE;
2775 if (edit_submode != NULL)
2776 {
2777 edit_submode = NULL;
2778 showmode();
2779 }
2780
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002781 if (c == Ctrl_C && cmdwin_type != 0)
2782 // Avoid the popup menu remains displayed when leaving the
2783 // command line window.
2784 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002785 // Indent now if a key was typed that is in 'cinkeys'.
2786 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2787 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002788 // Trigger the CompleteDone event to give scripts a chance to act
2789 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002790 trigger_complete_done_event(prev_mode, word);
2791 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002792
2793 return retval;
2794}
2795
2796/*
glepnircf7f0122025-04-15 19:02:00 +02002797 * Cancel completion.
2798 */
2799 int
2800ins_compl_cancel(void)
2801{
2802 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2803}
2804
2805/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002806 * Prepare for Insert mode completion, or stop it.
2807 * Called just after typing a character in Insert mode.
2808 * Returns TRUE when the character is not to be inserted;
2809 */
2810 int
2811ins_compl_prep(int c)
2812{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002813 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002814 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002815
2816 // Forget any previous 'special' messages if this is actually
2817 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2818 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2819 edit_submode_extra = NULL;
2820
zeertzjq440d4cb2023-03-02 17:51:32 +00002821 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002822 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002823 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002824 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002825 return retval;
2826
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002827#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002828 // Ignore mouse events in a popup window
2829 if (is_mouse_key(c))
2830 {
2831 // Ignore drag and release events, the position does not need to be in
2832 // the popup and it may have just closed.
2833 if (c == K_LEFTRELEASE
2834 || c == K_LEFTRELEASE_NM
2835 || c == K_MIDDLERELEASE
2836 || c == K_RIGHTRELEASE
2837 || c == K_X1RELEASE
2838 || c == K_X2RELEASE
2839 || c == K_LEFTDRAG
2840 || c == K_MIDDLEDRAG
2841 || c == K_RIGHTDRAG
2842 || c == K_X1DRAG
2843 || c == K_X2DRAG)
2844 return retval;
2845 if (popup_visible)
2846 {
2847 int row = mouse_row;
2848 int col = mouse_col;
2849 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2850
2851 if (wp != NULL && WIN_IS_POPUP(wp))
2852 return retval;
2853 }
2854 }
2855#endif
2856
zeertzjqdca29d92021-08-31 19:12:51 +02002857 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2858 {
2859 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2860 || !vim_is_ctrl_x_key(c))
2861 {
2862 // Not starting another completion mode.
2863 ctrl_x_mode = CTRL_X_CMDLINE;
2864
2865 // CTRL-X CTRL-Z should stop completion without inserting anything
2866 if (c == Ctrl_Z)
2867 retval = TRUE;
2868 }
2869 else
2870 {
2871 ctrl_x_mode = CTRL_X_CMDLINE;
2872
2873 // Other CTRL-X keys first stop completion, then start another
2874 // completion mode.
2875 ins_compl_prep(' ');
2876 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2877 }
2878 }
2879
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002880 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002881 if (ctrl_x_mode_not_defined_yet()
2882 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002883 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002884 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002885 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002886 }
2887
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002888 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002889 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2890 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002891 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002892 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002893 {
2894 // We're already in CTRL-X mode, do we stay in it?
2895 if (!vim_is_ctrl_x_key(c))
2896 {
glepnir40891ba2025-02-10 22:18:00 +01002897 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002898 edit_submode = NULL;
2899 }
2900 showmode();
2901 }
2902
2903 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2904 {
2905 // Show error message from attempted keyword completion (probably
2906 // 'Pattern not found') until another key is hit, then go back to
2907 // showing what mode we are in.
2908 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002909 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002910 && c != Ctrl_R && !ins_compl_pum_key(c))
2911 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002912 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002913 }
2914 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2915 // Trigger the CompleteDone event to give scripts a chance to act
2916 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002917 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002918
LemonBoy2bf52dd2022-04-09 18:17:34 +01002919 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002920
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002921 // reset continue_* if we left expansion-mode, if we stay they'll be
2922 // (re)set properly in ins_complete()
2923 if (!vim_is_ctrl_x_key(c))
2924 {
2925 compl_cont_status = 0;
2926 compl_cont_mode = 0;
2927 }
2928
2929 return retval;
2930}
2931
2932/*
2933 * Fix the redo buffer for the completion leader replacing some of the typed
2934 * text. This inserts backspaces and appends the changed text.
2935 * "ptr" is the known leader text or NUL.
2936 */
2937 static void
2938ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2939{
John Marriott5e6ea922024-11-23 14:01:57 +01002940 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002941 char_u *p;
2942 char_u *ptr = ptr_arg;
2943
2944 if (ptr == NULL)
2945 {
John Marriott5e6ea922024-11-23 14:01:57 +01002946 if (compl_leader.string != NULL)
2947 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002948 else
2949 return; // nothing to do
2950 }
John Marriott5e6ea922024-11-23 14:01:57 +01002951 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002952 {
John Marriott5e6ea922024-11-23 14:01:57 +01002953 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002954 // Find length of common prefix between original text and new completion
2955 while (p[len] != NUL && p[len] == ptr[len])
2956 len++;
2957 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002958 if (len > 0)
2959 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002960 // Add backspace characters for each remaining character in
2961 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002962 for (p += len; *p != NUL; MB_PTR_ADV(p))
2963 AppendCharToRedobuff(K_BS);
2964 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002965 if (ptr != NULL)
2966 AppendToRedobuffLit(ptr + len, -1);
2967}
2968
2969/*
2970 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2971 * (depending on flag) starting from buf and looking for a non-scanned
2972 * buffer (other than curbuf). curbuf is special, if it is called with
2973 * buf=curbuf then it has to be the first call for a given flag/expansion.
2974 *
2975 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2976 */
2977 static buf_T *
2978ins_compl_next_buf(buf_T *buf, int flag)
2979{
2980 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01002981 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002982
2983 if (flag == 'w') // just windows
2984 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002985 if (buf == curbuf || !win_valid(wp))
2986 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002987 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01002988
2989 while (TRUE)
2990 {
2991 // Move to next window (wrap to first window if at the end)
2992 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
2993 // Break if we're back at start or found an unscanned buffer
2994 if (wp == curwin || !wp->w_buffer->b_scanned)
2995 break;
2996 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002997 buf = wp->w_buffer;
2998 }
2999 else
glepnir40891ba2025-02-10 22:18:00 +01003000 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003001 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3002 // (unlisted buffers)
3003 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003004 while (TRUE)
3005 {
3006 // Move to next buffer (wrap to first buffer if at the end)
3007 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3008 // Break if we're back at start buffer
3009 if (buf == curbuf)
3010 break;
3011
3012 // Check buffer conditions based on flag
3013 if (flag == 'U')
3014 skip_buffer = buf->b_p_bl;
3015 else
3016 skip_buffer = !buf->b_p_bl ||
3017 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3018
3019 // Break if we found a buffer that matches our criteria
3020 if (!skip_buffer && !buf->b_scanned)
3021 break;
3022 }
3023 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003024 return buf;
3025}
3026
3027#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003028
3029# ifdef FEAT_EVAL
3030static callback_T cfu_cb; // 'completefunc' callback function
3031static callback_T ofu_cb; // 'omnifunc' callback function
3032static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3033# endif
3034
3035/*
3036 * Copy a global callback function to a buffer local callback.
3037 */
3038 static void
3039copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3040{
3041 free_callback(bufcb);
3042 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3043 copy_callback(bufcb, globcb);
3044}
3045
3046/*
3047 * Parse the 'completefunc' option value and set the callback function.
3048 * Invoked when the 'completefunc' option is set. The option value can be a
3049 * name of a function (string), or function(<name>) or funcref(<name>) or a
3050 * lambda expression.
3051 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003052 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003053did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003054{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003055 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3056 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003057
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003058 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003059
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003060 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003061}
3062
3063/*
3064 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003065 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003066 */
3067 void
3068set_buflocal_cfu_callback(buf_T *buf UNUSED)
3069{
3070# ifdef FEAT_EVAL
3071 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3072# endif
3073}
3074
3075/*
3076 * Parse the 'omnifunc' option value and set the callback function.
3077 * Invoked when the 'omnifunc' option is set. The option value can be a
3078 * name of a function (string), or function(<name>) or funcref(<name>) or a
3079 * lambda expression.
3080 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003081 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003082did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003083{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003084 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3085 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003086
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003087 set_buflocal_ofu_callback(curbuf);
3088 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003089}
3090
3091/*
3092 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003093 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003094 */
3095 void
3096set_buflocal_ofu_callback(buf_T *buf UNUSED)
3097{
3098# ifdef FEAT_EVAL
3099 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3100# endif
3101}
3102
3103/*
3104 * Parse the 'thesaurusfunc' option value and set the callback function.
3105 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3106 * name of a function (string), or function(<name>) or funcref(<name>) or a
3107 * lambda expression.
3108 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003109 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003110did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003111{
3112 int retval;
3113
zeertzjq6eda2692024-11-03 09:23:33 +01003114 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003115 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003116 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3117 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003118 else
3119 {
3120 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003121 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003122 // when using :set, free the local callback
3123 if (!(args->os_flags & OPT_GLOBAL))
3124 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003125 }
3126
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003127 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003128}
3129
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003130/*
3131 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003132 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003133 */
3134 int
3135set_ref_in_insexpand_funcs(int copyID)
3136{
3137 int abort = FALSE;
3138
3139 abort = set_ref_in_callback(&cfu_cb, copyID);
3140 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3141 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3142
3143 return abort;
3144}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003145
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003146/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003147 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003148 */
3149 static char_u *
3150get_complete_funcname(int type)
3151{
3152 switch (type)
3153 {
3154 case CTRL_X_FUNCTION:
3155 return curbuf->b_p_cfu;
3156 case CTRL_X_OMNI:
3157 return curbuf->b_p_ofu;
3158 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003159 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003160 default:
3161 return (char_u *)"";
3162 }
3163}
3164
3165/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003166 * Get the callback to use for insert mode completion.
3167 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003168 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003169get_insert_callback(int type)
3170{
3171 if (type == CTRL_X_FUNCTION)
3172 return &curbuf->b_cfu_cb;
3173 if (type == CTRL_X_OMNI)
3174 return &curbuf->b_ofu_cb;
3175 // CTRL_X_THESAURUS
3176 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3177}
3178
3179/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003180 * Execute user defined complete function 'completefunc', 'omnifunc' or
3181 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003182 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3183 * Callback function "cb" is set if triggered by a function in the 'cpt'
3184 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003185 */
3186 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003187expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003188{
3189 list_T *matchlist = NULL;
3190 dict_T *matchdict = NULL;
3191 typval_T args[3];
3192 char_u *funcname;
3193 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003194 typval_T rettv;
3195 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003196 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003197 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003198
Girish Palyacbe53192025-04-14 22:13:15 +02003199 if (!is_cpt_function)
3200 {
3201 funcname = get_complete_funcname(type);
3202 if (*funcname == NUL)
3203 return;
3204 cb = get_insert_callback(type);
3205 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003206
3207 // Call 'completefunc' to obtain the list of matches.
3208 args[0].v_type = VAR_NUMBER;
3209 args[0].vval.v_number = 0;
3210 args[1].v_type = VAR_STRING;
3211 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3212 args[2].v_type = VAR_UNKNOWN;
3213
3214 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003215 // Lock the text to avoid weird things from happening. Also disallow
3216 // switching to another window, it should not be needed and may end up in
3217 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003218 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003219
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003220 retval = call_callback(cb, 0, &rettv, 2, args);
3221
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003222 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003223 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003224 {
3225 switch (rettv.v_type)
3226 {
3227 case VAR_LIST:
3228 matchlist = rettv.vval.v_list;
3229 break;
3230 case VAR_DICT:
3231 matchdict = rettv.vval.v_dict;
3232 break;
3233 case VAR_SPECIAL:
3234 if (rettv.vval.v_number == VVAL_NONE)
3235 compl_opt_suppress_empty = TRUE;
3236 // FALLTHROUGH
3237 default:
3238 // TODO: Give error message?
3239 clear_tv(&rettv);
3240 break;
3241 }
3242 }
zeertzjqcfe45652022-05-27 17:26:55 +01003243 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003244
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003245 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003246 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003247 validate_cursor();
3248 if (!EQUAL_POS(curwin->w_cursor, pos))
3249 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003250 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003251 goto theend;
3252 }
3253
3254 if (matchlist != NULL)
3255 ins_compl_add_list(matchlist);
3256 else if (matchdict != NULL)
3257 ins_compl_add_dict(matchdict);
3258
3259theend:
3260 // Restore State, it might have been changed.
3261 State = save_State;
3262
3263 if (matchdict != NULL)
3264 dict_unref(matchdict);
3265 if (matchlist != NULL)
3266 list_unref(matchlist);
3267}
3268#endif // FEAT_COMPL_FUNC
3269
3270#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003271
3272 static inline int
3273get_user_highlight_attr(char_u *hlname)
3274{
3275 if (hlname != NULL && *hlname != NUL)
3276 return syn_name2attr(hlname);
3277 return -1;
3278}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003279/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003280 * Add a match to the list of matches from a typeval_T.
3281 * If the given string is already in the list of completions, then return
3282 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3283 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003284 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003285 */
3286 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003287ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003288{
3289 char_u *word;
3290 int dup = FALSE;
3291 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003292 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003293 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003294 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003295 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003296 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003297 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003298 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003299
Bram Moolenaar08928322020-01-04 14:32:48 +01003300 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003301 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3302 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003303 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3304 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3305 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3306 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3307 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003308
glepnir0fe17f82024-10-08 22:26:44 +02003309 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003310 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003311
3312 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003313 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003314
Bram Moolenaard61efa52022-07-23 09:52:04 +01003315 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3316 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3317 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003318 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003319 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3320 dup = dict_get_number(tv->vval.v_dict, "dup");
3321 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3322 empty = dict_get_number(tv->vval.v_dict, "empty");
3323 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3324 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003325 flags |= CP_EQUAL;
3326 }
3327 else
3328 {
3329 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003330 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003331 }
3332 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003333 {
3334 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003335 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003336 }
glepnir508e7852024-07-25 21:39:08 +02003337 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003338 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003339 if (status != OK)
3340 clear_tv(&user_data);
3341 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003342}
3343
3344/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003345 * Add completions from a list.
3346 */
3347 static void
3348ins_compl_add_list(list_T *list)
3349{
3350 listitem_T *li;
3351 int dir = compl_direction;
3352
3353 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003354 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003355 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003356 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003357 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003358 // if dir was BACKWARD then honor it just once
3359 dir = FORWARD;
3360 else if (did_emsg)
3361 break;
3362 }
3363}
3364
3365/*
3366 * Add completions from a dict.
3367 */
3368 static void
3369ins_compl_add_dict(dict_T *dict)
3370{
3371 dictitem_T *di_refresh;
3372 dictitem_T *di_words;
3373
3374 // Check for optional "refresh" item.
3375 compl_opt_refresh_always = FALSE;
3376 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3377 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3378 {
3379 char_u *v = di_refresh->di_tv.vval.v_string;
3380
3381 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3382 compl_opt_refresh_always = TRUE;
3383 }
3384
3385 // Add completions from a "words" list.
3386 di_words = dict_find(dict, (char_u *)"words", 5);
3387 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3388 ins_compl_add_list(di_words->di_tv.vval.v_list);
3389}
3390
3391/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003392 * Start completion for the complete() function.
3393 * "startcol" is where the matched text starts (1 is first column).
3394 * "list" is the list of matches.
3395 */
3396 static void
3397set_completion(colnr_T startcol, list_T *list)
3398{
3399 int save_w_wrow = curwin->w_wrow;
3400 int save_w_leftcol = curwin->w_leftcol;
3401 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003402 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003403 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3404 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3405 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003406
3407 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003408 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003409 ins_compl_prep(' ');
3410 ins_compl_clear();
3411 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003412 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003413
3414 compl_direction = FORWARD;
3415 if (startcol > curwin->w_cursor.col)
3416 startcol = curwin->w_cursor.col;
3417 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003418 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003419 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3420 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003421 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3422 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003423 if (p_ic)
3424 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003425 if (compl_orig_text.string == NULL)
3426 {
3427 compl_orig_text.length = 0;
3428 return;
3429 }
3430 compl_orig_text.length = (size_t)compl_length;
3431 if (ins_compl_add(compl_orig_text.string,
3432 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
glepnirf31cfa22025-03-06 21:59:13 +01003433 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003434 return;
3435
3436 ctrl_x_mode = CTRL_X_EVAL;
3437
3438 ins_compl_add_list(list);
3439 compl_matches = ins_compl_make_cyclic();
3440 compl_started = TRUE;
3441 compl_used_match = TRUE;
3442 compl_cont_status = 0;
3443
3444 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003445 int no_select = compl_no_select || compl_longest;
3446 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003447 {
3448 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003449 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003450 // Down/Up has no real effect.
3451 ins_complete(K_UP, FALSE);
3452 }
3453 else
3454 ins_complete(Ctrl_N, FALSE);
3455 compl_enter_selects = compl_no_insert;
3456
3457 // Lazily show the popup menu, unless we got interrupted.
3458 if (!compl_interrupted)
3459 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003460 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003461 out_flush();
3462}
3463
3464/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003465 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003466 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003467 void
3468f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003469{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003470 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003471
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003472 if (in_vim9script()
3473 && (check_for_number_arg(argvars, 0) == FAIL
3474 || check_for_list_arg(argvars, 1) == FAIL))
3475 return;
3476
Bram Moolenaar24959102022-05-07 20:01:16 +01003477 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003478 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003479 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003480 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003481 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003482
3483 // Check for undo allowed here, because if something was already inserted
3484 // the line was already saved for undo and this check isn't done.
3485 if (!undo_allowed())
3486 return;
3487
Bram Moolenaard83392a2022-09-01 12:22:46 +01003488 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003489 {
3490 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3491 if (startcol > 0)
3492 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003493 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003494}
3495
3496/*
3497 * "complete_add()" function
3498 */
3499 void
3500f_complete_add(typval_T *argvars, typval_T *rettv)
3501{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003502 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003503 return;
3504
Bram Moolenaar440cf092021-04-03 20:13:30 +02003505 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003506}
3507
3508/*
3509 * "complete_check()" function
3510 */
3511 void
3512f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3513{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003514 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003515 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003516
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003517 ins_compl_check_keys(0, TRUE);
3518 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003519
3520 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003521}
3522
3523/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003524 * Return Insert completion mode name string
3525 */
3526 static char_u *
3527ins_compl_mode(void)
3528{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003529 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003530 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3531
3532 return (char_u *)"";
3533}
3534
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003535/*
3536 * Assign the sequence number to all the completion matches which don't have
3537 * one assigned yet.
3538 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003539 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003540ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003541{
3542 int number = 0;
3543 compl_T *match;
3544
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003545 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003546 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003547 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003548 // This should normally succeed already at the first loop
3549 // cycle, so it's fast!
3550 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003551 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003552 if (match->cp_number != -1)
3553 {
3554 number = match->cp_number;
3555 break;
3556 }
3557 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003558 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003559 for (match = match->cp_next;
3560 match != NULL && match->cp_number == -1;
3561 match = match->cp_next)
3562 match->cp_number = ++number;
3563 }
3564 else // BACKWARD
3565 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003566 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003567 // number. This should normally succeed already at the
3568 // first loop cycle, so it's fast!
3569 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003570 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003571 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003572 if (match->cp_number != -1)
3573 {
3574 number = match->cp_number;
3575 break;
3576 }
glepnir40891ba2025-02-10 22:18:00 +01003577 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003578 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003579 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003580 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003581 for (match = match->cp_prev; match
3582 && match->cp_number == -1;
3583 match = match->cp_prev)
3584 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003585 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003586 }
3587}
3588
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003589/*
glepnir037b0282025-01-16 14:37:44 +01003590 * Fill the dict of complete_info
3591 */
3592 static void
3593fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3594{
3595 dict_add_string(di, "word", match->cp_str.string);
3596 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3597 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3598 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3599 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3600 if (add_match)
3601 dict_add_bool(di, "match", match->cp_in_match_array);
3602 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3603 // Add an empty string for backwards compatibility
3604 dict_add_string(di, "user_data", (char_u *)"");
3605 else
3606 dict_add_tv(di, "user_data", &match->cp_user_data);
3607}
3608
3609/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003610 * Get complete information
3611 */
3612 static void
3613get_complete_info(list_T *what_list, dict_T *retdict)
3614{
3615 int ret = OK;
3616 listitem_T *item;
3617#define CI_WHAT_MODE 0x01
3618#define CI_WHAT_PUM_VISIBLE 0x02
3619#define CI_WHAT_ITEMS 0x04
3620#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003621#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003622#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003623#define CI_WHAT_ALL 0xff
3624 int what_flag;
3625
3626 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003627 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003628 else
3629 {
3630 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003631 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003632 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003633 {
3634 char_u *what = tv_get_string(&item->li_tv);
3635
3636 if (STRCMP(what, "mode") == 0)
3637 what_flag |= CI_WHAT_MODE;
3638 else if (STRCMP(what, "pum_visible") == 0)
3639 what_flag |= CI_WHAT_PUM_VISIBLE;
3640 else if (STRCMP(what, "items") == 0)
3641 what_flag |= CI_WHAT_ITEMS;
3642 else if (STRCMP(what, "selected") == 0)
3643 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003644 else if (STRCMP(what, "completed") == 0)
3645 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003646 else if (STRCMP(what, "matches") == 0)
3647 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003648 }
3649 }
3650
3651 if (ret == OK && (what_flag & CI_WHAT_MODE))
3652 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3653
3654 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3655 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3656
glepnir037b0282025-01-16 14:37:44 +01003657 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3658 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003659 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003660 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003661 dict_T *di;
3662 compl_T *match;
3663 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003664 int has_items = what_flag & CI_WHAT_ITEMS;
3665 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003666 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003667
glepnird4088ed2024-12-31 10:55:22 +01003668 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003669 {
3670 li = list_alloc();
3671 if (li == NULL)
3672 return;
glepnird4088ed2024-12-31 10:55:22 +01003673 ret = dict_add_list(retdict, (has_matches && !has_items)
3674 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003675 }
3676 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3677 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3678 ins_compl_update_sequence_numbers();
3679 if (ret == OK && compl_first_match != NULL)
3680 {
3681 int list_idx = 0;
3682 match = compl_first_match;
3683 do
3684 {
3685 if (!match_at_original_text(match))
3686 {
glepnird4088ed2024-12-31 10:55:22 +01003687 if (has_items
3688 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003689 {
3690 di = dict_alloc();
3691 if (di == NULL)
3692 return;
3693 ret = list_append_dict(li, di);
3694 if (ret != OK)
3695 return;
glepnir037b0282025-01-16 14:37:44 +01003696 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003697 }
glepnird4088ed2024-12-31 10:55:22 +01003698 if (compl_curr_match != NULL
3699 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003700 selected_idx = list_idx;
3701 list_idx += 1;
3702 }
3703 match = match->cp_next;
3704 }
3705 while (match != NULL && !is_first_match(match));
3706 }
3707 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3708 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003709
glepnir037b0282025-01-16 14:37:44 +01003710 if (ret == OK && selected_idx != -1 && has_completed)
3711 {
3712 di = dict_alloc();
3713 if (di == NULL)
3714 return;
3715 fill_complete_info_dict(di, compl_curr_match, FALSE);
3716 ret = dict_add_dict(retdict, "completed", di);
3717 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003718 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003719}
3720
3721/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003722 * "complete_info()" function
3723 */
3724 void
3725f_complete_info(typval_T *argvars, typval_T *rettv)
3726{
3727 list_T *what_list = NULL;
3728
Bram Moolenaar93a10962022-06-16 11:42:09 +01003729 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003730 return;
3731
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003732 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3733 return;
3734
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003735 if (argvars[0].v_type != VAR_UNKNOWN)
3736 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003737 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003738 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003739 what_list = argvars[0].vval.v_list;
3740 }
3741 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003742}
3743#endif
3744
3745/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003746 * Returns TRUE when using a user-defined function for thesaurus completion.
3747 */
3748 static int
3749thesaurus_func_complete(int type UNUSED)
3750{
3751#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003752 return type == CTRL_X_THESAURUS
3753 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003754#else
3755 return FALSE;
3756#endif
3757}
3758
3759/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003760 * Return value of process_next_cpt_value()
3761 */
3762enum
3763{
3764 INS_COMPL_CPT_OK = 1,
3765 INS_COMPL_CPT_CONT,
3766 INS_COMPL_CPT_END
3767};
3768
3769/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003770 * state information used for getting the next set of insert completion
3771 * matches.
3772 */
3773typedef struct
3774{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003775 char_u *e_cpt_copy; // copy of 'complete'
3776 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003777 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003778 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003779 pos_T prev_match_pos; // previous match position
3780 int set_match_pos; // save first_match_pos/last_match_pos
3781 pos_T first_match_pos; // first match position
3782 pos_T last_match_pos; // last match position
3783 int found_all; // found all matches of a certain type.
3784 char_u *dict; // dictionary file to search
3785 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003786 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003787} ins_compl_next_state_T;
3788
3789/*
3790 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003791 *
3792 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003793 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003794 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003795 * st->found_all - all matches of this type are found
3796 * st->ins_buf - search for completions in this buffer
3797 * st->first_match_pos - position of the first completion match
3798 * st->last_match_pos - position of the last completion match
3799 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003800 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003801 * st->dict - name of the dictionary or thesaurus file to search
3802 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003803 *
3804 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003805 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3806 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003807 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003808 */
3809 static int
3810process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003811 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003812 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003813 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003814 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003815{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003816 int compl_type = -1;
3817 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003818
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003819 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003820
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003821 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3822 st->e_cpt++;
3823
3824 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003825 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003826 st->ins_buf = curbuf;
3827 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003828 // Move the cursor back one character so that ^N can match the
3829 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003830 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003831 {
3832 // Move the cursor to after the last character in the
3833 // buffer, so that word at start of buffer is found
3834 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003835 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003836 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003837 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003838 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003839 compl_type = 0;
3840
3841 // Remember the first match so that the loop stops when we
3842 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003843 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003844 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003845 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003846 && (st->ins_buf = ins_compl_next_buf(
3847 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003848 {
3849 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003850 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003851 {
3852 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003853 st->first_match_pos.col = st->last_match_pos.col = 0;
3854 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3855 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003856 compl_type = 0;
3857 }
3858 else // unloaded buffer, scan like dictionary
3859 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003860 st->found_all = TRUE;
3861 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003862 {
3863 status = INS_COMPL_CPT_CONT;
3864 goto done;
3865 }
3866 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003867 st->dict = st->ins_buf->b_fname;
3868 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003869 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003870 if (!shortmess(SHM_COMPLETIONSCAN))
3871 {
3872 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3873 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3874 st->ins_buf->b_fname == NULL
3875 ? buf_spname(st->ins_buf)
3876 : st->ins_buf->b_sfname == NULL
3877 ? st->ins_buf->b_fname
3878 : st->ins_buf->b_sfname);
3879 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3880 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003881 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003882 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003883 status = INS_COMPL_CPT_END;
3884 else
3885 {
3886 if (ctrl_x_mode_line_or_eval())
3887 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003888 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003889 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003890 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003891 compl_type = CTRL_X_DICTIONARY;
3892 else
3893 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003894 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003895 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003896 st->dict = st->e_cpt;
3897 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003898 }
3899 }
Girish Palyacbe53192025-04-14 22:13:15 +02003900#ifdef FEAT_COMPL_FUNC
3901 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
3902 {
3903 compl_type = CTRL_X_FUNCTION;
3904 if (*st->e_cpt == 'o')
3905 st->func_cb = &curbuf->b_ofu_cb;
3906 else
3907 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
3908 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
3909 if (!st->func_cb)
3910 compl_type = -1;
3911 }
3912#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003913#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003914 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003915 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003916 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003917 compl_type = CTRL_X_PATH_DEFINES;
3918#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003919 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003920 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003921 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003922 if (!shortmess(SHM_COMPLETIONSCAN))
3923 {
3924 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3925 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3926 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3927 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003928 }
3929 else
3930 compl_type = -1;
3931
3932 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003933 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003934
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003935 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003936 if (compl_type == -1)
3937 status = INS_COMPL_CPT_CONT;
3938 }
3939
3940done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003941 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003942 return status;
3943}
3944
3945#ifdef FEAT_FIND_ID
3946/*
3947 * Get the next set of identifiers or defines matching "compl_pattern" in
3948 * included files.
3949 */
3950 static void
3951get_next_include_file_completion(int compl_type)
3952{
John Marriott5e6ea922024-11-23 14:01:57 +01003953 find_pattern_in_path(compl_pattern.string, compl_direction,
3954 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003955 (compl_type == CTRL_X_PATH_DEFINES
3956 && !(compl_cont_status & CONT_SOL))
3957 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003958 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003959}
3960#endif
3961
3962/*
3963 * Get the next set of words matching "compl_pattern" in dictionary or
3964 * thesaurus files.
3965 */
3966 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003967get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003968{
3969#ifdef FEAT_COMPL_FUNC
3970 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02003971 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003972 else
3973#endif
3974 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003975 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003976 : (compl_type == CTRL_X_THESAURUS
3977 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3978 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003979 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003980 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003981 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003982}
3983
3984/*
3985 * Get the next set of tag names matching "compl_pattern".
3986 */
3987 static void
3988get_next_tag_completion(void)
3989{
3990 int save_p_ic;
3991 char_u **matches;
3992 int num_matches;
3993
3994 // set p_ic according to p_ic, p_scs and pat for find_tags().
3995 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003996 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003997
3998 // Find up to TAG_MANY matches. Avoids that an enormous number
3999 // of matches is found when compl_pattern is empty
4000 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004001 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004002 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004003 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004004 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4005 ins_compl_add_matches(num_matches, matches, p_ic);
4006 g_tag_at_cursor = FALSE;
4007 p_ic = save_p_ic;
4008}
4009
4010/*
glepnir8159fb12024-07-17 20:32:54 +02004011 * Compare function for qsort
4012 */
glepnirf31cfa22025-03-06 21:59:13 +01004013 static int
4014compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004015{
4016 int idx_a = *(const int *)a;
4017 int idx_b = *(const int *)b;
4018 int score_a = compl_fuzzy_scores[idx_a];
4019 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004020 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4021 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004022}
4023
4024/*
glepnirf31cfa22025-03-06 21:59:13 +01004025 * insert prefix with redraw
4026 */
4027 static void
4028ins_compl_longest_insert(char_u *prefix)
4029{
4030 ins_compl_delete();
4031 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4032 ins_redraw(FALSE);
4033}
4034
4035/*
4036 * Calculate the longest common prefix among the best fuzzy matches
4037 * stored in compl_best_matches, and insert it as the longest.
4038 */
4039 static void
4040fuzzy_longest_match(void)
4041{
4042 char_u *prefix = NULL;
4043 int prefix_len = 0;
4044 int i = 0;
4045 int j = 0;
4046 char_u *match_str = NULL;
4047 char_u *prefix_ptr = NULL;
4048 char_u *match_ptr = NULL;
4049 char_u *leader = NULL;
4050 size_t leader_len = 0;
4051 compl_T *compl = NULL;
4052 int more_candidates = FALSE;
4053 compl_T *nn_compl = NULL;
4054
4055 if (compl_num_bests == 0)
4056 return;
4057
4058 nn_compl = compl_first_match->cp_next->cp_next;
4059 if (nn_compl && nn_compl != compl_first_match)
4060 more_candidates = TRUE;
4061
4062 compl = ctrl_x_mode_whole_line() ? compl_first_match
4063 : compl_first_match->cp_next;
4064 if (compl_num_bests == 1)
4065 {
4066 // no more candidates insert the match str
4067 if (!more_candidates)
4068 {
4069 ins_compl_longest_insert(compl->cp_str.string);
4070 compl_num_bests = 0;
4071 }
4072 compl_num_bests = 0;
4073 return;
4074 }
4075
4076 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4077 if (compl_best_matches == NULL)
4078 return;
4079 while (compl != NULL && i < compl_num_bests)
4080 {
4081 compl_best_matches[i] = compl;
4082 compl = compl->cp_next;
4083 i++;
4084 }
4085
4086 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004087 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004088
4089 for (i = 1; i < compl_num_bests; i++)
4090 {
4091 match_str = compl_best_matches[i]->cp_str.string;
4092 prefix_ptr = prefix;
4093 match_ptr = match_str;
4094 j = 0;
4095
4096 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4097 {
4098 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4099 break;
4100
4101 MB_PTR_ADV(prefix_ptr);
4102 MB_PTR_ADV(match_ptr);
4103 j++;
4104 }
4105
4106 if (j > 0)
4107 prefix_len = j;
4108 }
4109
4110 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004111 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004112
4113 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004114 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004115 goto end;
4116
zeertzjq4422de62025-03-07 19:06:02 +01004117 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004118 if (prefix != NULL)
4119 {
4120 ins_compl_longest_insert(prefix);
4121 compl_cfc_longest_ins = TRUE;
4122 vim_free(prefix);
4123 }
4124
4125end:
4126 vim_free(compl_best_matches);
4127 compl_best_matches = NULL;
4128 compl_num_bests = 0;
4129}
4130
4131/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004132 * Get the next set of filename matching "compl_pattern".
4133 */
4134 static void
4135get_next_filename_completion(void)
4136{
4137 char_u **matches;
4138 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004139 char_u *ptr;
4140 garray_T fuzzy_indices;
4141 int i;
4142 int score;
4143 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004144 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004145 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004146 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004147 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004148 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4149 int max_score = 0;
4150 int current_score = 0;
4151 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004152
glepnirb9de1a02024-08-02 19:14:38 +02004153#ifdef BACKSLASH_IN_FILENAME
4154 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4155 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4156#else
4157 char pathsep = PATHSEP;
4158#endif
4159
glepnirf31cfa22025-03-06 21:59:13 +01004160 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004161 {
glepnirb9de1a02024-08-02 19:14:38 +02004162#ifdef BACKSLASH_IN_FILENAME
4163 if (curbuf->b_p_csl[0] == 's')
4164 {
John Marriott5e6ea922024-11-23 14:01:57 +01004165 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004166 {
4167 if (leader[i] == '\\')
4168 leader[i] = '/';
4169 }
4170 }
4171 else if (curbuf->b_p_csl[0] == 'b')
4172 {
John Marriott5e6ea922024-11-23 14:01:57 +01004173 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004174 {
4175 if (leader[i] == '/')
4176 leader[i] = '\\';
4177 }
4178 }
4179#endif
4180 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004181 if (last_sep == NULL)
4182 {
4183 // No path separator or separator is the last character,
4184 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004185 VIM_CLEAR_STRING(compl_pattern);
4186 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4187 if (compl_pattern.string == NULL)
4188 return;
4189 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004190 }
4191 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004192 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004193 else
4194 {
4195 // Split leader into path and file parts
4196 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004197 char_u *path_with_wildcard;
4198
4199 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004200 if (path_with_wildcard != NULL)
4201 {
John Marriott5e6ea922024-11-23 14:01:57 +01004202 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4203 VIM_CLEAR_STRING(compl_pattern);
4204 compl_pattern.string = path_with_wildcard;
4205 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004206
4207 // Move leader to the file part
4208 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004209 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004210 }
4211 }
glepnir8159fb12024-07-17 20:32:54 +02004212 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004213
John Marriott5e6ea922024-11-23 14:01:57 +01004214 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004215 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4216 return;
4217
4218 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004219 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004220#ifdef BACKSLASH_IN_FILENAME
4221 if (curbuf->b_p_csl[0] != NUL)
4222 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004223 for (i = 0; i < num_matches; ++i)
4224 {
glepnir8159fb12024-07-17 20:32:54 +02004225 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004226 while (*ptr != NUL)
4227 {
4228 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4229 *ptr = '/';
4230 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4231 *ptr = '\\';
4232 ptr += (*mb_ptr2len)(ptr);
4233 }
4234 }
4235 }
4236#endif
glepnir8159fb12024-07-17 20:32:54 +02004237
glepnirf31cfa22025-03-06 21:59:13 +01004238 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004239 {
4240 ga_init2(&fuzzy_indices, sizeof(int), 10);
4241 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4242
4243 for (i = 0; i < num_matches; i++)
4244 {
4245 ptr = matches[i];
4246 score = fuzzy_match_str(ptr, leader);
4247 if (score > 0)
4248 {
4249 if (ga_grow(&fuzzy_indices, 1) == OK)
4250 {
4251 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4252 compl_fuzzy_scores[i] = score;
4253 fuzzy_indices.ga_len++;
4254 }
4255 }
4256 }
4257
Christian Brabandt220474d2024-07-20 13:26:44 +02004258 // prevent qsort from deref NULL pointer
4259 if (fuzzy_indices.ga_len > 0)
4260 {
glepnirf31cfa22025-03-06 21:59:13 +01004261 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004262 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4263 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004264
Christian Brabandt220474d2024-07-20 13:26:44 +02004265 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004266 {
4267 match = matches[fuzzy_indices_data[i]];
4268 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4269 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
4270 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4271 FALSE, NULL, current_score) == OK)
4272 dir = FORWARD;
4273
4274 if (need_collect_bests)
4275 {
4276 if (i == 0 || current_score == max_score)
4277 {
4278 compl_num_bests++;
4279 max_score = current_score;
4280 }
4281 }
4282 }
glepnir8159fb12024-07-17 20:32:54 +02004283
Christian Brabandt220474d2024-07-20 13:26:44 +02004284 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004285 }
glepnir6b6280c2024-07-27 16:25:45 +02004286 else if (leader_len > 0)
4287 {
4288 FreeWild(num_matches, matches);
4289 num_matches = 0;
4290 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004291
glepnir8159fb12024-07-17 20:32:54 +02004292 vim_free(compl_fuzzy_scores);
4293 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004294
4295 if (compl_num_bests > 0 && compl_get_longest)
4296 fuzzy_longest_match();
4297 return;
glepnir8159fb12024-07-17 20:32:54 +02004298 }
4299
glepnir6b6280c2024-07-27 16:25:45 +02004300 if (num_matches > 0)
4301 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004302}
4303
4304/*
4305 * Get the next set of command-line completions matching "compl_pattern".
4306 */
4307 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004308get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004309{
4310 char_u **matches;
4311 int num_matches;
4312
John Marriott5e6ea922024-11-23 14:01:57 +01004313 if (expand_cmdline(&compl_xp, compl_pattern.string,
4314 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004315 ins_compl_add_matches(num_matches, matches, FALSE);
4316}
4317
4318/*
4319 * Get the next set of spell suggestions matching "compl_pattern".
4320 */
4321 static void
4322get_next_spell_completion(linenr_T lnum UNUSED)
4323{
4324#ifdef FEAT_SPELL
4325 char_u **matches;
4326 int num_matches;
4327
John Marriott5e6ea922024-11-23 14:01:57 +01004328 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004329 if (num_matches > 0)
4330 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004331 else
4332 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004333#endif
4334}
4335
4336/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004337 * Return the next word or line from buffer "ins_buf" at position
4338 * "cur_match_pos" for completion. The length of the match is set in "len".
4339 */
4340 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004341ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004342 buf_T *ins_buf, // buffer being scanned
4343 pos_T *cur_match_pos, // current match position
4344 int *match_len,
4345 int *cont_s_ipos) // next ^X<> will set initial_pos
4346{
4347 char_u *ptr;
4348 int len;
4349
4350 *match_len = 0;
4351 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4352 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004353 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004354 if (ctrl_x_mode_line_or_eval())
4355 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004356 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004357 {
4358 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4359 return NULL;
4360 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004361 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004362 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004363 {
4364 char_u *tmp_ptr = ptr;
4365
4366 ptr = skipwhite(tmp_ptr);
4367 len -= (int)(ptr - tmp_ptr);
4368 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004369 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004370 }
4371 else
4372 {
4373 char_u *tmp_ptr = ptr;
4374
John Marriott5e6ea922024-11-23 14:01:57 +01004375 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004376 {
4377 tmp_ptr += compl_length;
4378 // Skip if already inside a word.
4379 if (vim_iswordp(tmp_ptr))
4380 return NULL;
4381 // Find start of next word.
4382 tmp_ptr = find_word_start(tmp_ptr);
4383 }
4384 // Find end of this word.
4385 tmp_ptr = find_word_end(tmp_ptr);
4386 len = (int)(tmp_ptr - ptr);
4387
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004388 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004389 {
4390 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4391 {
4392 // Try next line, if any. the new word will be
4393 // "join" as if the normal command "J" was used.
4394 // IOSIZE is always greater than
4395 // compl_length, so the next STRNCPY always
4396 // works -- Acevedo
4397 STRNCPY(IObuff, ptr, len);
4398 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4399 tmp_ptr = ptr = skipwhite(ptr);
4400 // Find start of next word.
4401 tmp_ptr = find_word_start(tmp_ptr);
4402 // Find end of next word.
4403 tmp_ptr = find_word_end(tmp_ptr);
4404 if (tmp_ptr > ptr)
4405 {
4406 if (*ptr != ')' && IObuff[len - 1] != TAB)
4407 {
4408 if (IObuff[len - 1] != ' ')
4409 IObuff[len++] = ' ';
4410 // IObuf =~ "\k.* ", thus len >= 2
4411 if (p_js
4412 && (IObuff[len - 2] == '.'
4413 || (vim_strchr(p_cpo, CPO_JOINSP)
4414 == NULL
4415 && (IObuff[len - 2] == '?'
4416 || IObuff[len - 2] == '!'))))
4417 IObuff[len++] = ' ';
4418 }
4419 // copy as much as possible of the new word
4420 if (tmp_ptr - ptr >= IOSIZE - len)
4421 tmp_ptr = ptr + IOSIZE - len - 1;
4422 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4423 len += (int)(tmp_ptr - ptr);
4424 *cont_s_ipos = TRUE;
4425 }
4426 IObuff[len] = NUL;
4427 ptr = IObuff;
4428 }
4429 if (len == compl_length)
4430 return NULL;
4431 }
4432 }
4433
4434 *match_len = len;
4435 return ptr;
4436}
4437
4438/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004439 * Get the next set of words matching "compl_pattern" for default completion(s)
4440 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004441 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4442 * position "st->start_pos" in the "compl_direction" direction. If
4443 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4444 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004445 * Returns OK if a new next match is found, otherwise returns FAIL.
4446 */
4447 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004448get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004449{
4450 int found_new_match = FAIL;
4451 int save_p_scs;
4452 int save_p_ws;
4453 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004454 char_u *ptr = NULL;
4455 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004456 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004457 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004458 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004459 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004460
4461 // If 'infercase' is set, don't use 'smartcase' here
4462 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004463 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004464 p_scs = FALSE;
4465
4466 // Buffers other than curbuf are scanned from the beginning or the
4467 // end but never from the middle, thus setting nowrapscan in this
4468 // buffer is a good idea, on the other hand, we always set
4469 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4470 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004471 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004472 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004473 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004474 p_ws = TRUE;
4475 looped_around = FALSE;
4476 for (;;)
4477 {
4478 int cont_s_ipos = FALSE;
4479
4480 ++msg_silent; // Don't want messages for wrapscan.
4481
glepnirf31cfa22025-03-06 21:59:13 +01004482 if (in_collect)
4483 {
glepnir8159fb12024-07-17 20:32:54 +02004484 found_new_match = search_for_fuzzy_match(st->ins_buf,
4485 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004486 start_pos, &len, &ptr, &score);
4487 }
4488 // ctrl_x_mode_line_or_eval() || word-wise search that
4489 // has added a word that was at the beginning of the line
4490 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4491 found_new_match = search_for_exact_line(st->ins_buf,
4492 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004493 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004494 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004495 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004496 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004497 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004498 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004499 {
4500 // set "compl_started" even on fail
4501 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004502 st->first_match_pos = *st->cur_match_pos;
4503 st->last_match_pos = *st->cur_match_pos;
4504 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004505 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004506 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4507 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004508 {
4509 found_new_match = FAIL;
4510 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004511 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004512 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4513 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4514 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004515 {
4516 if (looped_around)
4517 found_new_match = FAIL;
4518 else
4519 looped_around = TRUE;
4520 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004521 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004522 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4523 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4524 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004525 {
4526 if (looped_around)
4527 found_new_match = FAIL;
4528 else
4529 looped_around = TRUE;
4530 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004531 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004532 if (found_new_match == FAIL)
4533 break;
4534
4535 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004536 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004537 && start_pos->lnum == st->cur_match_pos->lnum
4538 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004539 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004540
glepnirf31cfa22025-03-06 21:59:13 +01004541 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004542 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4543 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004544 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004545 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004546
Girish Palyab1565882025-04-15 20:16:00 +02004547 if (is_nearest_active() && in_curbuf)
4548 {
4549 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4550 if (score < 0)
4551 score = -score;
4552 score++;
4553 }
4554
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004555 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004556 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004557 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004558 {
glepnirf31cfa22025-03-06 21:59:13 +01004559 if (in_collect && score == compl_first_match->cp_next->cp_score)
4560 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004561 found_new_match = OK;
4562 break;
4563 }
4564 }
4565 p_scs = save_p_scs;
4566 p_ws = save_p_ws;
4567
4568 return found_new_match;
4569}
4570
4571/*
Girish Palyacbe53192025-04-14 22:13:15 +02004572 * Return the callback function associated with "funcname".
4573 */
4574#ifdef FEAT_COMPL_FUNC
4575 static callback_T *
4576get_cpt_func_callback(char_u *funcname)
4577{
4578 static callback_T cb;
4579 char_u buf[LSIZE];
4580 int slen;
4581
4582 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4583 if (slen > 0 && option_set_callback_func(buf, &cb))
4584 return &cb;
4585 return NULL;
4586}
4587
4588/*
4589 * Retrieve new completion matches by invoking callback "cb".
4590 */
4591 static void
4592expand_cpt_function(callback_T *cb)
4593{
4594 // Re-insert the text removed by ins_compl_delete().
4595 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4596 // Get matches
4597 get_cpt_func_completion_matches(cb);
4598 // Undo insertion
4599 ins_compl_delete();
4600}
4601#endif
4602
4603/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004604 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004605 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004606 */
4607 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004608get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004609{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004610 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004611
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004612 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004613 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004614 case -1:
4615 break;
4616#ifdef FEAT_FIND_ID
4617 case CTRL_X_PATH_PATTERNS:
4618 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004619 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004620 break;
4621#endif
4622
4623 case CTRL_X_DICTIONARY:
4624 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004625 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4626 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004627 break;
4628
4629 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004630 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004631 break;
4632
4633 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004634 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004635 break;
4636
4637 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004638 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004639 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004640 break;
4641
4642#ifdef FEAT_COMPL_FUNC
4643 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004644 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4645 expand_cpt_function(st->func_cb);
4646 else
4647 expand_by_function(type, compl_pattern.string, NULL);
4648 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004649 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004650 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004651 break;
4652#endif
4653
4654 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004655 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004656 break;
4657
4658 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004659 found_new_match = get_next_default_completion(st, ini);
4660 if (found_new_match == FAIL && st->ins_buf == curbuf)
4661 st->found_all = TRUE;
4662 }
4663
4664 // check if compl_curr_match has changed, (e.g. other type of
4665 // expansion added something)
4666 if (type != 0 && compl_curr_match != compl_old_match)
4667 found_new_match = OK;
4668
4669 return found_new_match;
4670}
4671
4672/*
4673 * Get the next expansion(s), using "compl_pattern".
4674 * The search starts at position "ini" in curbuf and in the direction
4675 * compl_direction.
4676 * When "compl_started" is FALSE start at that position, otherwise continue
4677 * where we stopped searching before.
4678 * This may return before finding all the matches.
4679 * Return the total number of matches or -1 if still unknown -- Acevedo
4680 */
4681 static int
4682ins_compl_get_exp(pos_T *ini)
4683{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004684 static ins_compl_next_state_T st;
4685 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004686 int i;
4687 int found_new_match;
4688 int type = ctrl_x_mode;
4689
4690 if (!compl_started)
4691 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004692 buf_T *buf;
4693
4694 FOR_ALL_BUFFERS(buf)
4695 buf->b_scanned = 0;
4696 if (!st_cleared)
4697 {
4698 CLEAR_FIELD(st);
4699 st_cleared = TRUE;
4700 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004701 st.found_all = FALSE;
4702 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004703 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004704 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004705 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4706 ? (char_u *)"." : curbuf->b_p_cpt);
4707 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004708 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004709
4710 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
4711 && !cpt_compl_src_init(st.e_cpt))
4712 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004713 }
4714 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4715 st.ins_buf = curbuf; // In case the buffer was wiped out.
4716
4717 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004718 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004719 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004720
4721 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palyacbe53192025-04-14 22:13:15 +02004722 for (cpt_value_idx = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004723 {
4724 found_new_match = FAIL;
4725 st.set_match_pos = FALSE;
4726
4727 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4728 // or if found_all says this entry is done. For ^X^L only use the
4729 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004730 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004731 && (!compl_started || st.found_all))
4732 {
glepnir53b14572025-03-12 21:28:39 +01004733 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004734
4735 if (status == INS_COMPL_CPT_END)
4736 break;
4737 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004738 {
4739 cpt_value_idx++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004740 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004741 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004742 }
4743
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004744 // If complete() was called then compl_pattern has been reset. The
4745 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004746 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004747 break;
4748
4749 // get the next set of completion matches
4750 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004751
Girish Palyacbe53192025-04-14 22:13:15 +02004752 if (type > 0)
4753 cpt_value_idx++;
4754
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004755 // break the loop for specialized modes (use 'complete' just for the
4756 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4757 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004758 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4759 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004760 {
4761 if (got_int)
4762 break;
4763 // Fill the popup menu as soon as possible.
4764 if (type != -1)
4765 ins_compl_check_keys(0, FALSE);
4766
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004767 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004768 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4769 break;
4770 compl_started = TRUE;
4771 }
4772 else
4773 {
4774 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004775 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004776 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004777
4778 compl_started = FALSE;
4779 }
4780 }
Girish Palyacbe53192025-04-14 22:13:15 +02004781 cpt_value_idx = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004782 compl_started = TRUE;
4783
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004784 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004785 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004786 found_new_match = FAIL;
4787
4788 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004789 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004790 && !ctrl_x_mode_line_or_eval()))
4791 i = ins_compl_make_cyclic();
4792
glepnirf31cfa22025-03-06 21:59:13 +01004793 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4794 fuzzy_longest_match();
4795
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004796 if (compl_old_match != NULL)
4797 {
4798 // If several matches were added (FORWARD) or the search failed and has
4799 // just been made cyclic then we have to move compl_curr_match to the
4800 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004801 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004802 : compl_old_match->cp_prev;
4803 if (compl_curr_match == NULL)
4804 compl_curr_match = compl_old_match;
4805 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004806 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004807
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004808 return i;
4809}
4810
4811/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004812 * Update "compl_shown_match" to the actually shown match, it may differ when
4813 * "compl_leader" is used to omit some of the matches.
4814 */
4815 static void
4816ins_compl_update_shown_match(void)
4817{
4818 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004819 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004820 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004821 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004822 compl_shown_match = compl_shown_match->cp_next;
4823
4824 // If we didn't find it searching forward, and compl_shows_dir is
4825 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004826 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004827 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004828 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004829 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004830 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004831 {
4832 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004833 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004834 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004835 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004836 compl_shown_match = compl_shown_match->cp_prev;
4837 }
4838}
4839
4840/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004841 * Delete the old text being completed.
4842 */
4843 void
4844ins_compl_delete(void)
4845{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004846 // In insert mode: Delete the typed part.
4847 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004848 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01004849 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01004850 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004851 int has_preinsert = ins_compl_preinsert_effect();
4852 if (has_preinsert)
4853 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02004854 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004855 curwin->w_cursor.col = compl_ins_end_col;
4856 }
4857
glepnir76bdb822025-02-08 19:04:51 +01004858 if (curwin->w_cursor.lnum > compl_lnum)
4859 {
4860 if (curwin->w_cursor.col < ml_get_curline_len())
4861 {
John Marriottf4b36412025-02-23 09:09:59 +01004862 char_u *line = ml_get_cursor();
4863 remaining.length = ml_get_cursor_len();
4864 remaining.string = vim_strnsave(line, remaining.length);
4865 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01004866 return;
4867 }
4868 while (curwin->w_cursor.lnum > compl_lnum)
4869 {
4870 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4871 {
John Marriottf4b36412025-02-23 09:09:59 +01004872 if (remaining.string)
4873 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004874 return;
4875 }
zeertzjq060e6552025-02-21 20:06:26 +01004876 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01004877 curwin->w_cursor.lnum--;
4878 }
4879 // move cursor to end of line
4880 curwin->w_cursor.col = ml_get_curline_len();
4881 }
4882
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004883 if ((int)curwin->w_cursor.col > col)
4884 {
4885 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004886 {
John Marriottf4b36412025-02-23 09:09:59 +01004887 if (remaining.string)
4888 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004889 return;
glepnire3647c82025-02-10 21:16:32 +01004890 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004891 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004892 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004893 }
4894
John Marriottf4b36412025-02-23 09:09:59 +01004895 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01004896 {
4897 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01004898 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01004899 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01004900 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004901 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004902 // TODO: is this sufficient for redrawing? Redrawing everything causes
4903 // flicker, thus we can't do that.
4904 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004905#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004906 // clear v:completed_item
4907 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004908#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004909}
4910
4911/*
glepnir76bdb822025-02-08 19:04:51 +01004912 * Insert a completion string that contains newlines.
4913 * The string is split and inserted line by line.
4914 */
4915 static void
4916ins_compl_expand_multiple(char_u *str)
4917{
4918 char_u *start = str;
4919 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01004920 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01004921
4922 while (*curr != NUL)
4923 {
4924 if (*curr == '\n')
4925 {
4926 // Insert the text chunk before newline
4927 if (curr > start)
4928 ins_char_bytes(start, (int)(curr - start));
4929
4930 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01004931 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01004932 start = curr + 1;
4933 }
4934 curr++;
4935 }
4936
4937 // Handle remaining text after last newline (if any)
4938 if (curr > start)
4939 ins_char_bytes(start, (int)(curr - start));
4940
4941 compl_ins_end_col = curwin->w_cursor.col;
4942}
4943
4944/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004945 * Insert the new text being completed.
4946 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004947 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4948 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004949 */
4950 void
glepniredd4ac32025-01-29 18:53:51 +01004951ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004952{
glepnir76bdb822025-02-08 19:04:51 +01004953 int compl_len = get_compl_len();
4954 int preinsert = ins_compl_has_preinsert();
4955 char_u *cp_str = compl_shown_match->cp_str.string;
4956 size_t cp_str_len = compl_shown_match->cp_str.length;
4957 size_t leader_len = ins_compl_leader_len();
4958 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004959
4960 // Make sure we don't go over the end of the string, this can happen with
4961 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004962 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004963 {
glepnir76bdb822025-02-08 19:04:51 +01004964 if (has_multiple)
4965 ins_compl_expand_multiple(cp_str + compl_len);
4966 else
4967 {
4968 ins_compl_insert_bytes(cp_str + compl_len, -1);
4969 if (preinsert && move_cursor)
4970 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4971 }
glepniredd4ac32025-01-29 18:53:51 +01004972 }
4973 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004974 compl_used_match = FALSE;
4975 else
4976 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004977#ifdef FEAT_EVAL
4978 {
4979 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4980
4981 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4982 }
4983#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004984 if (!in_compl_func)
4985 compl_curr_match = compl_shown_match;
4986}
4987
4988/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004989 * show the file name for the completion match (if any). Truncate the file
4990 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004991 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004992 static void
4993ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004994{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004995 char *lead = _("match in file");
4996 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4997 char_u *s;
4998 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004999
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005000 if (space <= 0)
5001 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005002
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005003 // We need the tail that fits. With double-byte encoding going
5004 // back from the end is very slow, thus go from the start and keep
5005 // the text that fits in "space" between "s" and "e".
5006 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005007 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005008 space -= ptr2cells(e);
5009 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005010 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005011 space += ptr2cells(s);
5012 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005013 }
5014 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005015 msg_hist_off = TRUE;
5016 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5017 s > compl_shown_match->cp_fname ? "<" : "", s);
5018 msg((char *)IObuff);
5019 msg_hist_off = FALSE;
5020 redraw_cmdline = FALSE; // don't overwrite!
5021}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005022
glepnirdca57fb2024-06-04 22:01:21 +02005023/*
zeertzjq551d8c32024-06-05 19:53:32 +02005024 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005025 */
glepnira218cc62024-06-03 19:32:39 +02005026 static compl_T *
5027find_comp_when_fuzzy(void)
5028{
5029 int score;
5030 char_u* str;
5031 int target_idx = -1;
5032 int is_forward = compl_shows_dir_forward();
5033 int is_backward = compl_shows_dir_backward();
5034 compl_T *comp = NULL;
5035
glepnir43eef882024-06-19 20:20:48 +02005036 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005037 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02005038 return compl_first_match != compl_shown_match ?
5039 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02005040 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02005041
5042 if (is_forward)
5043 target_idx = compl_selected_item + 1;
5044 else if (is_backward)
5045 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005046 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005047
5048 score = compl_match_array[target_idx].pum_score;
5049 str = compl_match_array[target_idx].pum_text;
5050
5051 comp = compl_first_match;
5052 do {
John Marriott5e6ea922024-11-23 14:01:57 +01005053 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02005054 return comp;
5055 comp = comp->cp_next;
5056 } while (comp != NULL && !is_first_match(comp));
5057
5058 return NULL;
5059}
5060
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005061/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005062 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005063 * times. The number of matches found is returned in 'num_matches'.
5064 *
5065 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5066 * get more completions. If it is FALSE, then do nothing when there are no more
5067 * completions in the given direction.
5068 *
5069 * If "advance" is TRUE, then completion will move to the first match.
5070 * Otherwise, the original text will be shown.
5071 *
5072 * Returns OK on success and -1 if the number of matches are unknown.
5073 */
5074 static int
5075find_next_completion_match(
5076 int allow_get_expansion,
5077 int todo, // repeat completion this many times
5078 int advance,
5079 int *num_matches)
5080{
5081 int found_end = FALSE;
5082 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005083 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005084 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5085 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005086
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005087 while (--todo >= 0)
5088 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005089 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005090 {
glepniraced8c22024-06-15 15:13:05 +02005091 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
5092 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005093 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005094 && (is_first_match(compl_shown_match->cp_next)
5095 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005096 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005097 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005098 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005099 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005100 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02005101 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
5102 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005103 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005104 }
5105 else
5106 {
5107 if (!allow_get_expansion)
5108 {
5109 if (advance)
5110 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005111 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005112 compl_pending -= todo + 1;
5113 else
5114 compl_pending += todo + 1;
5115 }
5116 return -1;
5117 }
5118
5119 if (!compl_no_select && advance)
5120 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005121 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005122 --compl_pending;
5123 else
5124 ++compl_pending;
5125 }
5126
5127 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005128 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005129
5130 // handle any pending completions
5131 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005132 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005133 {
5134 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5135 {
5136 compl_shown_match = compl_shown_match->cp_next;
5137 --compl_pending;
5138 }
5139 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5140 {
5141 compl_shown_match = compl_shown_match->cp_prev;
5142 ++compl_pending;
5143 }
5144 else
5145 break;
5146 }
5147 found_end = FALSE;
5148 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005149 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005150 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005151 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005152 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005153 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005154 ++todo;
5155 else
5156 // Remember a matching item.
5157 found_compl = compl_shown_match;
5158
5159 // Stop at the end of the list when we found a usable match.
5160 if (found_end)
5161 {
5162 if (found_compl != NULL)
5163 {
5164 compl_shown_match = found_compl;
5165 break;
5166 }
5167 todo = 1; // use first usable match after wrapping around
5168 }
5169 }
5170
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005171 return OK;
5172}
5173
5174/*
5175 * Fill in the next completion in the current direction.
5176 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5177 * get more completions. If it is FALSE, then we just do nothing when there
5178 * are no more completions in a given direction. The latter case is used when
5179 * we are still in the middle of finding completions, to allow browsing
5180 * through the ones found so far.
5181 * Return the total number of matches, or -1 if still unknown -- webb.
5182 *
5183 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5184 * compl_shown_match here.
5185 *
5186 * Note that this function may be called recursively once only. First with
5187 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5188 * calls this function with "allow_get_expansion" FALSE.
5189 */
5190 static int
5191ins_compl_next(
5192 int allow_get_expansion,
5193 int count, // repeat completion this many times; should
5194 // be at least 1
5195 int insert_match, // Insert the newly selected match
5196 int in_compl_func) // called from complete_check()
5197{
5198 int num_matches = -1;
5199 int todo = count;
5200 int advance;
5201 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005202 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005203 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005204 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5205 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005206 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005207
5208 // When user complete function return -1 for findstart which is next
5209 // time of 'always', compl_shown_match become NULL.
5210 if (compl_shown_match == NULL)
5211 return -1;
5212
John Marriott5e6ea922024-11-23 14:01:57 +01005213 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005214 && !match_at_original_text(compl_shown_match)
5215 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005216 // Update "compl_shown_match" to the actually shown match
5217 ins_compl_update_shown_match();
5218
5219 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005220 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005221 // Delete old text to be replaced
5222 ins_compl_delete();
5223
5224 // When finding the longest common text we stick at the original text,
5225 // don't let CTRL-N or CTRL-P move to the first match.
5226 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5227
5228 // When restarting the search don't insert the first match either.
5229 if (compl_restarting)
5230 {
5231 advance = FALSE;
5232 compl_restarting = FALSE;
5233 }
5234
5235 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5236 // around.
5237 if (find_next_completion_match(allow_get_expansion, todo, advance,
5238 &num_matches) == -1)
5239 return -1;
5240
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005241 if (curbuf != orig_curbuf)
5242 {
5243 // In case some completion function switched buffer, don't want to
5244 // insert the completion elsewhere.
5245 return -1;
5246 }
5247
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005248 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005249 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005250 {
glepnir6a38aff2024-12-16 21:56:16 +01005251 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005252 compl_used_match = FALSE;
5253 }
5254 else if (insert_match)
5255 {
5256 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005257 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005258 else
glepnir6a38aff2024-12-16 21:56:16 +01005259 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005260 }
5261 else
5262 compl_used_match = FALSE;
5263
5264 if (!allow_get_expansion)
5265 {
5266 // may undisplay the popup menu first
5267 ins_compl_upd_pum();
5268
5269 if (pum_enough_matches())
5270 // Will display the popup menu, don't redraw yet to avoid flicker.
5271 pum_call_update_screen();
5272 else
5273 // Not showing the popup menu yet, redraw to show the user what was
5274 // inserted.
5275 update_screen(0);
5276
5277 // display the updated popup menu
5278 ins_compl_show_pum();
5279#ifdef FEAT_GUI
5280 if (gui.in_use)
5281 {
5282 // Show the cursor after the match, not after the redrawn text.
5283 setcursor();
5284 out_flush_cursor(FALSE, FALSE);
5285 }
5286#endif
5287
5288 // Delete old text to be replaced, since we're still searching and
5289 // don't want to match ourselves!
5290 ins_compl_delete();
5291 }
5292
5293 // Enter will select a match when the match wasn't inserted and the popup
5294 // menu is visible.
5295 if (compl_no_insert && !started)
5296 compl_enter_selects = TRUE;
5297 else
5298 compl_enter_selects = !insert_match && compl_match_array != NULL;
5299
5300 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005301 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005302 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005303
5304 return num_matches;
5305}
5306
5307/*
5308 * Call this while finding completions, to check whether the user has hit a key
5309 * that should change the currently displayed completion, or exit completion
5310 * mode. Also, when compl_pending is not zero, show a completion as soon as
5311 * possible. -- webb
5312 * "frequency" specifies out of how many calls we actually check.
5313 * "in_compl_func" is TRUE when called from complete_check(), don't set
5314 * compl_curr_match.
5315 */
5316 void
5317ins_compl_check_keys(int frequency, int in_compl_func)
5318{
5319 static int count = 0;
5320 int c;
5321
5322 // Don't check when reading keys from a script, :normal or feedkeys().
5323 // That would break the test scripts. But do check for keys when called
5324 // from complete_check().
5325 if (!in_compl_func && (using_script() || ex_normal_busy))
5326 return;
5327
5328 // Only do this at regular intervals
5329 if (++count < frequency)
5330 return;
5331 count = 0;
5332
5333 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5334 // can't do its work correctly.
5335 c = vpeekc_any();
5336 if (c != NUL)
5337 {
5338 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5339 {
5340 c = safe_vgetc(); // Eat the character
5341 compl_shows_dir = ins_compl_key2dir(c);
5342 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5343 c != K_UP && c != K_DOWN, in_compl_func);
5344 }
5345 else
5346 {
5347 // Need to get the character to have KeyTyped set. We'll put it
5348 // back with vungetc() below. But skip K_IGNORE.
5349 c = safe_vgetc();
5350 if (c != K_IGNORE)
5351 {
5352 // Don't interrupt completion when the character wasn't typed,
5353 // e.g., when doing @q to replay keys.
5354 if (c != Ctrl_R && KeyTyped)
5355 compl_interrupted = TRUE;
5356
5357 vungetc(c);
5358 }
5359 }
5360 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005361 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005362 {
5363 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5364
5365 compl_pending = 0;
5366 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5367 }
5368}
5369
5370/*
5371 * Decide the direction of Insert mode complete from the key typed.
5372 * Returns BACKWARD or FORWARD.
5373 */
5374 static int
5375ins_compl_key2dir(int c)
5376{
5377 if (c == Ctrl_P || c == Ctrl_L
5378 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5379 return BACKWARD;
5380 return FORWARD;
5381}
5382
5383/*
5384 * Return TRUE for keys that are used for completion only when the popup menu
5385 * is visible.
5386 */
5387 static int
5388ins_compl_pum_key(int c)
5389{
5390 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5391 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5392 || c == K_UP || c == K_DOWN);
5393}
5394
5395/*
5396 * Decide the number of completions to move forward.
5397 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5398 */
5399 static int
5400ins_compl_key2count(int c)
5401{
5402 int h;
5403
5404 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5405 {
5406 h = pum_get_height();
5407 if (h > 3)
5408 h -= 2; // keep some context
5409 return h;
5410 }
5411 return 1;
5412}
5413
5414/*
5415 * Return TRUE if completion with "c" should insert the match, FALSE if only
5416 * to change the currently selected completion.
5417 */
5418 static int
5419ins_compl_use_match(int c)
5420{
5421 switch (c)
5422 {
5423 case K_UP:
5424 case K_DOWN:
5425 case K_PAGEDOWN:
5426 case K_KPAGEDOWN:
5427 case K_S_DOWN:
5428 case K_PAGEUP:
5429 case K_KPAGEUP:
5430 case K_S_UP:
5431 return FALSE;
5432 }
5433 return TRUE;
5434}
5435
5436/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005437 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5438 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005439 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005440 * Uses the global variables: compl_cont_status and ctrl_x_mode
5441 */
5442 static int
5443get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5444{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005445 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005446 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005447 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005448 {
5449 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5450 ;
5451 compl_col += ++startcol;
5452 compl_length = curs_col - startcol;
5453 }
5454 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005455 {
John Marriott5e6ea922024-11-23 14:01:57 +01005456 compl_pattern.string = str_foldcase(line + compl_col,
5457 compl_length, NULL, 0);
5458 if (compl_pattern.string == NULL)
5459 {
5460 compl_pattern.length = 0;
5461 return FAIL;
5462 }
5463 compl_pattern.length = STRLEN(compl_pattern.string);
5464 }
5465 else
5466 {
5467 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5468 if (compl_pattern.string == NULL)
5469 {
5470 compl_pattern.length = 0;
5471 return FAIL;
5472 }
5473 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005474 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005475 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005476 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005477 {
5478 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005479 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005480 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005481
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005482 if (!vim_iswordp(line + compl_col)
5483 || (compl_col > 0
5484 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005485 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005486 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005487 prefixlen = 0;
5488 }
John Marriott5e6ea922024-11-23 14:01:57 +01005489
5490 // we need up to 2 extra chars for the prefix
5491 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5492 compl_pattern.string = alloc(n);
5493 if (compl_pattern.string == NULL)
5494 {
5495 compl_pattern.length = 0;
5496 return FAIL;
5497 }
5498 STRCPY((char *)compl_pattern.string, prefix);
5499 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005500 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005501 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005502 }
5503 else if (--startcol < 0
5504 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5505 {
John Marriott5e6ea922024-11-23 14:01:57 +01005506 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5507
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005508 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005509 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5510 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005511 {
John Marriott5e6ea922024-11-23 14:01:57 +01005512 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005513 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005514 }
John Marriott5e6ea922024-11-23 14:01:57 +01005515 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005516 compl_col += curs_col;
5517 compl_length = 0;
5518 }
5519 else
5520 {
5521 // Search the point of change class of multibyte character
5522 // or not a word single byte character backward.
5523 if (has_mbyte)
5524 {
5525 int base_class;
5526 int head_off;
5527
5528 startcol -= (*mb_head_off)(line, line + startcol);
5529 base_class = mb_get_class(line + startcol);
5530 while (--startcol >= 0)
5531 {
5532 head_off = (*mb_head_off)(line, line + startcol);
5533 if (base_class != mb_get_class(line + startcol
5534 - head_off))
5535 break;
5536 startcol -= head_off;
5537 }
5538 }
5539 else
5540 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5541 ;
5542 compl_col += ++startcol;
5543 compl_length = (int)curs_col - startcol;
5544 if (compl_length == 1)
5545 {
5546 // Only match word with at least two chars -- webb
5547 // there's no need to call quote_meta,
5548 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005549 compl_pattern.string = alloc(7);
5550 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005551 {
John Marriott5e6ea922024-11-23 14:01:57 +01005552 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005553 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005554 }
John Marriott5e6ea922024-11-23 14:01:57 +01005555 STRCPY((char *)compl_pattern.string, "\\<");
5556 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5557 STRCAT((char *)compl_pattern.string, "\\k");
5558 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005559 }
5560 else
5561 {
John Marriott5e6ea922024-11-23 14:01:57 +01005562 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5563
5564 compl_pattern.string = alloc(n);
5565 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005566 {
John Marriott5e6ea922024-11-23 14:01:57 +01005567 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005568 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005569 }
John Marriott5e6ea922024-11-23 14:01:57 +01005570 STRCPY((char *)compl_pattern.string, "\\<");
5571 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005572 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005573 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005574 }
5575 }
5576
5577 return OK;
5578}
5579
5580/*
5581 * Get the pattern, column and length for whole line completion or for the
5582 * complete() function.
5583 * Sets the global variables: compl_col, compl_length and compl_pattern.
5584 */
5585 static int
5586get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5587{
5588 compl_col = (colnr_T)getwhitecols(line);
5589 compl_length = (int)curs_col - (int)compl_col;
5590 if (compl_length < 0) // cursor in indent: empty pattern
5591 compl_length = 0;
5592 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005593 {
John Marriott5e6ea922024-11-23 14:01:57 +01005594 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5595 NULL, 0);
5596 if (compl_pattern.string == NULL)
5597 {
5598 compl_pattern.length = 0;
5599 return FAIL;
5600 }
5601 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005602 }
John Marriott5e6ea922024-11-23 14:01:57 +01005603 else
5604 {
5605 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5606 if (compl_pattern.string == NULL)
5607 {
5608 compl_pattern.length = 0;
5609 return FAIL;
5610 }
5611 compl_pattern.length = (size_t)compl_length;
5612 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005613
5614 return OK;
5615}
5616
5617/*
5618 * Get the pattern, column and length for filename completion.
5619 * Sets the global variables: compl_col, compl_length and compl_pattern.
5620 */
5621 static int
5622get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5623{
5624 // Go back to just before the first filename character.
5625 if (startcol > 0)
5626 {
5627 char_u *p = line + startcol;
5628
5629 MB_PTR_BACK(line, p);
5630 while (p > line && vim_isfilec(PTR2CHAR(p)))
5631 MB_PTR_BACK(line, p);
5632 if (p == line && vim_isfilec(PTR2CHAR(p)))
5633 startcol = 0;
5634 else
5635 startcol = (int)(p - line) + 1;
5636 }
5637
5638 compl_col += startcol;
5639 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005640 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5641 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005642 {
John Marriott5e6ea922024-11-23 14:01:57 +01005643 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005644 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005645 }
5646
John Marriott5e6ea922024-11-23 14:01:57 +01005647 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005648
5649 return OK;
5650}
5651
5652/*
5653 * Get the pattern, column and length for command-line completion.
5654 * Sets the global variables: compl_col, compl_length and compl_pattern.
5655 */
5656 static int
5657get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5658{
John Marriott5e6ea922024-11-23 14:01:57 +01005659 compl_pattern.string = vim_strnsave(line, curs_col);
5660 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005661 {
John Marriott5e6ea922024-11-23 14:01:57 +01005662 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005663 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005664 }
John Marriott5e6ea922024-11-23 14:01:57 +01005665 compl_pattern.length = curs_col;
5666 set_cmd_context(&compl_xp, compl_pattern.string,
5667 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005668 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5669 || compl_xp.xp_context == EXPAND_NOTHING)
5670 // No completion possible, use an empty pattern to get a
5671 // "pattern not found" message.
5672 compl_col = curs_col;
5673 else
John Marriott5e6ea922024-11-23 14:01:57 +01005674 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005675 compl_length = curs_col - compl_col;
5676
5677 return OK;
5678}
5679
5680/*
5681 * Get the pattern, column and length for user defined completion ('omnifunc',
5682 * 'completefunc' and 'thesaurusfunc')
5683 * Sets the global variables: compl_col, compl_length and compl_pattern.
5684 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005685 * Callback function "cb" is set if triggered by a function in the 'cpt'
5686 * option; otherwise, it is NULL.
5687 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005688 */
5689 static int
Girish Palyacbe53192025-04-14 22:13:15 +02005690get_userdefined_compl_info(colnr_T curs_col UNUSED, callback_T *cb UNUSED,
5691 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005692{
5693 int ret = FAIL;
5694
5695#ifdef FEAT_COMPL_FUNC
5696 // Call user defined function 'completefunc' with "a:findstart"
5697 // set to 1 to obtain the length of text to use for completion.
5698 char_u *line;
5699 typval_T args[3];
5700 int col;
5701 char_u *funcname;
5702 pos_T pos;
5703 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005704 int len;
5705 string_T *compl_pat;
5706 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005707
Girish Palyacbe53192025-04-14 22:13:15 +02005708 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005709 {
Girish Palyacbe53192025-04-14 22:13:15 +02005710 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5711 // length as a string
5712 funcname = get_complete_funcname(ctrl_x_mode);
5713 if (*funcname == NUL)
5714 {
5715 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5716 ? "completefunc" : "omnifunc");
5717 return FAIL;
5718 }
5719 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005720 }
5721
5722 args[0].v_type = VAR_NUMBER;
5723 args[0].vval.v_number = 1;
5724 args[1].v_type = VAR_STRING;
5725 args[1].vval.v_string = (char_u *)"";
5726 args[2].v_type = VAR_UNKNOWN;
5727 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005728 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005729 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005730 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005731
5732 State = save_State;
5733 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005734 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005735 validate_cursor();
5736 if (!EQUAL_POS(curwin->w_cursor, pos))
5737 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005738 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005739 return FAIL;
5740 }
5741
Girish Palyacbe53192025-04-14 22:13:15 +02005742 if (startcol != NULL)
5743 *startcol = col;
5744
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005745 // Return value -2 means the user complete function wants to cancel the
5746 // complete without an error, do the same if the function did not execute
5747 // successfully.
5748 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005749 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005750 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005751 if (col == -3)
5752 {
Girish Palyacbe53192025-04-14 22:13:15 +02005753 if (is_cpt_function)
5754 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005755 ctrl_x_mode = CTRL_X_NORMAL;
5756 edit_submode = NULL;
5757 if (!shortmess(SHM_COMPLETIONMENU))
5758 msg_clr_cmdline();
5759 return FAIL;
5760 }
5761
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005762 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005763 // completion.
5764 compl_opt_refresh_always = FALSE;
5765 compl_opt_suppress_empty = FALSE;
5766
Girish Palyacbe53192025-04-14 22:13:15 +02005767 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005768 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005769
5770 // Setup variables for completion. Need to obtain "line" again,
5771 // it may have become invalid.
5772 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02005773 len = curs_col - col;
5774 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
5775 compl_pat->string = vim_strnsave(line + col, (size_t)len);
5776 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005777 {
Girish Palyacbe53192025-04-14 22:13:15 +02005778 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005779 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005780 }
Girish Palyacbe53192025-04-14 22:13:15 +02005781 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005782
Girish Palyacbe53192025-04-14 22:13:15 +02005783 if (!is_cpt_function)
5784 {
5785 compl_col = col;
5786 compl_length = len;
5787 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005788 ret = OK;
5789#endif
5790
5791 return ret;
5792}
5793
5794/*
5795 * Get the pattern, column and length for spell completion.
5796 * Sets the global variables: compl_col, compl_length and compl_pattern.
5797 * Uses the global variable: spell_bad_len
5798 */
5799 static int
5800get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5801{
5802 int ret = FAIL;
5803#ifdef FEAT_SPELL
5804 char_u *line;
5805
5806 if (spell_bad_len > 0)
5807 compl_col = curs_col - spell_bad_len;
5808 else
5809 compl_col = spell_word_start(startcol);
5810 if (compl_col >= (colnr_T)startcol)
5811 {
5812 compl_length = 0;
5813 compl_col = curs_col;
5814 }
5815 else
5816 {
5817 spell_expand_check_cap(compl_col);
5818 compl_length = (int)curs_col - compl_col;
5819 }
5820 // Need to obtain "line" again, it may have become invalid.
5821 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005822 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5823 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005824 {
John Marriott5e6ea922024-11-23 14:01:57 +01005825 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005826 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005827 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005828
John Marriott5e6ea922024-11-23 14:01:57 +01005829 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005830 ret = OK;
5831#endif
5832
5833 return ret;
5834}
5835
5836/*
5837 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005838 * "startcol" - start column number of the completion pattern/text
5839 * "cur_col" - current cursor column
5840 * On return, "line_invalid" is set to TRUE, if the current line may have
5841 * become invalid and needs to be fetched again.
5842 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005843 */
5844 static int
5845compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5846{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005847 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005848 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5849 && !thesaurus_func_complete(ctrl_x_mode)))
5850 {
5851 return get_normal_compl_info(line, startcol, curs_col);
5852 }
5853 else if (ctrl_x_mode_line_or_eval())
5854 {
5855 return get_wholeline_compl_info(line, curs_col);
5856 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005857 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005858 {
5859 return get_filename_compl_info(line, startcol, curs_col);
5860 }
5861 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5862 {
5863 return get_cmdline_compl_info(line, curs_col);
5864 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005865 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005866 || thesaurus_func_complete(ctrl_x_mode))
5867 {
Girish Palyacbe53192025-04-14 22:13:15 +02005868 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005869 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005870 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005871 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005872 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005873 {
5874 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5875 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005876 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005877 }
5878 else
5879 {
5880 internal_error("ins_complete()");
5881 return FAIL;
5882 }
5883
5884 return OK;
5885}
5886
5887/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005888 * Continue an interrupted completion mode search in "line".
5889 *
5890 * If this same ctrl_x_mode has been interrupted use the text from
5891 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5892 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5893 * the same line as the cursor then fix it (the line has been split because it
5894 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5895 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005896 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005897 static void
5898ins_compl_continue_search(char_u *line)
5899{
5900 // it is a continued search
5901 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005902 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5903 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005904 {
5905 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5906 {
5907 // line (probably) wrapped, set compl_startpos to the
5908 // first non_blank in the line, if it is not a wordchar
5909 // include it to get a better pattern, but then we don't
5910 // want the "\\<" prefix, check it below
5911 compl_col = (colnr_T)getwhitecols(line);
5912 compl_startpos.col = compl_col;
5913 compl_startpos.lnum = curwin->w_cursor.lnum;
5914 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5915 }
5916 else
5917 {
5918 // S_IPOS was set when we inserted a word that was at the
5919 // beginning of the line, which means that we'll go to SOL
5920 // mode but first we need to redefine compl_startpos
5921 if (compl_cont_status & CONT_S_IPOS)
5922 {
5923 compl_cont_status |= CONT_SOL;
5924 compl_startpos.col = (colnr_T)(skipwhite(
5925 line + compl_length
5926 + compl_startpos.col) - line);
5927 }
5928 compl_col = compl_startpos.col;
5929 }
5930 compl_length = curwin->w_cursor.col - (int)compl_col;
5931 // IObuff is used to add a "word from the next line" would we
5932 // have enough space? just being paranoid
5933#define MIN_SPACE 75
5934 if (compl_length > (IOSIZE - MIN_SPACE))
5935 {
5936 compl_cont_status &= ~CONT_SOL;
5937 compl_length = (IOSIZE - MIN_SPACE);
5938 compl_col = curwin->w_cursor.col - compl_length;
5939 }
5940 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5941 if (compl_length < 1)
5942 compl_cont_status &= CONT_LOCAL;
5943 }
5944 else if (ctrl_x_mode_line_or_eval())
5945 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5946 else
5947 compl_cont_status = 0;
5948}
5949
5950/*
5951 * start insert mode completion
5952 */
5953 static int
5954ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005955{
5956 char_u *line;
5957 int startcol = 0; // column where searched text starts
5958 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005959 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005960 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005961 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005962
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005963 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005964
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005965 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005966 did_si = FALSE;
5967 can_si = FALSE;
5968 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005969 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005970 return FAIL;
5971
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005972 line = ml_get(curwin->w_cursor.lnum);
5973 curs_col = curwin->w_cursor.col;
5974 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005975 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005976
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005977 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5978 && compl_cont_mode == ctrl_x_mode)
5979 // this same ctrl-x_mode was interrupted previously. Continue the
5980 // completion.
5981 ins_compl_continue_search(line);
5982 else
5983 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005984
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005985 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005986 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005987 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005988 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005989 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5990 compl_cont_status = 0;
5991 compl_cont_status |= CONT_N_ADDS;
5992 compl_startpos = curwin->w_cursor;
5993 startcol = (int)curs_col;
5994 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005995 }
5996
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005997 // Work out completion pattern and original text -- webb
5998 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5999 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006000 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6001 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006002 // restore did_ai, so that adding comment leader works
6003 did_ai = save_did_ai;
6004 return FAIL;
6005 }
6006 // If "line" was changed while getting completion info get it again.
6007 if (line_invalid)
6008 line = ml_get(curwin->w_cursor.lnum);
6009
glepnir7cfe6932024-09-15 20:06:28 +02006010 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006011 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006012 {
6013 edit_submode_pre = (char_u *)_(" Adding");
6014 if (ctrl_x_mode_line_or_eval())
6015 {
6016 // Insert a new line, keep indentation but ignore 'comments'.
6017 char_u *old = curbuf->b_p_com;
6018
6019 curbuf->b_p_com = (char_u *)"";
6020 compl_startpos.lnum = curwin->w_cursor.lnum;
6021 compl_startpos.col = compl_col;
6022 ins_eol('\r');
6023 curbuf->b_p_com = old;
6024 compl_length = 0;
6025 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006026 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006027 }
glepnir7cfe6932024-09-15 20:06:28 +02006028 else if (ctrl_x_mode_normal() && in_fuzzy)
6029 {
6030 compl_startpos = curwin->w_cursor;
6031 compl_cont_status &= CONT_S_IPOS;
6032 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006033 }
6034 else
6035 {
6036 edit_submode_pre = NULL;
6037 compl_startpos.col = compl_col;
6038 }
6039
6040 if (compl_cont_status & CONT_LOCAL)
6041 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6042 else
6043 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6044
6045 // If any of the original typed text has been changed we need to fix
6046 // the redo buffer.
6047 ins_compl_fixRedoBufForLeader(NULL);
6048
6049 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006050 VIM_CLEAR_STRING(compl_orig_text);
6051 compl_orig_text.length = (size_t)compl_length;
6052 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006053 if (p_ic)
6054 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006055 if (compl_orig_text.string == NULL
6056 || ins_compl_add(compl_orig_text.string,
6057 (int)compl_orig_text.length,
6058 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006059 {
John Marriott5e6ea922024-11-23 14:01:57 +01006060 VIM_CLEAR_STRING(compl_pattern);
6061 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006062 return FAIL;
6063 }
6064
6065 // showmode might reset the internal line pointers, so it must
6066 // be called before line = ml_get(), or when this address is no
6067 // longer needed. -- Acevedo.
6068 edit_submode_extra = (char_u *)_("-- Searching...");
6069 edit_submode_highl = HLF_COUNT;
6070 showmode();
6071 edit_submode_extra = NULL;
6072 out_flush();
6073
6074 return OK;
6075}
6076
6077/*
6078 * display the completion status message
6079 */
6080 static void
6081ins_compl_show_statusmsg(void)
6082{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006083 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006084 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006085 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006086 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006087 ? (char_u *)_("Hit end of paragraph")
6088 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006089 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006090 }
6091
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006092 if (edit_submode_extra == NULL)
6093 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006094 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006095 {
6096 edit_submode_extra = (char_u *)_("Back at original");
6097 edit_submode_highl = HLF_W;
6098 }
6099 else if (compl_cont_status & CONT_S_IPOS)
6100 {
6101 edit_submode_extra = (char_u *)_("Word from other line");
6102 edit_submode_highl = HLF_COUNT;
6103 }
6104 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6105 {
6106 edit_submode_extra = (char_u *)_("The only match");
6107 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006108 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006109 }
6110 else
6111 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006112#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006113 // Update completion sequence number when needed.
6114 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006115 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006116#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006117 // The match should always have a sequence number now, this is
6118 // just a safety check.
6119 if (compl_curr_match->cp_number != -1)
6120 {
6121 // Space for 10 text chars. + 2x10-digit no.s = 31.
6122 // Translations may need more than twice that.
6123 static char_u match_ref[81];
6124
6125 if (compl_matches > 0)
6126 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006127 _("match %d of %d"),
6128 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006129 else
6130 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006131 _("match %d"),
6132 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006133 edit_submode_extra = match_ref;
6134 edit_submode_highl = HLF_R;
6135 if (dollar_vcol >= 0)
6136 curs_columns(FALSE);
6137 }
6138 }
6139 }
6140
6141 // Show a message about what (completion) mode we're in.
6142 if (!compl_opt_suppress_empty)
6143 {
6144 showmode();
6145 if (!shortmess(SHM_COMPLETIONMENU))
6146 {
6147 if (edit_submode_extra != NULL)
6148 {
6149 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006150 {
6151 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006152 msg_attr((char *)edit_submode_extra,
6153 edit_submode_highl < HLF_COUNT
6154 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006155 msg_hist_off = FALSE;
6156 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006157 }
6158 else
6159 msg_clr_cmdline(); // necessary for "noshowmode"
6160 }
6161 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006162}
6163
6164/*
6165 * Do Insert mode completion.
6166 * Called when character "c" was typed, which has a meaning for completion.
6167 * Returns OK if completion was done, FAIL if something failed (out of mem).
6168 */
6169 int
6170ins_complete(int c, int enable_pum)
6171{
6172 int n;
6173 int save_w_wrow;
6174 int save_w_leftcol;
6175 int insert_match;
6176
6177 compl_direction = ins_compl_key2dir(c);
6178 insert_match = ins_compl_use_match(c);
6179
6180 if (!compl_started)
6181 {
6182 if (ins_compl_start() == FAIL)
6183 return FAIL;
6184 }
6185 else if (insert_match && stop_arrow() == FAIL)
6186 return FAIL;
6187
glepnircf7f0122025-04-15 19:02:00 +02006188 compl_curr_win = curwin;
6189 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006190 compl_shown_match = compl_curr_match;
6191 compl_shows_dir = compl_direction;
6192
6193 // Find next match (and following matches).
6194 save_w_wrow = curwin->w_wrow;
6195 save_w_leftcol = curwin->w_leftcol;
6196 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6197
6198 // may undisplay the popup menu
6199 ins_compl_upd_pum();
6200
6201 if (n > 1) // all matches have been found
6202 compl_matches = n;
6203 compl_curr_match = compl_shown_match;
6204 compl_direction = compl_shows_dir;
6205
6206 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6207 // mode.
6208 if (got_int && !global_busy)
6209 {
6210 (void)vgetc();
6211 got_int = FALSE;
6212 }
6213
6214 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006215 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006216 {
6217 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6218 // because we couldn't expand anything at first place, but if we used
6219 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6220 // (such as M in M'exico) if not tried already. -- Acevedo
6221 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006222 || compl_status_adding()
6223 || (ctrl_x_mode_not_default()
6224 && !ctrl_x_mode_path_patterns()
6225 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006226 compl_cont_status &= ~CONT_N_ADDS;
6227 }
6228
6229 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6230 compl_cont_status |= CONT_S_IPOS;
6231 else
6232 compl_cont_status &= ~CONT_S_IPOS;
6233
6234 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006235
6236 // Show the popup menu, unless we got interrupted.
6237 if (enable_pum && !compl_interrupted)
6238 show_pum(save_w_wrow, save_w_leftcol);
6239
6240 compl_was_interrupted = compl_interrupted;
6241 compl_interrupted = FALSE;
6242
6243 return OK;
6244}
6245
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006246/*
6247 * Remove (if needed) and show the popup menu
6248 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006249 static void
6250show_pum(int prev_w_wrow, int prev_w_leftcol)
6251{
6252 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006253 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006254 RedrawingDisabled = 0;
6255
6256 // If the cursor moved or the display scrolled we need to remove the pum
6257 // first.
6258 setcursor();
6259 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6260 ins_compl_del_pum();
6261
6262 ins_compl_show_pum();
6263 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006264
6265 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006266}
6267
6268/*
6269 * Looks in the first "len" chars. of "src" for search-metachars.
6270 * If dest is not NULL the chars. are copied there quoting (with
6271 * a backslash) the metachars, and dest would be NUL terminated.
6272 * Returns the length (needed) of dest
6273 */
6274 static unsigned
6275quote_meta(char_u *dest, char_u *src, int len)
6276{
6277 unsigned m = (unsigned)len + 1; // one extra for the NUL
6278
6279 for ( ; --len >= 0; src++)
6280 {
6281 switch (*src)
6282 {
6283 case '.':
6284 case '*':
6285 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006286 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006287 break;
6288 // FALLTHROUGH
6289 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006290 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006291 break;
6292 // FALLTHROUGH
6293 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006294 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006295 break;
6296 // FALLTHROUGH
6297 case '^': // currently it's not needed.
6298 case '$':
6299 m++;
6300 if (dest != NULL)
6301 *dest++ = '\\';
6302 break;
6303 }
6304 if (dest != NULL)
6305 *dest++ = *src;
6306 // Copy remaining bytes of a multibyte character.
6307 if (has_mbyte)
6308 {
6309 int i, mb_len;
6310
6311 mb_len = (*mb_ptr2len)(src) - 1;
6312 if (mb_len > 0 && len >= mb_len)
6313 for (i = 0; i < mb_len; ++i)
6314 {
6315 --len;
6316 ++src;
6317 if (dest != NULL)
6318 *dest++ = *src;
6319 }
6320 }
6321 }
6322 if (dest != NULL)
6323 *dest = NUL;
6324
6325 return m;
6326}
6327
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006328#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006329 void
6330free_insexpand_stuff(void)
6331{
John Marriott5e6ea922024-11-23 14:01:57 +01006332 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006333# ifdef FEAT_EVAL
6334 free_callback(&cfu_cb);
6335 free_callback(&ofu_cb);
6336 free_callback(&tsrfu_cb);
6337# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006338}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006339#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006340
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006341#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006342/*
6343 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6344 * spelled word, if there is one.
6345 */
6346 static void
6347spell_back_to_badword(void)
6348{
6349 pos_T tpos = curwin->w_cursor;
6350
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006351 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006352 if (curwin->w_cursor.col != tpos.col)
6353 start_arrow(&tpos);
6354}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006355#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006356
6357/*
6358 * Reset the info associated with completion sources.
6359 */
6360 static void
6361cpt_compl_src_clear(void)
6362{
6363 VIM_CLEAR(cpt_func_refresh_always);
6364 cpt_value_idx = -1;
6365 cpt_value_count = 0;
6366}
6367
6368/*
6369 * Initialize the info associated with completion sources.
6370 */
6371 static int
6372cpt_compl_src_init(char_u *cpt_str)
6373{
6374 int count = 0;
6375 char_u *p = cpt_str;
6376
6377 while (*p)
6378 {
6379 while (*p == ',' || *p == ' ') // Skip delimiters
6380 p++;
6381 if (*p) // If not end of string, count this segment
6382 {
6383 count++;
6384 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6385 }
6386 }
6387 cpt_compl_src_clear();
6388 cpt_value_count = count;
6389 if (count > 0)
6390 {
6391 cpt_func_refresh_always = ALLOC_CLEAR_MULT(int, count);
6392 if (cpt_func_refresh_always == NULL)
6393 {
6394 cpt_value_count = 0;
6395 return FAIL;
6396 }
6397 }
6398 return OK;
6399}
6400
6401/*
6402 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6403 */
6404 static int
6405is_cpt_func_refresh_always(void)
6406{
6407#ifdef FEAT_COMPL_FUNC
6408 int i;
6409
6410 for (i = 0; i < cpt_value_count; i++)
6411 if (cpt_func_refresh_always[i])
6412 return TRUE;
6413#endif
6414 return FALSE;
6415}
6416
6417/*
6418 * Make the completion list non-cyclic.
6419 */
6420#ifdef FEAT_COMPL_FUNC
6421 static void
6422ins_compl_make_linear(void)
6423{
6424 compl_T *m;
6425
6426 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6427 return;
6428 m = compl_first_match->cp_prev;
6429 m->cp_next = NULL;
6430 compl_first_match->cp_prev = NULL;
6431}
6432#endif
6433
6434/*
6435 * Remove the matches linked to the current completion source (as indicated by
6436 * cpt_value_idx) from the completion list.
6437 */
6438#ifdef FEAT_COMPL_FUNC
6439 static compl_T *
6440remove_old_matches(void)
6441{
6442 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6443 compl_T *current, *next;
6444 int compl_shown_removed = FALSE;
6445 int forward = compl_dir_forward();
6446
6447 // Identify the sublist of old matches that needs removal
6448 for (current = compl_first_match; current != NULL; current = current->cp_next)
6449 {
6450 if (current->cp_cpt_value_idx < cpt_value_idx && (forward || (!forward && !insert_at)))
6451 insert_at = current;
6452
6453 if (current->cp_cpt_value_idx == cpt_value_idx)
6454 {
6455 if (!sublist_start)
6456 sublist_start = current;
6457 sublist_end = current;
6458 if (!compl_shown_removed && compl_shown_match == current)
6459 compl_shown_removed = TRUE;
6460 }
6461
6462 if ((forward && current->cp_cpt_value_idx > cpt_value_idx) || (!forward && insert_at))
6463 break;
6464 }
6465
6466 // Re-assign compl_shown_match if necessary
6467 if (compl_shown_removed)
6468 {
6469 if (forward)
6470 compl_shown_match = compl_first_match;
6471 else
6472 { // Last node will have the prefix that is being completed
6473 for (current = compl_first_match; current->cp_next != NULL; current = current->cp_next)
6474 ;
6475 compl_shown_match = current;
6476 }
6477 }
6478
6479 if (!sublist_start) // No nodes to remove
6480 return insert_at;
6481
6482 // Update links to remove sublist
6483 if (sublist_start->cp_prev)
6484 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6485 else
6486 compl_first_match = sublist_end->cp_next;
6487
6488 if (sublist_end->cp_next)
6489 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6490
6491 // Free all nodes in the sublist
6492 sublist_end->cp_next = NULL;
6493 for (current = sublist_start; current != NULL; current = next)
6494 {
6495 next = current->cp_next;
6496 ins_compl_item_free(current);
6497 }
6498
6499 return insert_at;
6500}
6501#endif
6502
6503/*
6504 * Retrieve completion matches using the callback function "cb" and store the
6505 * 'refresh:always' flag.
6506 */
6507#ifdef FEAT_COMPL_FUNC
6508 static void
6509get_cpt_func_completion_matches(callback_T *cb UNUSED)
6510{
6511 int ret;
6512 int startcol;
6513
6514 VIM_CLEAR_STRING(cpt_compl_pattern);
6515 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6516 if (ret == FAIL && startcol == -3)
6517 cpt_func_refresh_always[cpt_value_idx] = FALSE;
6518 else if (ret == OK)
6519 {
6520 expand_by_function(0, cpt_compl_pattern.string, cb);
6521 cpt_func_refresh_always[cpt_value_idx] = compl_opt_refresh_always;
6522 compl_opt_refresh_always = FALSE;
6523 }
6524}
6525#endif
6526
6527/*
6528 * Retrieve completion matches from functions in the 'cpt' option where the
6529 * 'refresh:always' flag is set.
6530 */
6531 static void
6532cpt_compl_refresh(void)
6533{
6534#ifdef FEAT_COMPL_FUNC
6535 char_u *cpt;
6536 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006537 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006538
6539 // Make the completion list linear (non-cyclic)
6540 ins_compl_make_linear();
6541 // Make a copy of 'cpt' in case the buffer gets wiped out
6542 cpt = vim_strsave(curbuf->b_p_cpt);
6543
6544 cpt_value_idx = 0;
6545 for (p = cpt; *p; cpt_value_idx++)
6546 {
6547 while (*p == ',' || *p == ' ') // Skip delimiters
6548 p++;
6549
6550 if (cpt_func_refresh_always[cpt_value_idx])
6551 {
6552 if (*p == 'o')
6553 cb = &curbuf->b_ofu_cb;
6554 else if (*p == 'f')
6555 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6556 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6557 if (cb)
6558 {
6559 compl_curr_match = remove_old_matches();
6560 get_cpt_func_completion_matches(cb);
6561 }
6562 }
6563
6564 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6565 }
6566 cpt_value_idx = -1;
6567
6568 vim_free(cpt);
6569 // Make the list cyclic
6570 compl_matches = ins_compl_make_cyclic();
6571#endif
6572}