blob: 55c0e483e28b080c8b300ad017d73c8fdb920ff8 [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
glepnir001c26c2025-02-02 09:36:22 +01002760 if ((c == Ctrl_W || c == Ctrl_U) && ins_compl_preinsert_effect())
2761 ins_compl_delete();
2762
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002763 auto_format(FALSE, TRUE);
2764
2765 // Trigger the CompleteDonePre event to give scripts a chance to
2766 // act upon the completion before clearing the info, and restore
2767 // ctrl_x_mode, so that complete_info() can be used.
2768 ctrl_x_mode = prev_mode;
2769 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2770
2771 ins_compl_free();
2772 compl_started = FALSE;
2773 compl_matches = 0;
2774 if (!shortmess(SHM_COMPLETIONMENU))
2775 msg_clr_cmdline(); // necessary for "noshowmode"
2776 ctrl_x_mode = CTRL_X_NORMAL;
2777 compl_enter_selects = FALSE;
2778 if (edit_submode != NULL)
2779 {
2780 edit_submode = NULL;
2781 showmode();
2782 }
2783
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002784 if (c == Ctrl_C && cmdwin_type != 0)
2785 // Avoid the popup menu remains displayed when leaving the
2786 // command line window.
2787 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002788 // Indent now if a key was typed that is in 'cinkeys'.
2789 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2790 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002791 // Trigger the CompleteDone event to give scripts a chance to act
2792 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002793 trigger_complete_done_event(prev_mode, word);
2794 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002795
2796 return retval;
2797}
2798
2799/*
glepnircf7f0122025-04-15 19:02:00 +02002800 * Cancel completion.
2801 */
2802 int
2803ins_compl_cancel(void)
2804{
2805 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2806}
2807
2808/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002809 * Prepare for Insert mode completion, or stop it.
2810 * Called just after typing a character in Insert mode.
2811 * Returns TRUE when the character is not to be inserted;
2812 */
2813 int
2814ins_compl_prep(int c)
2815{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002816 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002817 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002818
2819 // Forget any previous 'special' messages if this is actually
2820 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2821 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2822 edit_submode_extra = NULL;
2823
zeertzjq440d4cb2023-03-02 17:51:32 +00002824 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002825 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002826 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002827 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002828 return retval;
2829
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002830#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002831 // Ignore mouse events in a popup window
2832 if (is_mouse_key(c))
2833 {
2834 // Ignore drag and release events, the position does not need to be in
2835 // the popup and it may have just closed.
2836 if (c == K_LEFTRELEASE
2837 || c == K_LEFTRELEASE_NM
2838 || c == K_MIDDLERELEASE
2839 || c == K_RIGHTRELEASE
2840 || c == K_X1RELEASE
2841 || c == K_X2RELEASE
2842 || c == K_LEFTDRAG
2843 || c == K_MIDDLEDRAG
2844 || c == K_RIGHTDRAG
2845 || c == K_X1DRAG
2846 || c == K_X2DRAG)
2847 return retval;
2848 if (popup_visible)
2849 {
2850 int row = mouse_row;
2851 int col = mouse_col;
2852 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2853
2854 if (wp != NULL && WIN_IS_POPUP(wp))
2855 return retval;
2856 }
2857 }
2858#endif
2859
zeertzjqdca29d92021-08-31 19:12:51 +02002860 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2861 {
2862 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2863 || !vim_is_ctrl_x_key(c))
2864 {
2865 // Not starting another completion mode.
2866 ctrl_x_mode = CTRL_X_CMDLINE;
2867
2868 // CTRL-X CTRL-Z should stop completion without inserting anything
2869 if (c == Ctrl_Z)
2870 retval = TRUE;
2871 }
2872 else
2873 {
2874 ctrl_x_mode = CTRL_X_CMDLINE;
2875
2876 // Other CTRL-X keys first stop completion, then start another
2877 // completion mode.
2878 ins_compl_prep(' ');
2879 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2880 }
2881 }
2882
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002883 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002884 if (ctrl_x_mode_not_defined_yet()
2885 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002886 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002887 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002888 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002889 }
2890
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002891 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002892 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2893 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002894 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002895 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002896 {
2897 // We're already in CTRL-X mode, do we stay in it?
2898 if (!vim_is_ctrl_x_key(c))
2899 {
glepnir40891ba2025-02-10 22:18:00 +01002900 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002901 edit_submode = NULL;
2902 }
2903 showmode();
2904 }
2905
2906 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2907 {
2908 // Show error message from attempted keyword completion (probably
2909 // 'Pattern not found') until another key is hit, then go back to
2910 // showing what mode we are in.
2911 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002912 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002913 && c != Ctrl_R && !ins_compl_pum_key(c))
2914 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002915 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002916 }
2917 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2918 // Trigger the CompleteDone event to give scripts a chance to act
2919 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002920 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002921
LemonBoy2bf52dd2022-04-09 18:17:34 +01002922 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002923
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002924 // reset continue_* if we left expansion-mode, if we stay they'll be
2925 // (re)set properly in ins_complete()
2926 if (!vim_is_ctrl_x_key(c))
2927 {
2928 compl_cont_status = 0;
2929 compl_cont_mode = 0;
2930 }
2931
2932 return retval;
2933}
2934
2935/*
2936 * Fix the redo buffer for the completion leader replacing some of the typed
2937 * text. This inserts backspaces and appends the changed text.
2938 * "ptr" is the known leader text or NUL.
2939 */
2940 static void
2941ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2942{
John Marriott5e6ea922024-11-23 14:01:57 +01002943 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002944 char_u *p;
2945 char_u *ptr = ptr_arg;
2946
2947 if (ptr == NULL)
2948 {
John Marriott5e6ea922024-11-23 14:01:57 +01002949 if (compl_leader.string != NULL)
2950 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002951 else
2952 return; // nothing to do
2953 }
John Marriott5e6ea922024-11-23 14:01:57 +01002954 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002955 {
John Marriott5e6ea922024-11-23 14:01:57 +01002956 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002957 // Find length of common prefix between original text and new completion
2958 while (p[len] != NUL && p[len] == ptr[len])
2959 len++;
2960 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002961 if (len > 0)
2962 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002963 // Add backspace characters for each remaining character in
2964 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002965 for (p += len; *p != NUL; MB_PTR_ADV(p))
2966 AppendCharToRedobuff(K_BS);
2967 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002968 if (ptr != NULL)
2969 AppendToRedobuffLit(ptr + len, -1);
2970}
2971
2972/*
2973 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2974 * (depending on flag) starting from buf and looking for a non-scanned
2975 * buffer (other than curbuf). curbuf is special, if it is called with
2976 * buf=curbuf then it has to be the first call for a given flag/expansion.
2977 *
2978 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2979 */
2980 static buf_T *
2981ins_compl_next_buf(buf_T *buf, int flag)
2982{
2983 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01002984 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002985
2986 if (flag == 'w') // just windows
2987 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002988 if (buf == curbuf || !win_valid(wp))
2989 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002990 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01002991
2992 while (TRUE)
2993 {
2994 // Move to next window (wrap to first window if at the end)
2995 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
2996 // Break if we're back at start or found an unscanned buffer
2997 if (wp == curwin || !wp->w_buffer->b_scanned)
2998 break;
2999 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003000 buf = wp->w_buffer;
3001 }
3002 else
glepnir40891ba2025-02-10 22:18:00 +01003003 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003004 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3005 // (unlisted buffers)
3006 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003007 while (TRUE)
3008 {
3009 // Move to next buffer (wrap to first buffer if at the end)
3010 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3011 // Break if we're back at start buffer
3012 if (buf == curbuf)
3013 break;
3014
3015 // Check buffer conditions based on flag
3016 if (flag == 'U')
3017 skip_buffer = buf->b_p_bl;
3018 else
3019 skip_buffer = !buf->b_p_bl ||
3020 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3021
3022 // Break if we found a buffer that matches our criteria
3023 if (!skip_buffer && !buf->b_scanned)
3024 break;
3025 }
3026 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003027 return buf;
3028}
3029
3030#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003031
3032# ifdef FEAT_EVAL
3033static callback_T cfu_cb; // 'completefunc' callback function
3034static callback_T ofu_cb; // 'omnifunc' callback function
3035static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3036# endif
3037
3038/*
3039 * Copy a global callback function to a buffer local callback.
3040 */
3041 static void
3042copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3043{
3044 free_callback(bufcb);
3045 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3046 copy_callback(bufcb, globcb);
3047}
3048
3049/*
3050 * Parse the 'completefunc' option value and set the callback function.
3051 * Invoked when the 'completefunc' option is set. The option value can be a
3052 * name of a function (string), or function(<name>) or funcref(<name>) or a
3053 * lambda expression.
3054 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003055 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003056did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003057{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003058 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3059 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003060
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003061 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003062
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003063 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003064}
3065
3066/*
3067 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003068 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003069 */
3070 void
3071set_buflocal_cfu_callback(buf_T *buf UNUSED)
3072{
3073# ifdef FEAT_EVAL
3074 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3075# endif
3076}
3077
3078/*
3079 * Parse the 'omnifunc' option value and set the callback function.
3080 * Invoked when the 'omnifunc' option is set. The option value can be a
3081 * name of a function (string), or function(<name>) or funcref(<name>) or a
3082 * lambda expression.
3083 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003084 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003085did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003086{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003087 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3088 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003089
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003090 set_buflocal_ofu_callback(curbuf);
3091 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003092}
3093
3094/*
3095 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003096 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003097 */
3098 void
3099set_buflocal_ofu_callback(buf_T *buf UNUSED)
3100{
3101# ifdef FEAT_EVAL
3102 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3103# endif
3104}
3105
3106/*
3107 * Parse the 'thesaurusfunc' option value and set the callback function.
3108 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3109 * name of a function (string), or function(<name>) or funcref(<name>) or a
3110 * lambda expression.
3111 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003112 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003113did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003114{
3115 int retval;
3116
zeertzjq6eda2692024-11-03 09:23:33 +01003117 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003118 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003119 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3120 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003121 else
3122 {
3123 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003124 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003125 // when using :set, free the local callback
3126 if (!(args->os_flags & OPT_GLOBAL))
3127 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003128 }
3129
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003130 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003131}
3132
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003133/*
3134 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003135 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003136 */
3137 int
3138set_ref_in_insexpand_funcs(int copyID)
3139{
3140 int abort = FALSE;
3141
3142 abort = set_ref_in_callback(&cfu_cb, copyID);
3143 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3144 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3145
3146 return abort;
3147}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003148
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003149/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003150 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003151 */
3152 static char_u *
3153get_complete_funcname(int type)
3154{
3155 switch (type)
3156 {
3157 case CTRL_X_FUNCTION:
3158 return curbuf->b_p_cfu;
3159 case CTRL_X_OMNI:
3160 return curbuf->b_p_ofu;
3161 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003162 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003163 default:
3164 return (char_u *)"";
3165 }
3166}
3167
3168/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003169 * Get the callback to use for insert mode completion.
3170 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003171 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003172get_insert_callback(int type)
3173{
3174 if (type == CTRL_X_FUNCTION)
3175 return &curbuf->b_cfu_cb;
3176 if (type == CTRL_X_OMNI)
3177 return &curbuf->b_ofu_cb;
3178 // CTRL_X_THESAURUS
3179 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3180}
3181
3182/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003183 * Execute user defined complete function 'completefunc', 'omnifunc' or
3184 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003185 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3186 * Callback function "cb" is set if triggered by a function in the 'cpt'
3187 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003188 */
3189 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003190expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003191{
3192 list_T *matchlist = NULL;
3193 dict_T *matchdict = NULL;
3194 typval_T args[3];
3195 char_u *funcname;
3196 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003197 typval_T rettv;
3198 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003199 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003200 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003201
Girish Palyacbe53192025-04-14 22:13:15 +02003202 if (!is_cpt_function)
3203 {
3204 funcname = get_complete_funcname(type);
3205 if (*funcname == NUL)
3206 return;
3207 cb = get_insert_callback(type);
3208 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003209
3210 // Call 'completefunc' to obtain the list of matches.
3211 args[0].v_type = VAR_NUMBER;
3212 args[0].vval.v_number = 0;
3213 args[1].v_type = VAR_STRING;
3214 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3215 args[2].v_type = VAR_UNKNOWN;
3216
3217 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003218 // Lock the text to avoid weird things from happening. Also disallow
3219 // switching to another window, it should not be needed and may end up in
3220 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003221 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003222
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003223 retval = call_callback(cb, 0, &rettv, 2, args);
3224
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003225 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003226 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003227 {
3228 switch (rettv.v_type)
3229 {
3230 case VAR_LIST:
3231 matchlist = rettv.vval.v_list;
3232 break;
3233 case VAR_DICT:
3234 matchdict = rettv.vval.v_dict;
3235 break;
3236 case VAR_SPECIAL:
3237 if (rettv.vval.v_number == VVAL_NONE)
3238 compl_opt_suppress_empty = TRUE;
3239 // FALLTHROUGH
3240 default:
3241 // TODO: Give error message?
3242 clear_tv(&rettv);
3243 break;
3244 }
3245 }
zeertzjqcfe45652022-05-27 17:26:55 +01003246 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003247
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003248 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003249 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003250 validate_cursor();
3251 if (!EQUAL_POS(curwin->w_cursor, pos))
3252 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003253 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003254 goto theend;
3255 }
3256
3257 if (matchlist != NULL)
3258 ins_compl_add_list(matchlist);
3259 else if (matchdict != NULL)
3260 ins_compl_add_dict(matchdict);
3261
3262theend:
3263 // Restore State, it might have been changed.
3264 State = save_State;
3265
3266 if (matchdict != NULL)
3267 dict_unref(matchdict);
3268 if (matchlist != NULL)
3269 list_unref(matchlist);
3270}
3271#endif // FEAT_COMPL_FUNC
3272
3273#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003274
3275 static inline int
3276get_user_highlight_attr(char_u *hlname)
3277{
3278 if (hlname != NULL && *hlname != NUL)
3279 return syn_name2attr(hlname);
3280 return -1;
3281}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003282/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003283 * Add a match to the list of matches from a typeval_T.
3284 * If the given string is already in the list of completions, then return
3285 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3286 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003287 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003288 */
3289 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003290ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003291{
3292 char_u *word;
3293 int dup = FALSE;
3294 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003295 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003296 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003297 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003298 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003299 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003300 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003301 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003302
Bram Moolenaar08928322020-01-04 14:32:48 +01003303 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003304 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3305 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003306 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3307 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3308 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3309 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3310 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003311
glepnir0fe17f82024-10-08 22:26:44 +02003312 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003313 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003314
3315 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003316 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003317
Bram Moolenaard61efa52022-07-23 09:52:04 +01003318 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3319 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3320 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003321 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003322 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3323 dup = dict_get_number(tv->vval.v_dict, "dup");
3324 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3325 empty = dict_get_number(tv->vval.v_dict, "empty");
3326 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3327 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003328 flags |= CP_EQUAL;
3329 }
3330 else
3331 {
3332 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003333 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003334 }
3335 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003336 {
3337 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003338 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003339 }
glepnir508e7852024-07-25 21:39:08 +02003340 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003341 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003342 if (status != OK)
3343 clear_tv(&user_data);
3344 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003345}
3346
3347/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003348 * Add completions from a list.
3349 */
3350 static void
3351ins_compl_add_list(list_T *list)
3352{
3353 listitem_T *li;
3354 int dir = compl_direction;
3355
3356 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003357 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003358 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003359 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003360 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003361 // if dir was BACKWARD then honor it just once
3362 dir = FORWARD;
3363 else if (did_emsg)
3364 break;
3365 }
3366}
3367
3368/*
3369 * Add completions from a dict.
3370 */
3371 static void
3372ins_compl_add_dict(dict_T *dict)
3373{
3374 dictitem_T *di_refresh;
3375 dictitem_T *di_words;
3376
3377 // Check for optional "refresh" item.
3378 compl_opt_refresh_always = FALSE;
3379 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3380 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3381 {
3382 char_u *v = di_refresh->di_tv.vval.v_string;
3383
3384 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3385 compl_opt_refresh_always = TRUE;
3386 }
3387
3388 // Add completions from a "words" list.
3389 di_words = dict_find(dict, (char_u *)"words", 5);
3390 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3391 ins_compl_add_list(di_words->di_tv.vval.v_list);
3392}
3393
3394/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003395 * Start completion for the complete() function.
3396 * "startcol" is where the matched text starts (1 is first column).
3397 * "list" is the list of matches.
3398 */
3399 static void
3400set_completion(colnr_T startcol, list_T *list)
3401{
3402 int save_w_wrow = curwin->w_wrow;
3403 int save_w_leftcol = curwin->w_leftcol;
3404 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003405 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003406 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3407 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3408 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003409
3410 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003411 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003412 ins_compl_prep(' ');
3413 ins_compl_clear();
3414 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003415 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003416
3417 compl_direction = FORWARD;
3418 if (startcol > curwin->w_cursor.col)
3419 startcol = curwin->w_cursor.col;
3420 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003421 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003422 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3423 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003424 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3425 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003426 if (p_ic)
3427 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003428 if (compl_orig_text.string == NULL)
3429 {
3430 compl_orig_text.length = 0;
3431 return;
3432 }
3433 compl_orig_text.length = (size_t)compl_length;
3434 if (ins_compl_add(compl_orig_text.string,
3435 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
glepnirf31cfa22025-03-06 21:59:13 +01003436 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003437 return;
3438
3439 ctrl_x_mode = CTRL_X_EVAL;
3440
3441 ins_compl_add_list(list);
3442 compl_matches = ins_compl_make_cyclic();
3443 compl_started = TRUE;
3444 compl_used_match = TRUE;
3445 compl_cont_status = 0;
3446
3447 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003448 int no_select = compl_no_select || compl_longest;
3449 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003450 {
3451 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003452 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003453 // Down/Up has no real effect.
3454 ins_complete(K_UP, FALSE);
3455 }
3456 else
3457 ins_complete(Ctrl_N, FALSE);
3458 compl_enter_selects = compl_no_insert;
3459
3460 // Lazily show the popup menu, unless we got interrupted.
3461 if (!compl_interrupted)
3462 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003463 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003464 out_flush();
3465}
3466
3467/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003468 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003469 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003470 void
3471f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003472{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003473 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003474
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003475 if (in_vim9script()
3476 && (check_for_number_arg(argvars, 0) == FAIL
3477 || check_for_list_arg(argvars, 1) == FAIL))
3478 return;
3479
Bram Moolenaar24959102022-05-07 20:01:16 +01003480 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003481 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003482 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003483 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003484 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003485
3486 // Check for undo allowed here, because if something was already inserted
3487 // the line was already saved for undo and this check isn't done.
3488 if (!undo_allowed())
3489 return;
3490
Bram Moolenaard83392a2022-09-01 12:22:46 +01003491 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003492 {
3493 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3494 if (startcol > 0)
3495 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003496 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003497}
3498
3499/*
3500 * "complete_add()" function
3501 */
3502 void
3503f_complete_add(typval_T *argvars, typval_T *rettv)
3504{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003505 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003506 return;
3507
Bram Moolenaar440cf092021-04-03 20:13:30 +02003508 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003509}
3510
3511/*
3512 * "complete_check()" function
3513 */
3514 void
3515f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3516{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003517 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003518 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003519
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003520 ins_compl_check_keys(0, TRUE);
3521 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003522
3523 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003524}
3525
3526/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003527 * Return Insert completion mode name string
3528 */
3529 static char_u *
3530ins_compl_mode(void)
3531{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003532 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003533 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3534
3535 return (char_u *)"";
3536}
3537
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003538/*
3539 * Assign the sequence number to all the completion matches which don't have
3540 * one assigned yet.
3541 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003542 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003543ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003544{
3545 int number = 0;
3546 compl_T *match;
3547
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003548 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003549 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003550 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003551 // This should normally succeed already at the first loop
3552 // cycle, so it's fast!
3553 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003554 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003555 if (match->cp_number != -1)
3556 {
3557 number = match->cp_number;
3558 break;
3559 }
3560 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003561 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003562 for (match = match->cp_next;
3563 match != NULL && match->cp_number == -1;
3564 match = match->cp_next)
3565 match->cp_number = ++number;
3566 }
3567 else // BACKWARD
3568 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003569 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003570 // number. This should normally succeed already at the
3571 // first loop cycle, so it's fast!
3572 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003573 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003574 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003575 if (match->cp_number != -1)
3576 {
3577 number = match->cp_number;
3578 break;
3579 }
glepnir40891ba2025-02-10 22:18:00 +01003580 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003581 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003582 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003583 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003584 for (match = match->cp_prev; match
3585 && match->cp_number == -1;
3586 match = match->cp_prev)
3587 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003588 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003589 }
3590}
3591
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003592/*
glepnir037b0282025-01-16 14:37:44 +01003593 * Fill the dict of complete_info
3594 */
3595 static void
3596fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3597{
3598 dict_add_string(di, "word", match->cp_str.string);
3599 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3600 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3601 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3602 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3603 if (add_match)
3604 dict_add_bool(di, "match", match->cp_in_match_array);
3605 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3606 // Add an empty string for backwards compatibility
3607 dict_add_string(di, "user_data", (char_u *)"");
3608 else
3609 dict_add_tv(di, "user_data", &match->cp_user_data);
3610}
3611
3612/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003613 * Get complete information
3614 */
3615 static void
3616get_complete_info(list_T *what_list, dict_T *retdict)
3617{
3618 int ret = OK;
3619 listitem_T *item;
3620#define CI_WHAT_MODE 0x01
3621#define CI_WHAT_PUM_VISIBLE 0x02
3622#define CI_WHAT_ITEMS 0x04
3623#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003624#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003625#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003626#define CI_WHAT_ALL 0xff
3627 int what_flag;
3628
3629 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003630 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003631 else
3632 {
3633 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003634 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003635 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003636 {
3637 char_u *what = tv_get_string(&item->li_tv);
3638
3639 if (STRCMP(what, "mode") == 0)
3640 what_flag |= CI_WHAT_MODE;
3641 else if (STRCMP(what, "pum_visible") == 0)
3642 what_flag |= CI_WHAT_PUM_VISIBLE;
3643 else if (STRCMP(what, "items") == 0)
3644 what_flag |= CI_WHAT_ITEMS;
3645 else if (STRCMP(what, "selected") == 0)
3646 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003647 else if (STRCMP(what, "completed") == 0)
3648 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003649 else if (STRCMP(what, "matches") == 0)
3650 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003651 }
3652 }
3653
3654 if (ret == OK && (what_flag & CI_WHAT_MODE))
3655 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3656
3657 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3658 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3659
glepnir037b0282025-01-16 14:37:44 +01003660 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3661 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003662 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003663 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003664 dict_T *di;
3665 compl_T *match;
3666 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003667 int has_items = what_flag & CI_WHAT_ITEMS;
3668 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003669 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003670
glepnird4088ed2024-12-31 10:55:22 +01003671 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003672 {
3673 li = list_alloc();
3674 if (li == NULL)
3675 return;
glepnird4088ed2024-12-31 10:55:22 +01003676 ret = dict_add_list(retdict, (has_matches && !has_items)
3677 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003678 }
3679 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3680 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3681 ins_compl_update_sequence_numbers();
3682 if (ret == OK && compl_first_match != NULL)
3683 {
3684 int list_idx = 0;
3685 match = compl_first_match;
3686 do
3687 {
3688 if (!match_at_original_text(match))
3689 {
glepnird4088ed2024-12-31 10:55:22 +01003690 if (has_items
3691 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003692 {
3693 di = dict_alloc();
3694 if (di == NULL)
3695 return;
3696 ret = list_append_dict(li, di);
3697 if (ret != OK)
3698 return;
glepnir037b0282025-01-16 14:37:44 +01003699 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003700 }
glepnird4088ed2024-12-31 10:55:22 +01003701 if (compl_curr_match != NULL
3702 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003703 selected_idx = list_idx;
3704 list_idx += 1;
3705 }
3706 match = match->cp_next;
3707 }
3708 while (match != NULL && !is_first_match(match));
3709 }
3710 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3711 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003712
glepnir037b0282025-01-16 14:37:44 +01003713 if (ret == OK && selected_idx != -1 && has_completed)
3714 {
3715 di = dict_alloc();
3716 if (di == NULL)
3717 return;
3718 fill_complete_info_dict(di, compl_curr_match, FALSE);
3719 ret = dict_add_dict(retdict, "completed", di);
3720 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003721 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003722}
3723
3724/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003725 * "complete_info()" function
3726 */
3727 void
3728f_complete_info(typval_T *argvars, typval_T *rettv)
3729{
3730 list_T *what_list = NULL;
3731
Bram Moolenaar93a10962022-06-16 11:42:09 +01003732 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003733 return;
3734
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003735 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3736 return;
3737
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003738 if (argvars[0].v_type != VAR_UNKNOWN)
3739 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003740 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003741 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003742 what_list = argvars[0].vval.v_list;
3743 }
3744 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003745}
3746#endif
3747
3748/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003749 * Returns TRUE when using a user-defined function for thesaurus completion.
3750 */
3751 static int
3752thesaurus_func_complete(int type UNUSED)
3753{
3754#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003755 return type == CTRL_X_THESAURUS
3756 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003757#else
3758 return FALSE;
3759#endif
3760}
3761
3762/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003763 * Return value of process_next_cpt_value()
3764 */
3765enum
3766{
3767 INS_COMPL_CPT_OK = 1,
3768 INS_COMPL_CPT_CONT,
3769 INS_COMPL_CPT_END
3770};
3771
3772/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003773 * state information used for getting the next set of insert completion
3774 * matches.
3775 */
3776typedef struct
3777{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003778 char_u *e_cpt_copy; // copy of 'complete'
3779 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003780 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003781 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003782 pos_T prev_match_pos; // previous match position
3783 int set_match_pos; // save first_match_pos/last_match_pos
3784 pos_T first_match_pos; // first match position
3785 pos_T last_match_pos; // last match position
3786 int found_all; // found all matches of a certain type.
3787 char_u *dict; // dictionary file to search
3788 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003789 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003790} ins_compl_next_state_T;
3791
3792/*
3793 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003794 *
3795 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003796 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003797 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003798 * st->found_all - all matches of this type are found
3799 * st->ins_buf - search for completions in this buffer
3800 * st->first_match_pos - position of the first completion match
3801 * st->last_match_pos - position of the last completion match
3802 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003803 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003804 * st->dict - name of the dictionary or thesaurus file to search
3805 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003806 *
3807 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003808 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3809 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003810 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003811 */
3812 static int
3813process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003814 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003815 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003816 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003817 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003818{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003819 int compl_type = -1;
3820 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003821
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003822 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003823
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003824 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3825 st->e_cpt++;
3826
3827 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003828 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003829 st->ins_buf = curbuf;
3830 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003831 // Move the cursor back one character so that ^N can match the
3832 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003833 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003834 {
3835 // Move the cursor to after the last character in the
3836 // buffer, so that word at start of buffer is found
3837 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003838 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003839 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003840 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003841 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003842 compl_type = 0;
3843
3844 // Remember the first match so that the loop stops when we
3845 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003846 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003847 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003848 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003849 && (st->ins_buf = ins_compl_next_buf(
3850 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003851 {
3852 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003853 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003854 {
3855 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003856 st->first_match_pos.col = st->last_match_pos.col = 0;
3857 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3858 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003859 compl_type = 0;
3860 }
3861 else // unloaded buffer, scan like dictionary
3862 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003863 st->found_all = TRUE;
3864 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003865 {
3866 status = INS_COMPL_CPT_CONT;
3867 goto done;
3868 }
3869 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003870 st->dict = st->ins_buf->b_fname;
3871 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003872 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003873 if (!shortmess(SHM_COMPLETIONSCAN))
3874 {
3875 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3876 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3877 st->ins_buf->b_fname == NULL
3878 ? buf_spname(st->ins_buf)
3879 : st->ins_buf->b_sfname == NULL
3880 ? st->ins_buf->b_fname
3881 : st->ins_buf->b_sfname);
3882 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3883 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003884 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003885 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003886 status = INS_COMPL_CPT_END;
3887 else
3888 {
3889 if (ctrl_x_mode_line_or_eval())
3890 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003891 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003892 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003893 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003894 compl_type = CTRL_X_DICTIONARY;
3895 else
3896 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003897 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003898 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003899 st->dict = st->e_cpt;
3900 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003901 }
3902 }
Girish Palyacbe53192025-04-14 22:13:15 +02003903#ifdef FEAT_COMPL_FUNC
3904 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
3905 {
3906 compl_type = CTRL_X_FUNCTION;
3907 if (*st->e_cpt == 'o')
3908 st->func_cb = &curbuf->b_ofu_cb;
3909 else
3910 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
3911 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
3912 if (!st->func_cb)
3913 compl_type = -1;
3914 }
3915#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003916#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003917 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003918 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003919 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003920 compl_type = CTRL_X_PATH_DEFINES;
3921#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003922 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003923 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003924 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003925 if (!shortmess(SHM_COMPLETIONSCAN))
3926 {
3927 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3928 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3929 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3930 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003931 }
3932 else
3933 compl_type = -1;
3934
3935 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003936 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003937
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003938 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003939 if (compl_type == -1)
3940 status = INS_COMPL_CPT_CONT;
3941 }
3942
3943done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003944 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003945 return status;
3946}
3947
3948#ifdef FEAT_FIND_ID
3949/*
3950 * Get the next set of identifiers or defines matching "compl_pattern" in
3951 * included files.
3952 */
3953 static void
3954get_next_include_file_completion(int compl_type)
3955{
John Marriott5e6ea922024-11-23 14:01:57 +01003956 find_pattern_in_path(compl_pattern.string, compl_direction,
3957 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003958 (compl_type == CTRL_X_PATH_DEFINES
3959 && !(compl_cont_status & CONT_SOL))
3960 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003961 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003962}
3963#endif
3964
3965/*
3966 * Get the next set of words matching "compl_pattern" in dictionary or
3967 * thesaurus files.
3968 */
3969 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003970get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003971{
3972#ifdef FEAT_COMPL_FUNC
3973 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02003974 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003975 else
3976#endif
3977 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003978 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003979 : (compl_type == CTRL_X_THESAURUS
3980 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3981 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003982 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003983 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003984 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003985}
3986
3987/*
3988 * Get the next set of tag names matching "compl_pattern".
3989 */
3990 static void
3991get_next_tag_completion(void)
3992{
3993 int save_p_ic;
3994 char_u **matches;
3995 int num_matches;
3996
3997 // set p_ic according to p_ic, p_scs and pat for find_tags().
3998 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003999 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004000
4001 // Find up to TAG_MANY matches. Avoids that an enormous number
4002 // of matches is found when compl_pattern is empty
4003 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004004 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004005 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004006 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004007 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4008 ins_compl_add_matches(num_matches, matches, p_ic);
4009 g_tag_at_cursor = FALSE;
4010 p_ic = save_p_ic;
4011}
4012
4013/*
glepnir8159fb12024-07-17 20:32:54 +02004014 * Compare function for qsort
4015 */
glepnirf31cfa22025-03-06 21:59:13 +01004016 static int
4017compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004018{
4019 int idx_a = *(const int *)a;
4020 int idx_b = *(const int *)b;
4021 int score_a = compl_fuzzy_scores[idx_a];
4022 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004023 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4024 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004025}
4026
4027/*
glepnirf31cfa22025-03-06 21:59:13 +01004028 * insert prefix with redraw
4029 */
4030 static void
4031ins_compl_longest_insert(char_u *prefix)
4032{
4033 ins_compl_delete();
4034 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4035 ins_redraw(FALSE);
4036}
4037
4038/*
4039 * Calculate the longest common prefix among the best fuzzy matches
4040 * stored in compl_best_matches, and insert it as the longest.
4041 */
4042 static void
4043fuzzy_longest_match(void)
4044{
4045 char_u *prefix = NULL;
4046 int prefix_len = 0;
4047 int i = 0;
4048 int j = 0;
4049 char_u *match_str = NULL;
4050 char_u *prefix_ptr = NULL;
4051 char_u *match_ptr = NULL;
4052 char_u *leader = NULL;
4053 size_t leader_len = 0;
4054 compl_T *compl = NULL;
4055 int more_candidates = FALSE;
4056 compl_T *nn_compl = NULL;
4057
4058 if (compl_num_bests == 0)
4059 return;
4060
4061 nn_compl = compl_first_match->cp_next->cp_next;
4062 if (nn_compl && nn_compl != compl_first_match)
4063 more_candidates = TRUE;
4064
4065 compl = ctrl_x_mode_whole_line() ? compl_first_match
4066 : compl_first_match->cp_next;
4067 if (compl_num_bests == 1)
4068 {
4069 // no more candidates insert the match str
4070 if (!more_candidates)
4071 {
4072 ins_compl_longest_insert(compl->cp_str.string);
4073 compl_num_bests = 0;
4074 }
4075 compl_num_bests = 0;
4076 return;
4077 }
4078
4079 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4080 if (compl_best_matches == NULL)
4081 return;
4082 while (compl != NULL && i < compl_num_bests)
4083 {
4084 compl_best_matches[i] = compl;
4085 compl = compl->cp_next;
4086 i++;
4087 }
4088
4089 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004090 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004091
4092 for (i = 1; i < compl_num_bests; i++)
4093 {
4094 match_str = compl_best_matches[i]->cp_str.string;
4095 prefix_ptr = prefix;
4096 match_ptr = match_str;
4097 j = 0;
4098
4099 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4100 {
4101 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4102 break;
4103
4104 MB_PTR_ADV(prefix_ptr);
4105 MB_PTR_ADV(match_ptr);
4106 j++;
4107 }
4108
4109 if (j > 0)
4110 prefix_len = j;
4111 }
4112
4113 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004114 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004115
4116 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004117 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004118 goto end;
4119
zeertzjq4422de62025-03-07 19:06:02 +01004120 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004121 if (prefix != NULL)
4122 {
4123 ins_compl_longest_insert(prefix);
4124 compl_cfc_longest_ins = TRUE;
4125 vim_free(prefix);
4126 }
4127
4128end:
4129 vim_free(compl_best_matches);
4130 compl_best_matches = NULL;
4131 compl_num_bests = 0;
4132}
4133
4134/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004135 * Get the next set of filename matching "compl_pattern".
4136 */
4137 static void
4138get_next_filename_completion(void)
4139{
4140 char_u **matches;
4141 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004142 char_u *ptr;
4143 garray_T fuzzy_indices;
4144 int i;
4145 int score;
4146 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004147 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004148 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004149 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004150 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004151 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4152 int max_score = 0;
4153 int current_score = 0;
4154 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004155
glepnirb9de1a02024-08-02 19:14:38 +02004156#ifdef BACKSLASH_IN_FILENAME
4157 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4158 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4159#else
4160 char pathsep = PATHSEP;
4161#endif
4162
glepnirf31cfa22025-03-06 21:59:13 +01004163 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004164 {
glepnirb9de1a02024-08-02 19:14:38 +02004165#ifdef BACKSLASH_IN_FILENAME
4166 if (curbuf->b_p_csl[0] == 's')
4167 {
John Marriott5e6ea922024-11-23 14:01:57 +01004168 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004169 {
4170 if (leader[i] == '\\')
4171 leader[i] = '/';
4172 }
4173 }
4174 else if (curbuf->b_p_csl[0] == 'b')
4175 {
John Marriott5e6ea922024-11-23 14:01:57 +01004176 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004177 {
4178 if (leader[i] == '/')
4179 leader[i] = '\\';
4180 }
4181 }
4182#endif
4183 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004184 if (last_sep == NULL)
4185 {
4186 // No path separator or separator is the last character,
4187 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004188 VIM_CLEAR_STRING(compl_pattern);
4189 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4190 if (compl_pattern.string == NULL)
4191 return;
4192 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004193 }
4194 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004195 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004196 else
4197 {
4198 // Split leader into path and file parts
4199 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004200 char_u *path_with_wildcard;
4201
4202 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004203 if (path_with_wildcard != NULL)
4204 {
John Marriott5e6ea922024-11-23 14:01:57 +01004205 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4206 VIM_CLEAR_STRING(compl_pattern);
4207 compl_pattern.string = path_with_wildcard;
4208 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004209
4210 // Move leader to the file part
4211 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004212 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004213 }
4214 }
glepnir8159fb12024-07-17 20:32:54 +02004215 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004216
John Marriott5e6ea922024-11-23 14:01:57 +01004217 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004218 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4219 return;
4220
4221 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004222 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004223#ifdef BACKSLASH_IN_FILENAME
4224 if (curbuf->b_p_csl[0] != NUL)
4225 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004226 for (i = 0; i < num_matches; ++i)
4227 {
glepnir8159fb12024-07-17 20:32:54 +02004228 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004229 while (*ptr != NUL)
4230 {
4231 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4232 *ptr = '/';
4233 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4234 *ptr = '\\';
4235 ptr += (*mb_ptr2len)(ptr);
4236 }
4237 }
4238 }
4239#endif
glepnir8159fb12024-07-17 20:32:54 +02004240
glepnirf31cfa22025-03-06 21:59:13 +01004241 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004242 {
4243 ga_init2(&fuzzy_indices, sizeof(int), 10);
4244 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4245
4246 for (i = 0; i < num_matches; i++)
4247 {
4248 ptr = matches[i];
4249 score = fuzzy_match_str(ptr, leader);
4250 if (score > 0)
4251 {
4252 if (ga_grow(&fuzzy_indices, 1) == OK)
4253 {
4254 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4255 compl_fuzzy_scores[i] = score;
4256 fuzzy_indices.ga_len++;
4257 }
4258 }
4259 }
4260
Christian Brabandt220474d2024-07-20 13:26:44 +02004261 // prevent qsort from deref NULL pointer
4262 if (fuzzy_indices.ga_len > 0)
4263 {
glepnirf31cfa22025-03-06 21:59:13 +01004264 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004265 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4266 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004267
Christian Brabandt220474d2024-07-20 13:26:44 +02004268 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004269 {
4270 match = matches[fuzzy_indices_data[i]];
4271 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4272 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
4273 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4274 FALSE, NULL, current_score) == OK)
4275 dir = FORWARD;
4276
4277 if (need_collect_bests)
4278 {
4279 if (i == 0 || current_score == max_score)
4280 {
4281 compl_num_bests++;
4282 max_score = current_score;
4283 }
4284 }
4285 }
glepnir8159fb12024-07-17 20:32:54 +02004286
Christian Brabandt220474d2024-07-20 13:26:44 +02004287 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004288 }
glepnir6b6280c2024-07-27 16:25:45 +02004289 else if (leader_len > 0)
4290 {
4291 FreeWild(num_matches, matches);
4292 num_matches = 0;
4293 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004294
glepnir8159fb12024-07-17 20:32:54 +02004295 vim_free(compl_fuzzy_scores);
4296 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004297
4298 if (compl_num_bests > 0 && compl_get_longest)
4299 fuzzy_longest_match();
4300 return;
glepnir8159fb12024-07-17 20:32:54 +02004301 }
4302
glepnir6b6280c2024-07-27 16:25:45 +02004303 if (num_matches > 0)
4304 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004305}
4306
4307/*
4308 * Get the next set of command-line completions matching "compl_pattern".
4309 */
4310 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004311get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004312{
4313 char_u **matches;
4314 int num_matches;
4315
John Marriott5e6ea922024-11-23 14:01:57 +01004316 if (expand_cmdline(&compl_xp, compl_pattern.string,
4317 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004318 ins_compl_add_matches(num_matches, matches, FALSE);
4319}
4320
4321/*
4322 * Get the next set of spell suggestions matching "compl_pattern".
4323 */
4324 static void
4325get_next_spell_completion(linenr_T lnum UNUSED)
4326{
4327#ifdef FEAT_SPELL
4328 char_u **matches;
4329 int num_matches;
4330
John Marriott5e6ea922024-11-23 14:01:57 +01004331 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004332 if (num_matches > 0)
4333 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004334 else
4335 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004336#endif
4337}
4338
4339/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004340 * Return the next word or line from buffer "ins_buf" at position
4341 * "cur_match_pos" for completion. The length of the match is set in "len".
4342 */
4343 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004344ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004345 buf_T *ins_buf, // buffer being scanned
4346 pos_T *cur_match_pos, // current match position
4347 int *match_len,
4348 int *cont_s_ipos) // next ^X<> will set initial_pos
4349{
4350 char_u *ptr;
4351 int len;
4352
4353 *match_len = 0;
4354 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4355 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004356 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004357 if (ctrl_x_mode_line_or_eval())
4358 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004359 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004360 {
4361 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4362 return NULL;
4363 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004364 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004365 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004366 {
4367 char_u *tmp_ptr = ptr;
4368
4369 ptr = skipwhite(tmp_ptr);
4370 len -= (int)(ptr - tmp_ptr);
4371 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004372 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004373 }
4374 else
4375 {
4376 char_u *tmp_ptr = ptr;
4377
John Marriott5e6ea922024-11-23 14:01:57 +01004378 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004379 {
4380 tmp_ptr += compl_length;
4381 // Skip if already inside a word.
4382 if (vim_iswordp(tmp_ptr))
4383 return NULL;
4384 // Find start of next word.
4385 tmp_ptr = find_word_start(tmp_ptr);
4386 }
4387 // Find end of this word.
4388 tmp_ptr = find_word_end(tmp_ptr);
4389 len = (int)(tmp_ptr - ptr);
4390
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004391 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004392 {
4393 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4394 {
4395 // Try next line, if any. the new word will be
4396 // "join" as if the normal command "J" was used.
4397 // IOSIZE is always greater than
4398 // compl_length, so the next STRNCPY always
4399 // works -- Acevedo
4400 STRNCPY(IObuff, ptr, len);
4401 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4402 tmp_ptr = ptr = skipwhite(ptr);
4403 // Find start of next word.
4404 tmp_ptr = find_word_start(tmp_ptr);
4405 // Find end of next word.
4406 tmp_ptr = find_word_end(tmp_ptr);
4407 if (tmp_ptr > ptr)
4408 {
4409 if (*ptr != ')' && IObuff[len - 1] != TAB)
4410 {
4411 if (IObuff[len - 1] != ' ')
4412 IObuff[len++] = ' ';
4413 // IObuf =~ "\k.* ", thus len >= 2
4414 if (p_js
4415 && (IObuff[len - 2] == '.'
4416 || (vim_strchr(p_cpo, CPO_JOINSP)
4417 == NULL
4418 && (IObuff[len - 2] == '?'
4419 || IObuff[len - 2] == '!'))))
4420 IObuff[len++] = ' ';
4421 }
4422 // copy as much as possible of the new word
4423 if (tmp_ptr - ptr >= IOSIZE - len)
4424 tmp_ptr = ptr + IOSIZE - len - 1;
4425 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4426 len += (int)(tmp_ptr - ptr);
4427 *cont_s_ipos = TRUE;
4428 }
4429 IObuff[len] = NUL;
4430 ptr = IObuff;
4431 }
4432 if (len == compl_length)
4433 return NULL;
4434 }
4435 }
4436
4437 *match_len = len;
4438 return ptr;
4439}
4440
4441/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004442 * Get the next set of words matching "compl_pattern" for default completion(s)
4443 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004444 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4445 * position "st->start_pos" in the "compl_direction" direction. If
4446 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4447 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004448 * Returns OK if a new next match is found, otherwise returns FAIL.
4449 */
4450 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004451get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004452{
4453 int found_new_match = FAIL;
4454 int save_p_scs;
4455 int save_p_ws;
4456 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004457 char_u *ptr = NULL;
4458 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004459 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004460 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004461 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004462 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004463
4464 // If 'infercase' is set, don't use 'smartcase' here
4465 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004466 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004467 p_scs = FALSE;
4468
4469 // Buffers other than curbuf are scanned from the beginning or the
4470 // end but never from the middle, thus setting nowrapscan in this
4471 // buffer is a good idea, on the other hand, we always set
4472 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4473 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004474 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004475 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004476 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004477 p_ws = TRUE;
4478 looped_around = FALSE;
4479 for (;;)
4480 {
4481 int cont_s_ipos = FALSE;
4482
4483 ++msg_silent; // Don't want messages for wrapscan.
4484
glepnirf31cfa22025-03-06 21:59:13 +01004485 if (in_collect)
4486 {
glepnir8159fb12024-07-17 20:32:54 +02004487 found_new_match = search_for_fuzzy_match(st->ins_buf,
4488 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004489 start_pos, &len, &ptr, &score);
4490 }
4491 // ctrl_x_mode_line_or_eval() || word-wise search that
4492 // has added a word that was at the beginning of the line
4493 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4494 found_new_match = search_for_exact_line(st->ins_buf,
4495 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004496 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004497 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004498 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004499 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004500 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004501 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004502 {
4503 // set "compl_started" even on fail
4504 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004505 st->first_match_pos = *st->cur_match_pos;
4506 st->last_match_pos = *st->cur_match_pos;
4507 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004508 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004509 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4510 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004511 {
4512 found_new_match = FAIL;
4513 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004514 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004515 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4516 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4517 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004518 {
4519 if (looped_around)
4520 found_new_match = FAIL;
4521 else
4522 looped_around = TRUE;
4523 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004524 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004525 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4526 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4527 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004528 {
4529 if (looped_around)
4530 found_new_match = FAIL;
4531 else
4532 looped_around = TRUE;
4533 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004534 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004535 if (found_new_match == FAIL)
4536 break;
4537
4538 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004539 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004540 && start_pos->lnum == st->cur_match_pos->lnum
4541 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004542 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004543
glepnirf31cfa22025-03-06 21:59:13 +01004544 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004545 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4546 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004547 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004548 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004549
Girish Palyab1565882025-04-15 20:16:00 +02004550 if (is_nearest_active() && in_curbuf)
4551 {
4552 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4553 if (score < 0)
4554 score = -score;
4555 score++;
4556 }
4557
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004558 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004559 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004560 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004561 {
glepnirf31cfa22025-03-06 21:59:13 +01004562 if (in_collect && score == compl_first_match->cp_next->cp_score)
4563 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004564 found_new_match = OK;
4565 break;
4566 }
4567 }
4568 p_scs = save_p_scs;
4569 p_ws = save_p_ws;
4570
4571 return found_new_match;
4572}
4573
4574/*
Girish Palyacbe53192025-04-14 22:13:15 +02004575 * Return the callback function associated with "funcname".
4576 */
4577#ifdef FEAT_COMPL_FUNC
4578 static callback_T *
4579get_cpt_func_callback(char_u *funcname)
4580{
4581 static callback_T cb;
4582 char_u buf[LSIZE];
4583 int slen;
4584
4585 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4586 if (slen > 0 && option_set_callback_func(buf, &cb))
4587 return &cb;
4588 return NULL;
4589}
4590
4591/*
4592 * Retrieve new completion matches by invoking callback "cb".
4593 */
4594 static void
4595expand_cpt_function(callback_T *cb)
4596{
4597 // Re-insert the text removed by ins_compl_delete().
4598 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4599 // Get matches
4600 get_cpt_func_completion_matches(cb);
4601 // Undo insertion
4602 ins_compl_delete();
4603}
4604#endif
4605
4606/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004607 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004608 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004609 */
4610 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004611get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004612{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004613 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004614
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004615 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004616 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004617 case -1:
4618 break;
4619#ifdef FEAT_FIND_ID
4620 case CTRL_X_PATH_PATTERNS:
4621 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004622 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004623 break;
4624#endif
4625
4626 case CTRL_X_DICTIONARY:
4627 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004628 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4629 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004630 break;
4631
4632 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004633 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004634 break;
4635
4636 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004637 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004638 break;
4639
4640 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004641 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004642 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004643 break;
4644
4645#ifdef FEAT_COMPL_FUNC
4646 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004647 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4648 expand_cpt_function(st->func_cb);
4649 else
4650 expand_by_function(type, compl_pattern.string, NULL);
4651 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004652 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004653 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004654 break;
4655#endif
4656
4657 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004658 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004659 break;
4660
4661 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004662 found_new_match = get_next_default_completion(st, ini);
4663 if (found_new_match == FAIL && st->ins_buf == curbuf)
4664 st->found_all = TRUE;
4665 }
4666
4667 // check if compl_curr_match has changed, (e.g. other type of
4668 // expansion added something)
4669 if (type != 0 && compl_curr_match != compl_old_match)
4670 found_new_match = OK;
4671
4672 return found_new_match;
4673}
4674
4675/*
4676 * Get the next expansion(s), using "compl_pattern".
4677 * The search starts at position "ini" in curbuf and in the direction
4678 * compl_direction.
4679 * When "compl_started" is FALSE start at that position, otherwise continue
4680 * where we stopped searching before.
4681 * This may return before finding all the matches.
4682 * Return the total number of matches or -1 if still unknown -- Acevedo
4683 */
4684 static int
4685ins_compl_get_exp(pos_T *ini)
4686{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004687 static ins_compl_next_state_T st;
4688 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004689 int i;
4690 int found_new_match;
4691 int type = ctrl_x_mode;
4692
4693 if (!compl_started)
4694 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004695 buf_T *buf;
4696
4697 FOR_ALL_BUFFERS(buf)
4698 buf->b_scanned = 0;
4699 if (!st_cleared)
4700 {
4701 CLEAR_FIELD(st);
4702 st_cleared = TRUE;
4703 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004704 st.found_all = FALSE;
4705 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004706 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004707 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004708 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4709 ? (char_u *)"." : curbuf->b_p_cpt);
4710 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004711 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004712
4713 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
4714 && !cpt_compl_src_init(st.e_cpt))
4715 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004716 }
4717 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4718 st.ins_buf = curbuf; // In case the buffer was wiped out.
4719
4720 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004721 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004722 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004723
4724 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palyacbe53192025-04-14 22:13:15 +02004725 for (cpt_value_idx = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004726 {
4727 found_new_match = FAIL;
4728 st.set_match_pos = FALSE;
4729
4730 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4731 // or if found_all says this entry is done. For ^X^L only use the
4732 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004733 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004734 && (!compl_started || st.found_all))
4735 {
glepnir53b14572025-03-12 21:28:39 +01004736 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004737
4738 if (status == INS_COMPL_CPT_END)
4739 break;
4740 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004741 {
4742 cpt_value_idx++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004743 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004744 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004745 }
4746
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004747 // If complete() was called then compl_pattern has been reset. The
4748 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004749 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004750 break;
4751
4752 // get the next set of completion matches
4753 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004754
Girish Palyacbe53192025-04-14 22:13:15 +02004755 if (type > 0)
4756 cpt_value_idx++;
4757
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004758 // break the loop for specialized modes (use 'complete' just for the
4759 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4760 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004761 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4762 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004763 {
4764 if (got_int)
4765 break;
4766 // Fill the popup menu as soon as possible.
4767 if (type != -1)
4768 ins_compl_check_keys(0, FALSE);
4769
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004770 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004771 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4772 break;
4773 compl_started = TRUE;
4774 }
4775 else
4776 {
4777 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004778 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004779 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004780
4781 compl_started = FALSE;
4782 }
4783 }
Girish Palyacbe53192025-04-14 22:13:15 +02004784 cpt_value_idx = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004785 compl_started = TRUE;
4786
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004787 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004788 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004789 found_new_match = FAIL;
4790
4791 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004792 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004793 && !ctrl_x_mode_line_or_eval()))
4794 i = ins_compl_make_cyclic();
4795
glepnirf31cfa22025-03-06 21:59:13 +01004796 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4797 fuzzy_longest_match();
4798
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004799 if (compl_old_match != NULL)
4800 {
4801 // If several matches were added (FORWARD) or the search failed and has
4802 // just been made cyclic then we have to move compl_curr_match to the
4803 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004804 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004805 : compl_old_match->cp_prev;
4806 if (compl_curr_match == NULL)
4807 compl_curr_match = compl_old_match;
4808 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004809 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004810
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004811 return i;
4812}
4813
4814/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004815 * Update "compl_shown_match" to the actually shown match, it may differ when
4816 * "compl_leader" is used to omit some of the matches.
4817 */
4818 static void
4819ins_compl_update_shown_match(void)
4820{
4821 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004822 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004823 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004824 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004825 compl_shown_match = compl_shown_match->cp_next;
4826
4827 // If we didn't find it searching forward, and compl_shows_dir is
4828 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004829 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004830 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004831 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004832 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004833 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004834 {
4835 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004836 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004837 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004838 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004839 compl_shown_match = compl_shown_match->cp_prev;
4840 }
4841}
4842
4843/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004844 * Delete the old text being completed.
4845 */
4846 void
4847ins_compl_delete(void)
4848{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004849 // In insert mode: Delete the typed part.
4850 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004851 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01004852 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01004853 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004854 int has_preinsert = ins_compl_preinsert_effect();
4855 if (has_preinsert)
4856 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02004857 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004858 curwin->w_cursor.col = compl_ins_end_col;
4859 }
4860
glepnir76bdb822025-02-08 19:04:51 +01004861 if (curwin->w_cursor.lnum > compl_lnum)
4862 {
4863 if (curwin->w_cursor.col < ml_get_curline_len())
4864 {
John Marriottf4b36412025-02-23 09:09:59 +01004865 char_u *line = ml_get_cursor();
4866 remaining.length = ml_get_cursor_len();
4867 remaining.string = vim_strnsave(line, remaining.length);
4868 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01004869 return;
4870 }
4871 while (curwin->w_cursor.lnum > compl_lnum)
4872 {
4873 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4874 {
John Marriottf4b36412025-02-23 09:09:59 +01004875 if (remaining.string)
4876 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004877 return;
4878 }
zeertzjq060e6552025-02-21 20:06:26 +01004879 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01004880 curwin->w_cursor.lnum--;
4881 }
4882 // move cursor to end of line
4883 curwin->w_cursor.col = ml_get_curline_len();
4884 }
4885
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004886 if ((int)curwin->w_cursor.col > col)
4887 {
4888 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004889 {
John Marriottf4b36412025-02-23 09:09:59 +01004890 if (remaining.string)
4891 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004892 return;
glepnire3647c82025-02-10 21:16:32 +01004893 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004894 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004895 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004896 }
4897
John Marriottf4b36412025-02-23 09:09:59 +01004898 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01004899 {
4900 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01004901 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01004902 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01004903 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004904 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004905 // TODO: is this sufficient for redrawing? Redrawing everything causes
4906 // flicker, thus we can't do that.
4907 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004908#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004909 // clear v:completed_item
4910 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004911#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004912}
4913
4914/*
glepnir76bdb822025-02-08 19:04:51 +01004915 * Insert a completion string that contains newlines.
4916 * The string is split and inserted line by line.
4917 */
4918 static void
4919ins_compl_expand_multiple(char_u *str)
4920{
4921 char_u *start = str;
4922 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01004923 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01004924
4925 while (*curr != NUL)
4926 {
4927 if (*curr == '\n')
4928 {
4929 // Insert the text chunk before newline
4930 if (curr > start)
4931 ins_char_bytes(start, (int)(curr - start));
4932
4933 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01004934 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01004935 start = curr + 1;
4936 }
4937 curr++;
4938 }
4939
4940 // Handle remaining text after last newline (if any)
4941 if (curr > start)
4942 ins_char_bytes(start, (int)(curr - start));
4943
4944 compl_ins_end_col = curwin->w_cursor.col;
4945}
4946
4947/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004948 * Insert the new text being completed.
4949 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004950 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4951 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004952 */
4953 void
glepniredd4ac32025-01-29 18:53:51 +01004954ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004955{
glepnir76bdb822025-02-08 19:04:51 +01004956 int compl_len = get_compl_len();
4957 int preinsert = ins_compl_has_preinsert();
4958 char_u *cp_str = compl_shown_match->cp_str.string;
4959 size_t cp_str_len = compl_shown_match->cp_str.length;
4960 size_t leader_len = ins_compl_leader_len();
4961 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004962
4963 // Make sure we don't go over the end of the string, this can happen with
4964 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004965 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004966 {
glepnir76bdb822025-02-08 19:04:51 +01004967 if (has_multiple)
4968 ins_compl_expand_multiple(cp_str + compl_len);
4969 else
4970 {
4971 ins_compl_insert_bytes(cp_str + compl_len, -1);
4972 if (preinsert && move_cursor)
4973 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4974 }
glepniredd4ac32025-01-29 18:53:51 +01004975 }
4976 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004977 compl_used_match = FALSE;
4978 else
4979 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004980#ifdef FEAT_EVAL
4981 {
4982 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4983
4984 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4985 }
4986#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004987 if (!in_compl_func)
4988 compl_curr_match = compl_shown_match;
4989}
4990
4991/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004992 * show the file name for the completion match (if any). Truncate the file
4993 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004994 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004995 static void
4996ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004997{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004998 char *lead = _("match in file");
4999 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5000 char_u *s;
5001 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005002
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005003 if (space <= 0)
5004 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005005
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005006 // We need the tail that fits. With double-byte encoding going
5007 // back from the end is very slow, thus go from the start and keep
5008 // the text that fits in "space" between "s" and "e".
5009 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005010 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005011 space -= ptr2cells(e);
5012 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005013 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005014 space += ptr2cells(s);
5015 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005016 }
5017 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005018 msg_hist_off = TRUE;
5019 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5020 s > compl_shown_match->cp_fname ? "<" : "", s);
5021 msg((char *)IObuff);
5022 msg_hist_off = FALSE;
5023 redraw_cmdline = FALSE; // don't overwrite!
5024}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005025
glepnirdca57fb2024-06-04 22:01:21 +02005026/*
zeertzjq551d8c32024-06-05 19:53:32 +02005027 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02005028 */
glepnira218cc62024-06-03 19:32:39 +02005029 static compl_T *
5030find_comp_when_fuzzy(void)
5031{
5032 int score;
5033 char_u* str;
5034 int target_idx = -1;
5035 int is_forward = compl_shows_dir_forward();
5036 int is_backward = compl_shows_dir_backward();
5037 compl_T *comp = NULL;
5038
glepnir43eef882024-06-19 20:20:48 +02005039 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02005040 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02005041 return compl_first_match != compl_shown_match ?
5042 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02005043 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02005044
5045 if (is_forward)
5046 target_idx = compl_selected_item + 1;
5047 else if (is_backward)
5048 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02005049 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02005050
5051 score = compl_match_array[target_idx].pum_score;
5052 str = compl_match_array[target_idx].pum_text;
5053
5054 comp = compl_first_match;
5055 do {
John Marriott5e6ea922024-11-23 14:01:57 +01005056 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02005057 return comp;
5058 comp = comp->cp_next;
5059 } while (comp != NULL && !is_first_match(comp));
5060
5061 return NULL;
5062}
5063
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005064/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005065 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005066 * times. The number of matches found is returned in 'num_matches'.
5067 *
5068 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5069 * get more completions. If it is FALSE, then do nothing when there are no more
5070 * completions in the given direction.
5071 *
5072 * If "advance" is TRUE, then completion will move to the first match.
5073 * Otherwise, the original text will be shown.
5074 *
5075 * Returns OK on success and -1 if the number of matches are unknown.
5076 */
5077 static int
5078find_next_completion_match(
5079 int allow_get_expansion,
5080 int todo, // repeat completion this many times
5081 int advance,
5082 int *num_matches)
5083{
5084 int found_end = FALSE;
5085 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005086 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005087 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5088 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005089
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005090 while (--todo >= 0)
5091 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005092 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005093 {
glepniraced8c22024-06-15 15:13:05 +02005094 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
5095 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005096 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005097 && (is_first_match(compl_shown_match->cp_next)
5098 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005099 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005100 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005101 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005102 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005103 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02005104 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
5105 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005106 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005107 }
5108 else
5109 {
5110 if (!allow_get_expansion)
5111 {
5112 if (advance)
5113 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005114 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005115 compl_pending -= todo + 1;
5116 else
5117 compl_pending += todo + 1;
5118 }
5119 return -1;
5120 }
5121
5122 if (!compl_no_select && advance)
5123 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005124 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005125 --compl_pending;
5126 else
5127 ++compl_pending;
5128 }
5129
5130 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005131 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005132
5133 // handle any pending completions
5134 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005135 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005136 {
5137 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5138 {
5139 compl_shown_match = compl_shown_match->cp_next;
5140 --compl_pending;
5141 }
5142 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5143 {
5144 compl_shown_match = compl_shown_match->cp_prev;
5145 ++compl_pending;
5146 }
5147 else
5148 break;
5149 }
5150 found_end = FALSE;
5151 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005152 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005153 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005154 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005155 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005156 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005157 ++todo;
5158 else
5159 // Remember a matching item.
5160 found_compl = compl_shown_match;
5161
5162 // Stop at the end of the list when we found a usable match.
5163 if (found_end)
5164 {
5165 if (found_compl != NULL)
5166 {
5167 compl_shown_match = found_compl;
5168 break;
5169 }
5170 todo = 1; // use first usable match after wrapping around
5171 }
5172 }
5173
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005174 return OK;
5175}
5176
5177/*
5178 * Fill in the next completion in the current direction.
5179 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5180 * get more completions. If it is FALSE, then we just do nothing when there
5181 * are no more completions in a given direction. The latter case is used when
5182 * we are still in the middle of finding completions, to allow browsing
5183 * through the ones found so far.
5184 * Return the total number of matches, or -1 if still unknown -- webb.
5185 *
5186 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5187 * compl_shown_match here.
5188 *
5189 * Note that this function may be called recursively once only. First with
5190 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5191 * calls this function with "allow_get_expansion" FALSE.
5192 */
5193 static int
5194ins_compl_next(
5195 int allow_get_expansion,
5196 int count, // repeat completion this many times; should
5197 // be at least 1
5198 int insert_match, // Insert the newly selected match
5199 int in_compl_func) // called from complete_check()
5200{
5201 int num_matches = -1;
5202 int todo = count;
5203 int advance;
5204 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005205 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005206 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005207 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5208 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005209 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005210
5211 // When user complete function return -1 for findstart which is next
5212 // time of 'always', compl_shown_match become NULL.
5213 if (compl_shown_match == NULL)
5214 return -1;
5215
John Marriott5e6ea922024-11-23 14:01:57 +01005216 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005217 && !match_at_original_text(compl_shown_match)
5218 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005219 // Update "compl_shown_match" to the actually shown match
5220 ins_compl_update_shown_match();
5221
5222 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005223 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005224 // Delete old text to be replaced
5225 ins_compl_delete();
5226
5227 // When finding the longest common text we stick at the original text,
5228 // don't let CTRL-N or CTRL-P move to the first match.
5229 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5230
5231 // When restarting the search don't insert the first match either.
5232 if (compl_restarting)
5233 {
5234 advance = FALSE;
5235 compl_restarting = FALSE;
5236 }
5237
5238 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5239 // around.
5240 if (find_next_completion_match(allow_get_expansion, todo, advance,
5241 &num_matches) == -1)
5242 return -1;
5243
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005244 if (curbuf != orig_curbuf)
5245 {
5246 // In case some completion function switched buffer, don't want to
5247 // insert the completion elsewhere.
5248 return -1;
5249 }
5250
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005251 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005252 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005253 {
glepnir6a38aff2024-12-16 21:56:16 +01005254 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005255 compl_used_match = FALSE;
5256 }
5257 else if (insert_match)
5258 {
5259 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005260 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005261 else
glepnir6a38aff2024-12-16 21:56:16 +01005262 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005263 }
5264 else
5265 compl_used_match = FALSE;
5266
5267 if (!allow_get_expansion)
5268 {
5269 // may undisplay the popup menu first
5270 ins_compl_upd_pum();
5271
5272 if (pum_enough_matches())
5273 // Will display the popup menu, don't redraw yet to avoid flicker.
5274 pum_call_update_screen();
5275 else
5276 // Not showing the popup menu yet, redraw to show the user what was
5277 // inserted.
5278 update_screen(0);
5279
5280 // display the updated popup menu
5281 ins_compl_show_pum();
5282#ifdef FEAT_GUI
5283 if (gui.in_use)
5284 {
5285 // Show the cursor after the match, not after the redrawn text.
5286 setcursor();
5287 out_flush_cursor(FALSE, FALSE);
5288 }
5289#endif
5290
5291 // Delete old text to be replaced, since we're still searching and
5292 // don't want to match ourselves!
5293 ins_compl_delete();
5294 }
5295
5296 // Enter will select a match when the match wasn't inserted and the popup
5297 // menu is visible.
5298 if (compl_no_insert && !started)
5299 compl_enter_selects = TRUE;
5300 else
5301 compl_enter_selects = !insert_match && compl_match_array != NULL;
5302
5303 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005304 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005305 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005306
5307 return num_matches;
5308}
5309
5310/*
5311 * Call this while finding completions, to check whether the user has hit a key
5312 * that should change the currently displayed completion, or exit completion
5313 * mode. Also, when compl_pending is not zero, show a completion as soon as
5314 * possible. -- webb
5315 * "frequency" specifies out of how many calls we actually check.
5316 * "in_compl_func" is TRUE when called from complete_check(), don't set
5317 * compl_curr_match.
5318 */
5319 void
5320ins_compl_check_keys(int frequency, int in_compl_func)
5321{
5322 static int count = 0;
5323 int c;
5324
5325 // Don't check when reading keys from a script, :normal or feedkeys().
5326 // That would break the test scripts. But do check for keys when called
5327 // from complete_check().
5328 if (!in_compl_func && (using_script() || ex_normal_busy))
5329 return;
5330
5331 // Only do this at regular intervals
5332 if (++count < frequency)
5333 return;
5334 count = 0;
5335
5336 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5337 // can't do its work correctly.
5338 c = vpeekc_any();
5339 if (c != NUL)
5340 {
5341 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5342 {
5343 c = safe_vgetc(); // Eat the character
5344 compl_shows_dir = ins_compl_key2dir(c);
5345 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5346 c != K_UP && c != K_DOWN, in_compl_func);
5347 }
5348 else
5349 {
5350 // Need to get the character to have KeyTyped set. We'll put it
5351 // back with vungetc() below. But skip K_IGNORE.
5352 c = safe_vgetc();
5353 if (c != K_IGNORE)
5354 {
5355 // Don't interrupt completion when the character wasn't typed,
5356 // e.g., when doing @q to replay keys.
5357 if (c != Ctrl_R && KeyTyped)
5358 compl_interrupted = TRUE;
5359
5360 vungetc(c);
5361 }
5362 }
5363 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005364 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005365 {
5366 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5367
5368 compl_pending = 0;
5369 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5370 }
5371}
5372
5373/*
5374 * Decide the direction of Insert mode complete from the key typed.
5375 * Returns BACKWARD or FORWARD.
5376 */
5377 static int
5378ins_compl_key2dir(int c)
5379{
5380 if (c == Ctrl_P || c == Ctrl_L
5381 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5382 return BACKWARD;
5383 return FORWARD;
5384}
5385
5386/*
5387 * Return TRUE for keys that are used for completion only when the popup menu
5388 * is visible.
5389 */
5390 static int
5391ins_compl_pum_key(int c)
5392{
5393 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5394 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5395 || c == K_UP || c == K_DOWN);
5396}
5397
5398/*
5399 * Decide the number of completions to move forward.
5400 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5401 */
5402 static int
5403ins_compl_key2count(int c)
5404{
5405 int h;
5406
5407 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5408 {
5409 h = pum_get_height();
5410 if (h > 3)
5411 h -= 2; // keep some context
5412 return h;
5413 }
5414 return 1;
5415}
5416
5417/*
5418 * Return TRUE if completion with "c" should insert the match, FALSE if only
5419 * to change the currently selected completion.
5420 */
5421 static int
5422ins_compl_use_match(int c)
5423{
5424 switch (c)
5425 {
5426 case K_UP:
5427 case K_DOWN:
5428 case K_PAGEDOWN:
5429 case K_KPAGEDOWN:
5430 case K_S_DOWN:
5431 case K_PAGEUP:
5432 case K_KPAGEUP:
5433 case K_S_UP:
5434 return FALSE;
5435 }
5436 return TRUE;
5437}
5438
5439/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005440 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5441 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005442 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005443 * Uses the global variables: compl_cont_status and ctrl_x_mode
5444 */
5445 static int
5446get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5447{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005448 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005449 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005450 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005451 {
5452 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5453 ;
5454 compl_col += ++startcol;
5455 compl_length = curs_col - startcol;
5456 }
5457 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005458 {
John Marriott5e6ea922024-11-23 14:01:57 +01005459 compl_pattern.string = str_foldcase(line + compl_col,
5460 compl_length, NULL, 0);
5461 if (compl_pattern.string == NULL)
5462 {
5463 compl_pattern.length = 0;
5464 return FAIL;
5465 }
5466 compl_pattern.length = STRLEN(compl_pattern.string);
5467 }
5468 else
5469 {
5470 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5471 if (compl_pattern.string == NULL)
5472 {
5473 compl_pattern.length = 0;
5474 return FAIL;
5475 }
5476 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005477 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005478 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005479 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005480 {
5481 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005482 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005483 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005484
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005485 if (!vim_iswordp(line + compl_col)
5486 || (compl_col > 0
5487 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005488 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005489 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005490 prefixlen = 0;
5491 }
John Marriott5e6ea922024-11-23 14:01:57 +01005492
5493 // we need up to 2 extra chars for the prefix
5494 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5495 compl_pattern.string = alloc(n);
5496 if (compl_pattern.string == NULL)
5497 {
5498 compl_pattern.length = 0;
5499 return FAIL;
5500 }
5501 STRCPY((char *)compl_pattern.string, prefix);
5502 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005503 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005504 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005505 }
5506 else if (--startcol < 0
5507 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5508 {
John Marriott5e6ea922024-11-23 14:01:57 +01005509 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5510
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005511 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005512 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5513 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005514 {
John Marriott5e6ea922024-11-23 14:01:57 +01005515 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005516 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005517 }
John Marriott5e6ea922024-11-23 14:01:57 +01005518 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005519 compl_col += curs_col;
5520 compl_length = 0;
5521 }
5522 else
5523 {
5524 // Search the point of change class of multibyte character
5525 // or not a word single byte character backward.
5526 if (has_mbyte)
5527 {
5528 int base_class;
5529 int head_off;
5530
5531 startcol -= (*mb_head_off)(line, line + startcol);
5532 base_class = mb_get_class(line + startcol);
5533 while (--startcol >= 0)
5534 {
5535 head_off = (*mb_head_off)(line, line + startcol);
5536 if (base_class != mb_get_class(line + startcol
5537 - head_off))
5538 break;
5539 startcol -= head_off;
5540 }
5541 }
5542 else
5543 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5544 ;
5545 compl_col += ++startcol;
5546 compl_length = (int)curs_col - startcol;
5547 if (compl_length == 1)
5548 {
5549 // Only match word with at least two chars -- webb
5550 // there's no need to call quote_meta,
5551 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005552 compl_pattern.string = alloc(7);
5553 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005554 {
John Marriott5e6ea922024-11-23 14:01:57 +01005555 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005556 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005557 }
John Marriott5e6ea922024-11-23 14:01:57 +01005558 STRCPY((char *)compl_pattern.string, "\\<");
5559 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5560 STRCAT((char *)compl_pattern.string, "\\k");
5561 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005562 }
5563 else
5564 {
John Marriott5e6ea922024-11-23 14:01:57 +01005565 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5566
5567 compl_pattern.string = alloc(n);
5568 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005569 {
John Marriott5e6ea922024-11-23 14:01:57 +01005570 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005571 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005572 }
John Marriott5e6ea922024-11-23 14:01:57 +01005573 STRCPY((char *)compl_pattern.string, "\\<");
5574 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005575 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005576 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005577 }
5578 }
5579
5580 return OK;
5581}
5582
5583/*
5584 * Get the pattern, column and length for whole line completion or for the
5585 * complete() function.
5586 * Sets the global variables: compl_col, compl_length and compl_pattern.
5587 */
5588 static int
5589get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5590{
5591 compl_col = (colnr_T)getwhitecols(line);
5592 compl_length = (int)curs_col - (int)compl_col;
5593 if (compl_length < 0) // cursor in indent: empty pattern
5594 compl_length = 0;
5595 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005596 {
John Marriott5e6ea922024-11-23 14:01:57 +01005597 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5598 NULL, 0);
5599 if (compl_pattern.string == NULL)
5600 {
5601 compl_pattern.length = 0;
5602 return FAIL;
5603 }
5604 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005605 }
John Marriott5e6ea922024-11-23 14:01:57 +01005606 else
5607 {
5608 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5609 if (compl_pattern.string == NULL)
5610 {
5611 compl_pattern.length = 0;
5612 return FAIL;
5613 }
5614 compl_pattern.length = (size_t)compl_length;
5615 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005616
5617 return OK;
5618}
5619
5620/*
5621 * Get the pattern, column and length for filename completion.
5622 * Sets the global variables: compl_col, compl_length and compl_pattern.
5623 */
5624 static int
5625get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5626{
5627 // Go back to just before the first filename character.
5628 if (startcol > 0)
5629 {
5630 char_u *p = line + startcol;
5631
5632 MB_PTR_BACK(line, p);
5633 while (p > line && vim_isfilec(PTR2CHAR(p)))
5634 MB_PTR_BACK(line, p);
5635 if (p == line && vim_isfilec(PTR2CHAR(p)))
5636 startcol = 0;
5637 else
5638 startcol = (int)(p - line) + 1;
5639 }
5640
5641 compl_col += startcol;
5642 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005643 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5644 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005645 {
John Marriott5e6ea922024-11-23 14:01:57 +01005646 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005647 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005648 }
5649
John Marriott5e6ea922024-11-23 14:01:57 +01005650 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005651
5652 return OK;
5653}
5654
5655/*
5656 * Get the pattern, column and length for command-line completion.
5657 * Sets the global variables: compl_col, compl_length and compl_pattern.
5658 */
5659 static int
5660get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5661{
John Marriott5e6ea922024-11-23 14:01:57 +01005662 compl_pattern.string = vim_strnsave(line, curs_col);
5663 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005664 {
John Marriott5e6ea922024-11-23 14:01:57 +01005665 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005666 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005667 }
John Marriott5e6ea922024-11-23 14:01:57 +01005668 compl_pattern.length = curs_col;
5669 set_cmd_context(&compl_xp, compl_pattern.string,
5670 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005671 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5672 || compl_xp.xp_context == EXPAND_NOTHING)
5673 // No completion possible, use an empty pattern to get a
5674 // "pattern not found" message.
5675 compl_col = curs_col;
5676 else
John Marriott5e6ea922024-11-23 14:01:57 +01005677 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005678 compl_length = curs_col - compl_col;
5679
5680 return OK;
5681}
5682
5683/*
5684 * Get the pattern, column and length for user defined completion ('omnifunc',
5685 * 'completefunc' and 'thesaurusfunc')
5686 * Sets the global variables: compl_col, compl_length and compl_pattern.
5687 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005688 * Callback function "cb" is set if triggered by a function in the 'cpt'
5689 * option; otherwise, it is NULL.
5690 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005691 */
5692 static int
Girish Palyacbe53192025-04-14 22:13:15 +02005693get_userdefined_compl_info(colnr_T curs_col UNUSED, callback_T *cb UNUSED,
5694 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005695{
5696 int ret = FAIL;
5697
5698#ifdef FEAT_COMPL_FUNC
5699 // Call user defined function 'completefunc' with "a:findstart"
5700 // set to 1 to obtain the length of text to use for completion.
5701 char_u *line;
5702 typval_T args[3];
5703 int col;
5704 char_u *funcname;
5705 pos_T pos;
5706 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005707 int len;
5708 string_T *compl_pat;
5709 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005710
Girish Palyacbe53192025-04-14 22:13:15 +02005711 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005712 {
Girish Palyacbe53192025-04-14 22:13:15 +02005713 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5714 // length as a string
5715 funcname = get_complete_funcname(ctrl_x_mode);
5716 if (*funcname == NUL)
5717 {
5718 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5719 ? "completefunc" : "omnifunc");
5720 return FAIL;
5721 }
5722 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005723 }
5724
5725 args[0].v_type = VAR_NUMBER;
5726 args[0].vval.v_number = 1;
5727 args[1].v_type = VAR_STRING;
5728 args[1].vval.v_string = (char_u *)"";
5729 args[2].v_type = VAR_UNKNOWN;
5730 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005731 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005732 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005733 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005734
5735 State = save_State;
5736 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005737 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005738 validate_cursor();
5739 if (!EQUAL_POS(curwin->w_cursor, pos))
5740 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005741 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005742 return FAIL;
5743 }
5744
Girish Palyacbe53192025-04-14 22:13:15 +02005745 if (startcol != NULL)
5746 *startcol = col;
5747
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005748 // Return value -2 means the user complete function wants to cancel the
5749 // complete without an error, do the same if the function did not execute
5750 // successfully.
5751 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005752 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005753 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005754 if (col == -3)
5755 {
Girish Palyacbe53192025-04-14 22:13:15 +02005756 if (is_cpt_function)
5757 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005758 ctrl_x_mode = CTRL_X_NORMAL;
5759 edit_submode = NULL;
5760 if (!shortmess(SHM_COMPLETIONMENU))
5761 msg_clr_cmdline();
5762 return FAIL;
5763 }
5764
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005765 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005766 // completion.
5767 compl_opt_refresh_always = FALSE;
5768 compl_opt_suppress_empty = FALSE;
5769
Girish Palyacbe53192025-04-14 22:13:15 +02005770 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005771 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005772
5773 // Setup variables for completion. Need to obtain "line" again,
5774 // it may have become invalid.
5775 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02005776 len = curs_col - col;
5777 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
5778 compl_pat->string = vim_strnsave(line + col, (size_t)len);
5779 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005780 {
Girish Palyacbe53192025-04-14 22:13:15 +02005781 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005782 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005783 }
Girish Palyacbe53192025-04-14 22:13:15 +02005784 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005785
Girish Palyacbe53192025-04-14 22:13:15 +02005786 if (!is_cpt_function)
5787 {
5788 compl_col = col;
5789 compl_length = len;
5790 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005791 ret = OK;
5792#endif
5793
5794 return ret;
5795}
5796
5797/*
5798 * Get the pattern, column and length for spell completion.
5799 * Sets the global variables: compl_col, compl_length and compl_pattern.
5800 * Uses the global variable: spell_bad_len
5801 */
5802 static int
5803get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5804{
5805 int ret = FAIL;
5806#ifdef FEAT_SPELL
5807 char_u *line;
5808
5809 if (spell_bad_len > 0)
5810 compl_col = curs_col - spell_bad_len;
5811 else
5812 compl_col = spell_word_start(startcol);
5813 if (compl_col >= (colnr_T)startcol)
5814 {
5815 compl_length = 0;
5816 compl_col = curs_col;
5817 }
5818 else
5819 {
5820 spell_expand_check_cap(compl_col);
5821 compl_length = (int)curs_col - compl_col;
5822 }
5823 // Need to obtain "line" again, it may have become invalid.
5824 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005825 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5826 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005827 {
John Marriott5e6ea922024-11-23 14:01:57 +01005828 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005829 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005830 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005831
John Marriott5e6ea922024-11-23 14:01:57 +01005832 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005833 ret = OK;
5834#endif
5835
5836 return ret;
5837}
5838
5839/*
5840 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005841 * "startcol" - start column number of the completion pattern/text
5842 * "cur_col" - current cursor column
5843 * On return, "line_invalid" is set to TRUE, if the current line may have
5844 * become invalid and needs to be fetched again.
5845 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005846 */
5847 static int
5848compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5849{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005850 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005851 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5852 && !thesaurus_func_complete(ctrl_x_mode)))
5853 {
5854 return get_normal_compl_info(line, startcol, curs_col);
5855 }
5856 else if (ctrl_x_mode_line_or_eval())
5857 {
5858 return get_wholeline_compl_info(line, curs_col);
5859 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005860 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005861 {
5862 return get_filename_compl_info(line, startcol, curs_col);
5863 }
5864 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5865 {
5866 return get_cmdline_compl_info(line, curs_col);
5867 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005868 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005869 || thesaurus_func_complete(ctrl_x_mode))
5870 {
Girish Palyacbe53192025-04-14 22:13:15 +02005871 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005872 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005873 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005874 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005875 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005876 {
5877 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5878 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005879 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005880 }
5881 else
5882 {
5883 internal_error("ins_complete()");
5884 return FAIL;
5885 }
5886
5887 return OK;
5888}
5889
5890/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005891 * Continue an interrupted completion mode search in "line".
5892 *
5893 * If this same ctrl_x_mode has been interrupted use the text from
5894 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5895 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5896 * the same line as the cursor then fix it (the line has been split because it
5897 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5898 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005899 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005900 static void
5901ins_compl_continue_search(char_u *line)
5902{
5903 // it is a continued search
5904 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005905 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5906 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005907 {
5908 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5909 {
5910 // line (probably) wrapped, set compl_startpos to the
5911 // first non_blank in the line, if it is not a wordchar
5912 // include it to get a better pattern, but then we don't
5913 // want the "\\<" prefix, check it below
5914 compl_col = (colnr_T)getwhitecols(line);
5915 compl_startpos.col = compl_col;
5916 compl_startpos.lnum = curwin->w_cursor.lnum;
5917 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5918 }
5919 else
5920 {
5921 // S_IPOS was set when we inserted a word that was at the
5922 // beginning of the line, which means that we'll go to SOL
5923 // mode but first we need to redefine compl_startpos
5924 if (compl_cont_status & CONT_S_IPOS)
5925 {
5926 compl_cont_status |= CONT_SOL;
5927 compl_startpos.col = (colnr_T)(skipwhite(
5928 line + compl_length
5929 + compl_startpos.col) - line);
5930 }
5931 compl_col = compl_startpos.col;
5932 }
5933 compl_length = curwin->w_cursor.col - (int)compl_col;
5934 // IObuff is used to add a "word from the next line" would we
5935 // have enough space? just being paranoid
5936#define MIN_SPACE 75
5937 if (compl_length > (IOSIZE - MIN_SPACE))
5938 {
5939 compl_cont_status &= ~CONT_SOL;
5940 compl_length = (IOSIZE - MIN_SPACE);
5941 compl_col = curwin->w_cursor.col - compl_length;
5942 }
5943 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5944 if (compl_length < 1)
5945 compl_cont_status &= CONT_LOCAL;
5946 }
5947 else if (ctrl_x_mode_line_or_eval())
5948 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5949 else
5950 compl_cont_status = 0;
5951}
5952
5953/*
5954 * start insert mode completion
5955 */
5956 static int
5957ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005958{
5959 char_u *line;
5960 int startcol = 0; // column where searched text starts
5961 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005962 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005963 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005964 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005965
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005966 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005967
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005968 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005969 did_si = FALSE;
5970 can_si = FALSE;
5971 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005972 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005973 return FAIL;
5974
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005975 line = ml_get(curwin->w_cursor.lnum);
5976 curs_col = curwin->w_cursor.col;
5977 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005978 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005979
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005980 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5981 && compl_cont_mode == ctrl_x_mode)
5982 // this same ctrl-x_mode was interrupted previously. Continue the
5983 // completion.
5984 ins_compl_continue_search(line);
5985 else
5986 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005987
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005988 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005989 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005990 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005991 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005992 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5993 compl_cont_status = 0;
5994 compl_cont_status |= CONT_N_ADDS;
5995 compl_startpos = curwin->w_cursor;
5996 startcol = (int)curs_col;
5997 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005998 }
5999
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006000 // Work out completion pattern and original text -- webb
6001 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6002 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006003 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6004 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006005 // restore did_ai, so that adding comment leader works
6006 did_ai = save_did_ai;
6007 return FAIL;
6008 }
6009 // If "line" was changed while getting completion info get it again.
6010 if (line_invalid)
6011 line = ml_get(curwin->w_cursor.lnum);
6012
glepnir7cfe6932024-09-15 20:06:28 +02006013 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006014 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006015 {
6016 edit_submode_pre = (char_u *)_(" Adding");
6017 if (ctrl_x_mode_line_or_eval())
6018 {
6019 // Insert a new line, keep indentation but ignore 'comments'.
6020 char_u *old = curbuf->b_p_com;
6021
6022 curbuf->b_p_com = (char_u *)"";
6023 compl_startpos.lnum = curwin->w_cursor.lnum;
6024 compl_startpos.col = compl_col;
6025 ins_eol('\r');
6026 curbuf->b_p_com = old;
6027 compl_length = 0;
6028 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006029 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006030 }
glepnir7cfe6932024-09-15 20:06:28 +02006031 else if (ctrl_x_mode_normal() && in_fuzzy)
6032 {
6033 compl_startpos = curwin->w_cursor;
6034 compl_cont_status &= CONT_S_IPOS;
6035 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006036 }
6037 else
6038 {
6039 edit_submode_pre = NULL;
6040 compl_startpos.col = compl_col;
6041 }
6042
6043 if (compl_cont_status & CONT_LOCAL)
6044 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6045 else
6046 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6047
6048 // If any of the original typed text has been changed we need to fix
6049 // the redo buffer.
6050 ins_compl_fixRedoBufForLeader(NULL);
6051
6052 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006053 VIM_CLEAR_STRING(compl_orig_text);
6054 compl_orig_text.length = (size_t)compl_length;
6055 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006056 if (p_ic)
6057 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006058 if (compl_orig_text.string == NULL
6059 || ins_compl_add(compl_orig_text.string,
6060 (int)compl_orig_text.length,
6061 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006062 {
John Marriott5e6ea922024-11-23 14:01:57 +01006063 VIM_CLEAR_STRING(compl_pattern);
6064 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006065 return FAIL;
6066 }
6067
6068 // showmode might reset the internal line pointers, so it must
6069 // be called before line = ml_get(), or when this address is no
6070 // longer needed. -- Acevedo.
6071 edit_submode_extra = (char_u *)_("-- Searching...");
6072 edit_submode_highl = HLF_COUNT;
6073 showmode();
6074 edit_submode_extra = NULL;
6075 out_flush();
6076
6077 return OK;
6078}
6079
6080/*
6081 * display the completion status message
6082 */
6083 static void
6084ins_compl_show_statusmsg(void)
6085{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006086 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006087 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006088 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006089 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006090 ? (char_u *)_("Hit end of paragraph")
6091 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006092 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006093 }
6094
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006095 if (edit_submode_extra == NULL)
6096 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006097 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006098 {
6099 edit_submode_extra = (char_u *)_("Back at original");
6100 edit_submode_highl = HLF_W;
6101 }
6102 else if (compl_cont_status & CONT_S_IPOS)
6103 {
6104 edit_submode_extra = (char_u *)_("Word from other line");
6105 edit_submode_highl = HLF_COUNT;
6106 }
6107 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6108 {
6109 edit_submode_extra = (char_u *)_("The only match");
6110 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006111 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006112 }
6113 else
6114 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006115#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006116 // Update completion sequence number when needed.
6117 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006118 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006119#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006120 // The match should always have a sequence number now, this is
6121 // just a safety check.
6122 if (compl_curr_match->cp_number != -1)
6123 {
6124 // Space for 10 text chars. + 2x10-digit no.s = 31.
6125 // Translations may need more than twice that.
6126 static char_u match_ref[81];
6127
6128 if (compl_matches > 0)
6129 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006130 _("match %d of %d"),
6131 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006132 else
6133 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006134 _("match %d"),
6135 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006136 edit_submode_extra = match_ref;
6137 edit_submode_highl = HLF_R;
6138 if (dollar_vcol >= 0)
6139 curs_columns(FALSE);
6140 }
6141 }
6142 }
6143
6144 // Show a message about what (completion) mode we're in.
6145 if (!compl_opt_suppress_empty)
6146 {
6147 showmode();
6148 if (!shortmess(SHM_COMPLETIONMENU))
6149 {
6150 if (edit_submode_extra != NULL)
6151 {
6152 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006153 {
6154 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006155 msg_attr((char *)edit_submode_extra,
6156 edit_submode_highl < HLF_COUNT
6157 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006158 msg_hist_off = FALSE;
6159 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006160 }
6161 else
6162 msg_clr_cmdline(); // necessary for "noshowmode"
6163 }
6164 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006165}
6166
6167/*
6168 * Do Insert mode completion.
6169 * Called when character "c" was typed, which has a meaning for completion.
6170 * Returns OK if completion was done, FAIL if something failed (out of mem).
6171 */
6172 int
6173ins_complete(int c, int enable_pum)
6174{
6175 int n;
6176 int save_w_wrow;
6177 int save_w_leftcol;
6178 int insert_match;
6179
6180 compl_direction = ins_compl_key2dir(c);
6181 insert_match = ins_compl_use_match(c);
6182
6183 if (!compl_started)
6184 {
6185 if (ins_compl_start() == FAIL)
6186 return FAIL;
6187 }
6188 else if (insert_match && stop_arrow() == FAIL)
6189 return FAIL;
6190
glepnircf7f0122025-04-15 19:02:00 +02006191 compl_curr_win = curwin;
6192 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006193 compl_shown_match = compl_curr_match;
6194 compl_shows_dir = compl_direction;
6195
6196 // Find next match (and following matches).
6197 save_w_wrow = curwin->w_wrow;
6198 save_w_leftcol = curwin->w_leftcol;
6199 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6200
6201 // may undisplay the popup menu
6202 ins_compl_upd_pum();
6203
6204 if (n > 1) // all matches have been found
6205 compl_matches = n;
6206 compl_curr_match = compl_shown_match;
6207 compl_direction = compl_shows_dir;
6208
6209 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6210 // mode.
6211 if (got_int && !global_busy)
6212 {
6213 (void)vgetc();
6214 got_int = FALSE;
6215 }
6216
6217 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006218 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006219 {
6220 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6221 // because we couldn't expand anything at first place, but if we used
6222 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6223 // (such as M in M'exico) if not tried already. -- Acevedo
6224 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006225 || compl_status_adding()
6226 || (ctrl_x_mode_not_default()
6227 && !ctrl_x_mode_path_patterns()
6228 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006229 compl_cont_status &= ~CONT_N_ADDS;
6230 }
6231
6232 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6233 compl_cont_status |= CONT_S_IPOS;
6234 else
6235 compl_cont_status &= ~CONT_S_IPOS;
6236
6237 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006238
6239 // Show the popup menu, unless we got interrupted.
6240 if (enable_pum && !compl_interrupted)
6241 show_pum(save_w_wrow, save_w_leftcol);
6242
6243 compl_was_interrupted = compl_interrupted;
6244 compl_interrupted = FALSE;
6245
6246 return OK;
6247}
6248
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006249/*
6250 * Remove (if needed) and show the popup menu
6251 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006252 static void
6253show_pum(int prev_w_wrow, int prev_w_leftcol)
6254{
6255 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006256 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006257 RedrawingDisabled = 0;
6258
6259 // If the cursor moved or the display scrolled we need to remove the pum
6260 // first.
6261 setcursor();
6262 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6263 ins_compl_del_pum();
6264
6265 ins_compl_show_pum();
6266 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006267
6268 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006269}
6270
6271/*
6272 * Looks in the first "len" chars. of "src" for search-metachars.
6273 * If dest is not NULL the chars. are copied there quoting (with
6274 * a backslash) the metachars, and dest would be NUL terminated.
6275 * Returns the length (needed) of dest
6276 */
6277 static unsigned
6278quote_meta(char_u *dest, char_u *src, int len)
6279{
6280 unsigned m = (unsigned)len + 1; // one extra for the NUL
6281
6282 for ( ; --len >= 0; src++)
6283 {
6284 switch (*src)
6285 {
6286 case '.':
6287 case '*':
6288 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006289 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006290 break;
6291 // FALLTHROUGH
6292 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006293 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006294 break;
6295 // FALLTHROUGH
6296 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006297 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006298 break;
6299 // FALLTHROUGH
6300 case '^': // currently it's not needed.
6301 case '$':
6302 m++;
6303 if (dest != NULL)
6304 *dest++ = '\\';
6305 break;
6306 }
6307 if (dest != NULL)
6308 *dest++ = *src;
6309 // Copy remaining bytes of a multibyte character.
6310 if (has_mbyte)
6311 {
6312 int i, mb_len;
6313
6314 mb_len = (*mb_ptr2len)(src) - 1;
6315 if (mb_len > 0 && len >= mb_len)
6316 for (i = 0; i < mb_len; ++i)
6317 {
6318 --len;
6319 ++src;
6320 if (dest != NULL)
6321 *dest++ = *src;
6322 }
6323 }
6324 }
6325 if (dest != NULL)
6326 *dest = NUL;
6327
6328 return m;
6329}
6330
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006331#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006332 void
6333free_insexpand_stuff(void)
6334{
John Marriott5e6ea922024-11-23 14:01:57 +01006335 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006336# ifdef FEAT_EVAL
6337 free_callback(&cfu_cb);
6338 free_callback(&ofu_cb);
6339 free_callback(&tsrfu_cb);
6340# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006341}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006342#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006343
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006344#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006345/*
6346 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6347 * spelled word, if there is one.
6348 */
6349 static void
6350spell_back_to_badword(void)
6351{
6352 pos_T tpos = curwin->w_cursor;
6353
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006354 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006355 if (curwin->w_cursor.col != tpos.col)
6356 start_arrow(&tpos);
6357}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006358#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006359
6360/*
6361 * Reset the info associated with completion sources.
6362 */
6363 static void
6364cpt_compl_src_clear(void)
6365{
6366 VIM_CLEAR(cpt_func_refresh_always);
6367 cpt_value_idx = -1;
6368 cpt_value_count = 0;
6369}
6370
6371/*
6372 * Initialize the info associated with completion sources.
6373 */
6374 static int
6375cpt_compl_src_init(char_u *cpt_str)
6376{
6377 int count = 0;
6378 char_u *p = cpt_str;
6379
6380 while (*p)
6381 {
6382 while (*p == ',' || *p == ' ') // Skip delimiters
6383 p++;
6384 if (*p) // If not end of string, count this segment
6385 {
6386 count++;
6387 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6388 }
6389 }
6390 cpt_compl_src_clear();
6391 cpt_value_count = count;
6392 if (count > 0)
6393 {
6394 cpt_func_refresh_always = ALLOC_CLEAR_MULT(int, count);
6395 if (cpt_func_refresh_always == NULL)
6396 {
6397 cpt_value_count = 0;
6398 return FAIL;
6399 }
6400 }
6401 return OK;
6402}
6403
6404/*
6405 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6406 */
6407 static int
6408is_cpt_func_refresh_always(void)
6409{
6410#ifdef FEAT_COMPL_FUNC
6411 int i;
6412
6413 for (i = 0; i < cpt_value_count; i++)
6414 if (cpt_func_refresh_always[i])
6415 return TRUE;
6416#endif
6417 return FALSE;
6418}
6419
6420/*
6421 * Make the completion list non-cyclic.
6422 */
6423#ifdef FEAT_COMPL_FUNC
6424 static void
6425ins_compl_make_linear(void)
6426{
6427 compl_T *m;
6428
6429 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6430 return;
6431 m = compl_first_match->cp_prev;
6432 m->cp_next = NULL;
6433 compl_first_match->cp_prev = NULL;
6434}
6435#endif
6436
6437/*
6438 * Remove the matches linked to the current completion source (as indicated by
6439 * cpt_value_idx) from the completion list.
6440 */
6441#ifdef FEAT_COMPL_FUNC
6442 static compl_T *
6443remove_old_matches(void)
6444{
6445 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6446 compl_T *current, *next;
6447 int compl_shown_removed = FALSE;
6448 int forward = compl_dir_forward();
6449
6450 // Identify the sublist of old matches that needs removal
6451 for (current = compl_first_match; current != NULL; current = current->cp_next)
6452 {
6453 if (current->cp_cpt_value_idx < cpt_value_idx && (forward || (!forward && !insert_at)))
6454 insert_at = current;
6455
6456 if (current->cp_cpt_value_idx == cpt_value_idx)
6457 {
6458 if (!sublist_start)
6459 sublist_start = current;
6460 sublist_end = current;
6461 if (!compl_shown_removed && compl_shown_match == current)
6462 compl_shown_removed = TRUE;
6463 }
6464
6465 if ((forward && current->cp_cpt_value_idx > cpt_value_idx) || (!forward && insert_at))
6466 break;
6467 }
6468
6469 // Re-assign compl_shown_match if necessary
6470 if (compl_shown_removed)
6471 {
6472 if (forward)
6473 compl_shown_match = compl_first_match;
6474 else
6475 { // Last node will have the prefix that is being completed
6476 for (current = compl_first_match; current->cp_next != NULL; current = current->cp_next)
6477 ;
6478 compl_shown_match = current;
6479 }
6480 }
6481
6482 if (!sublist_start) // No nodes to remove
6483 return insert_at;
6484
6485 // Update links to remove sublist
6486 if (sublist_start->cp_prev)
6487 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6488 else
6489 compl_first_match = sublist_end->cp_next;
6490
6491 if (sublist_end->cp_next)
6492 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6493
6494 // Free all nodes in the sublist
6495 sublist_end->cp_next = NULL;
6496 for (current = sublist_start; current != NULL; current = next)
6497 {
6498 next = current->cp_next;
6499 ins_compl_item_free(current);
6500 }
6501
6502 return insert_at;
6503}
6504#endif
6505
6506/*
6507 * Retrieve completion matches using the callback function "cb" and store the
6508 * 'refresh:always' flag.
6509 */
6510#ifdef FEAT_COMPL_FUNC
6511 static void
6512get_cpt_func_completion_matches(callback_T *cb UNUSED)
6513{
6514 int ret;
6515 int startcol;
6516
6517 VIM_CLEAR_STRING(cpt_compl_pattern);
6518 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6519 if (ret == FAIL && startcol == -3)
6520 cpt_func_refresh_always[cpt_value_idx] = FALSE;
6521 else if (ret == OK)
6522 {
6523 expand_by_function(0, cpt_compl_pattern.string, cb);
6524 cpt_func_refresh_always[cpt_value_idx] = compl_opt_refresh_always;
6525 compl_opt_refresh_always = FALSE;
6526 }
6527}
6528#endif
6529
6530/*
6531 * Retrieve completion matches from functions in the 'cpt' option where the
6532 * 'refresh:always' flag is set.
6533 */
6534 static void
6535cpt_compl_refresh(void)
6536{
6537#ifdef FEAT_COMPL_FUNC
6538 char_u *cpt;
6539 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006540 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006541
6542 // Make the completion list linear (non-cyclic)
6543 ins_compl_make_linear();
6544 // Make a copy of 'cpt' in case the buffer gets wiped out
6545 cpt = vim_strsave(curbuf->b_p_cpt);
6546
6547 cpt_value_idx = 0;
6548 for (p = cpt; *p; cpt_value_idx++)
6549 {
6550 while (*p == ',' || *p == ' ') // Skip delimiters
6551 p++;
6552
6553 if (cpt_func_refresh_always[cpt_value_idx])
6554 {
6555 if (*p == 'o')
6556 cb = &curbuf->b_ofu_cb;
6557 else if (*p == 'f')
6558 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6559 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6560 if (cb)
6561 {
6562 compl_curr_match = remove_old_matches();
6563 get_cpt_func_completion_matches(cb);
6564 }
6565 }
6566
6567 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6568 }
6569 cpt_value_idx = -1;
6570
6571 vim_free(cpt);
6572 // Make the list cyclic
6573 compl_matches = ins_compl_make_cyclic();
6574#endif
6575}