blob: c0762da9081fdca00b1571e61a5494c8e84a4ed2 [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020061 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010062 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010091 * Structure used to store one match for insert completion.
92 */
93typedef struct compl_S compl_T;
94struct compl_S
95{
96 compl_T *cp_next;
97 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +010098 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +010099 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200100 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100101#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100102 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100103#endif
glepnir0fe17f82024-10-08 22:26:44 +0200104 char_u *cp_fname; // file containing the match, allocated when
105 // cp_flags has CP_FREE_FNAME
106 int cp_flags; // CP_ values
107 int cp_number; // sequence number
108 int cp_score; // fuzzy match score
glepnird4088ed2024-12-31 10:55:22 +0100109 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200110 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200111 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palyacbe53192025-04-14 22:13:15 +0200112 int cp_cpt_value_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100113};
114
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200115// values for cp_flags
116# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
117# define CP_FREE_FNAME 2 // cp_fname is allocated
118# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
119# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
120# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200121# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100122
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100123/*
124 * All the current matches are stored in a list.
125 * "compl_first_match" points to the start of the list.
126 * "compl_curr_match" points to the currently selected entry.
127 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200128 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000129 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100130 */
131static compl_T *compl_first_match = NULL;
132static compl_T *compl_curr_match = NULL;
133static compl_T *compl_shown_match = NULL;
134static compl_T *compl_old_match = NULL;
135
glepnirf31cfa22025-03-06 21:59:13 +0100136// list used to store the compl_T which have the max score
137// used for completefuzzycollect
138static compl_T **compl_best_matches = NULL;
139static int compl_num_bests = 0;
140// inserted a longest when completefuzzycollect enabled
141static int compl_cfc_longest_ins = FALSE;
142
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100143// After using a cursor key <Enter> selects a match in the popup menu,
144// otherwise it inserts a line break.
145static int compl_enter_selects = FALSE;
146
147// When "compl_leader" is not NULL only matches that start with this string
148// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100149static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100150
151static int compl_get_longest = FALSE; // put longest common string
152 // in compl_leader
153
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100154// Selected one of the matches. When FALSE the match was edited or using the
155// longest common string.
156static int compl_used_match;
157
158// didn't finish finding completions.
159static int compl_was_interrupted = FALSE;
160
161// Set when character typed while looking for matches and it means we should
162// stop looking for matches.
163static int compl_interrupted = FALSE;
164
165static int compl_restarting = FALSE; // don't insert match
166
167// When the first completion is done "compl_started" is set. When it's
168// FALSE the word to be completed must be located.
169static int compl_started = FALSE;
170
171// Which Ctrl-X mode are we in?
172static int ctrl_x_mode = CTRL_X_NORMAL;
173
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000174static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200175static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
176#ifdef FEAT_COMPL_FUNC
177static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
178#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100179static int compl_direction = FORWARD;
180static int compl_shows_dir = FORWARD;
181static int compl_pending = 0; // > 1 for postponed CTRL-N
182static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000183// Length in bytes of the text being completed (this is deleted to be replaced
184// by the match.)
185static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100186static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100187static colnr_T compl_col = 0; // column where the text starts
188 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100189static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100190static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100191 // completion started
192static int compl_cont_mode = 0;
193static expand_T compl_xp;
194
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000195// List of flags for method of completion.
196static int compl_cont_status = 0;
197# define CONT_ADDING 1 // "normal" or "adding" expansion
198# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
199 // it's set only iff N_ADDS is set
200# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
201# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
202 // if so, word-wise-expansion will set SOL
203# define CONT_SOL 16 // pattern includes start of line, just for
204 // word-wise expansion, not set for ^X^L
205# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
206 // expansion, (eg use complete=.)
207
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100208static int compl_opt_refresh_always = FALSE;
209static int compl_opt_suppress_empty = FALSE;
210
glepnira218cc62024-06-03 19:32:39 +0200211static int compl_selected_item = -1;
212
glepnir8159fb12024-07-17 20:32:54 +0200213static int *compl_fuzzy_scores;
214
Girish Palyacbe53192025-04-14 22:13:15 +0200215static int *cpt_func_refresh_always; // array indicating which 'cpt' functions have 'refresh:always' set
216static int cpt_value_count; // total number of completion sources specified in the 'cpt' option
217static int cpt_value_idx; // index of the current completion source being expanded
218
glepnir6a38aff2024-12-16 21:56:16 +0100219// "compl_match_array" points the currently displayed list of entries in the
220// popup menu. It is NULL when there is no popup menu.
221static pumitem_T *compl_match_array = NULL;
222static int compl_match_arraysize;
223
glepnirf31cfa22025-03-06 21:59:13 +0100224static 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 +0100225static void ins_compl_longest_match(compl_T *match);
226static void ins_compl_del_pum(void);
227static 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 +0100228static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100229static int ins_compl_need_restart(void);
230static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000231static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100232static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100233static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100234static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
235# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
236static void ins_compl_add_list(list_T *list);
237static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200238static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
239static callback_T *get_cpt_func_callback(char_u *funcname);
240static void get_cpt_func_completion_matches(callback_T *cb);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100241# endif
Girish Palyacbe53192025-04-14 22:13:15 +0200242static int cpt_compl_src_init(char_u *p_cpt);
243static int is_cpt_func_refresh_always(void);
244static void cpt_compl_src_clear(void);
245static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100246static int ins_compl_key2dir(int c);
247static int ins_compl_pum_key(int c);
248static int ins_compl_key2count(int c);
249static void show_pum(int prev_w_wrow, int prev_w_leftcol);
250static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100251static int ins_compl_has_multiple(void);
252static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100253static void ins_compl_longest_insert(char_u *prefix);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100254
255#ifdef FEAT_SPELL
256static void spell_back_to_badword(void);
257static int spell_bad_len = 0; // length of located bad word
258#endif
259
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100260/*
261 * CTRL-X pressed in Insert mode.
262 */
263 void
264ins_ctrl_x(void)
265{
zeertzjqdca29d92021-08-31 19:12:51 +0200266 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100267 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000268 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100269 if (compl_cont_status & CONT_N_ADDS)
270 compl_cont_status |= CONT_INTRPT;
271 else
272 compl_cont_status = 0;
273 // We're not sure which CTRL-X mode it will be yet
274 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
275 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
276 edit_submode_pre = NULL;
277 showmode();
278 }
zeertzjqdca29d92021-08-31 19:12:51 +0200279 else
280 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
281 // CTRL-V look like CTRL-N
282 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100283
LemonBoy2bf52dd2022-04-09 18:17:34 +0100284 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100285}
286
287/*
288 * Functions to check the current CTRL-X mode.
289 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000290int ctrl_x_mode_none(void)
291 { return ctrl_x_mode == 0; }
292int ctrl_x_mode_normal(void)
293 { return ctrl_x_mode == CTRL_X_NORMAL; }
294int ctrl_x_mode_scroll(void)
295 { return ctrl_x_mode == CTRL_X_SCROLL; }
296int ctrl_x_mode_whole_line(void)
297 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
298int ctrl_x_mode_files(void)
299 { return ctrl_x_mode == CTRL_X_FILES; }
300int ctrl_x_mode_tags(void)
301 { return ctrl_x_mode == CTRL_X_TAGS; }
302int ctrl_x_mode_path_patterns(void)
303 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
304int ctrl_x_mode_path_defines(void)
305 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
306int ctrl_x_mode_dictionary(void)
307 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
308int ctrl_x_mode_thesaurus(void)
309 { return ctrl_x_mode == CTRL_X_THESAURUS; }
310int ctrl_x_mode_cmdline(void)
311 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200312 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000313int ctrl_x_mode_function(void)
314 { return ctrl_x_mode == CTRL_X_FUNCTION; }
315int ctrl_x_mode_omni(void)
316 { return ctrl_x_mode == CTRL_X_OMNI; }
317int ctrl_x_mode_spell(void)
318 { return ctrl_x_mode == CTRL_X_SPELL; }
319static int ctrl_x_mode_eval(void)
320 { return ctrl_x_mode == CTRL_X_EVAL; }
321int ctrl_x_mode_line_or_eval(void)
322 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100323
324/*
325 * Whether other than default completion has been selected.
326 */
327 int
328ctrl_x_mode_not_default(void)
329{
330 return ctrl_x_mode != CTRL_X_NORMAL;
331}
332
333/*
zeertzjqdca29d92021-08-31 19:12:51 +0200334 * Whether CTRL-X was typed without a following character,
335 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100336 */
337 int
338ctrl_x_mode_not_defined_yet(void)
339{
340 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
341}
342
343/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000344 * Return TRUE if currently in "normal" or "adding" insert completion matches
345 * state
346 */
347 int
348compl_status_adding(void)
349{
350 return compl_cont_status & CONT_ADDING;
351}
352
353/*
354 * Return TRUE if the completion pattern includes start of line, just for
355 * word-wise expansion.
356 */
357 int
358compl_status_sol(void)
359{
360 return compl_cont_status & CONT_SOL;
361}
362
363/*
364 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
365 */
366 int
367compl_status_local(void)
368{
369 return compl_cont_status & CONT_LOCAL;
370}
371
372/*
373 * Clear the completion status flags
374 */
375 void
376compl_status_clear(void)
377{
378 compl_cont_status = 0;
379}
380
381/*
382 * Return TRUE if completion is using the forward direction matches
383 */
384 static int
385compl_dir_forward(void)
386{
387 return compl_direction == FORWARD;
388}
389
390/*
391 * Return TRUE if currently showing forward completion matches
392 */
393 static int
394compl_shows_dir_forward(void)
395{
396 return compl_shows_dir == FORWARD;
397}
398
399/*
400 * Return TRUE if currently showing backward completion matches
401 */
402 static int
403compl_shows_dir_backward(void)
404{
405 return compl_shows_dir == BACKWARD;
406}
407
408/*
409 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100410 */
411 int
412has_compl_option(int dict_opt)
413{
414 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200415#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100416 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200417#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100418 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100419 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
420#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100421 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100422#endif
423 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100424 {
425 ctrl_x_mode = CTRL_X_NORMAL;
426 edit_submode = NULL;
427 msg_attr(dict_opt ? _("'dictionary' option is empty")
428 : _("'thesaurus' option is empty"),
429 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100430 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100431 {
432 vim_beep(BO_COMPL);
433 setcursor();
434 out_flush();
435#ifdef FEAT_EVAL
436 if (!get_vim_var_nr(VV_TESTING))
437#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100438 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100439 }
440 return FALSE;
441 }
442 return TRUE;
443}
444
445/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000446 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100447 * This depends on the current mode.
448 */
449 int
450vim_is_ctrl_x_key(int c)
451{
452 // Always allow ^R - let its results then be checked
453 if (c == Ctrl_R)
454 return TRUE;
455
456 // Accept <PageUp> and <PageDown> if the popup menu is visible.
457 if (ins_compl_pum_key(c))
458 return TRUE;
459
460 switch (ctrl_x_mode)
461 {
462 case 0: // Not in any CTRL-X mode
463 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
464 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200465 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100466 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
467 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
468 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
469 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
470 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200471 || c == Ctrl_S || c == Ctrl_K || c == 's'
472 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100473 case CTRL_X_SCROLL:
474 return (c == Ctrl_Y || c == Ctrl_E);
475 case CTRL_X_WHOLE_LINE:
476 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
477 case CTRL_X_FILES:
478 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
479 case CTRL_X_DICTIONARY:
480 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
481 case CTRL_X_THESAURUS:
482 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
483 case CTRL_X_TAGS:
484 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
485#ifdef FEAT_FIND_ID
486 case CTRL_X_PATH_PATTERNS:
487 return (c == Ctrl_P || c == Ctrl_N);
488 case CTRL_X_PATH_DEFINES:
489 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
490#endif
491 case CTRL_X_CMDLINE:
492 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
493 || c == Ctrl_X);
494#ifdef FEAT_COMPL_FUNC
495 case CTRL_X_FUNCTION:
496 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
497 case CTRL_X_OMNI:
498 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
499#endif
500 case CTRL_X_SPELL:
501 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
502 case CTRL_X_EVAL:
503 return (c == Ctrl_P || c == Ctrl_N);
504 }
505 internal_error("vim_is_ctrl_x_key()");
506 return FALSE;
507}
508
509/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000510 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000511 */
512 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000513match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000514{
515 return match->cp_flags & CP_ORIGINAL_TEXT;
516}
517
518/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000519 * Returns TRUE if "match" is the first match in the completion list.
520 */
521 static int
522is_first_match(compl_T *match)
523{
524 return match == compl_first_match;
525}
526
527/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100528 * Return TRUE when character "c" is part of the item currently being
529 * completed. Used to decide whether to abandon complete mode when the menu
530 * is visible.
531 */
532 int
533ins_compl_accept_char(int c)
534{
535 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
536 // When expanding an identifier only accept identifier chars.
537 return vim_isIDc(c);
538
539 switch (ctrl_x_mode)
540 {
541 case CTRL_X_FILES:
542 // When expanding file name only accept file name chars. But not
543 // path separators, so that "proto/<Tab>" expands files in
544 // "proto", not "proto/" as a whole
545 return vim_isfilec(c) && !vim_ispathsep(c);
546
547 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200548 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100549 case CTRL_X_OMNI:
550 // Command line and Omni completion can work with just about any
551 // printable character, but do stop at white space.
552 return vim_isprintc(c) && !VIM_ISWHITE(c);
553
554 case CTRL_X_WHOLE_LINE:
555 // For while line completion a space can be part of the line.
556 return vim_isprintc(c);
557 }
558 return vim_iswordc(c);
559}
560
561/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000562 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100563 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000564 */
565 static char_u *
566ins_compl_infercase_gettext(
567 char_u *str,
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100568 int char_len,
569 int compl_char_len,
570 int min_len,
571 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000572{
573 int *wca; // Wide character array.
574 char_u *p;
575 int i, c;
576 int has_lower = FALSE;
577 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100578 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000579
580 IObuff[0] = NUL;
581
582 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100583 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000584 if (wca == NULL)
585 return IObuff;
586
587 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100588 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100589 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000590 if (has_mbyte)
591 wca[i] = mb_ptr2char_adv(&p);
592 else
593 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100594 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000595
596 // Rule 1: Were any chars converted to lower?
John Marriott5e6ea922024-11-23 14:01:57 +0100597 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000598 for (i = 0; i < min_len; ++i)
599 {
glepnir6e199932024-12-14 21:13:27 +0100600 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000601 if (MB_ISLOWER(c))
602 {
603 has_lower = TRUE;
604 if (MB_ISUPPER(wca[i]))
605 {
606 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100607 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000608 wca[i] = MB_TOLOWER(wca[i]);
609 break;
610 }
611 }
612 }
613
614 // Rule 2: No lower case, 2nd consecutive letter converted to
615 // upper case.
616 if (!has_lower)
617 {
John Marriott5e6ea922024-11-23 14:01:57 +0100618 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000619 for (i = 0; i < min_len; ++i)
620 {
glepnir6e199932024-12-14 21:13:27 +0100621 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000622 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
623 {
624 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100625 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000626 wca[i] = MB_TOUPPER(wca[i]);
627 break;
628 }
629 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
630 }
631 }
632
633 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100634 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000635 for (i = 0; i < min_len; ++i)
636 {
glepnir6e199932024-12-14 21:13:27 +0100637 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000638 if (MB_ISLOWER(c))
639 wca[i] = MB_TOLOWER(wca[i]);
640 else if (MB_ISUPPER(c))
641 wca[i] = MB_TOUPPER(wca[i]);
642 }
643
644 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000645 p = IObuff;
646 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100647 ga_init2(&gap, 1, 500);
648 while (i < char_len)
649 {
650 if (gap.ga_data != NULL)
651 {
652 if (ga_grow(&gap, 10) == FAIL)
653 {
654 ga_clear(&gap);
655 return (char_u *)"[failed]";
656 }
657 p = (char_u *)gap.ga_data + gap.ga_len;
658 if (has_mbyte)
659 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
660 else
661 {
662 *p = wca[i++];
663 ++gap.ga_len;
664 }
665 }
666 else if ((p - IObuff) + 6 >= IOSIZE)
667 {
668 // Multi-byte characters can occupy up to five bytes more than
669 // ASCII characters, and we also need one byte for NUL, so when
670 // getting to six bytes from the edge of IObuff switch to using a
671 // growarray. Add the character in the next round.
672 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100673 {
674 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100675 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100676 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100677 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100678 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100679 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100680 }
681 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000682 p += (*mb_char2bytes)(wca[i++], p);
683 else
684 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100685 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000686 vim_free(wca);
687
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100688 if (gap.ga_data != NULL)
689 {
690 *tofree = gap.ga_data;
691 return gap.ga_data;
692 }
693
694 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000695 return IObuff;
696}
697
698/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100699 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
700 * case of the originally typed text is used, and the case of the completed
701 * text is inferred, ie this tries to work out what case you probably wanted
702 * the rest of the word to be in -- webb
703 */
704 int
705ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200706 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100707 int len,
708 int icase,
709 char_u *fname,
710 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100711 int cont_s_ipos, // next ^X<> will set initial_pos
712 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100713{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200714 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100715 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100716 int char_len; // count multi-byte characters
717 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100718 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200719 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100720 int res;
721 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100722
723 if (p_ic && curbuf->b_p_inf && len > 0)
724 {
725 // Infer case of completed part.
726
727 // Find actual length of completion.
728 if (has_mbyte)
729 {
730 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100731 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100732 while (*p != NUL)
733 {
734 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100735 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100736 }
737 }
738 else
glepnir6e199932024-12-14 21:13:27 +0100739 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100740 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100741 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100742
743 // Find actual length of original text.
744 if (has_mbyte)
745 {
John Marriott5e6ea922024-11-23 14:01:57 +0100746 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100747 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100748 while (*p != NUL)
749 {
750 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100751 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100752 }
753 }
754 else
glepnir6e199932024-12-14 21:13:27 +0100755 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100756 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100757 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100758
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100759 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100760 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100761 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100762
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100763 str = ins_compl_infercase_gettext(str, char_len,
764 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100765 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200766 if (cont_s_ipos)
767 flags |= CP_CONT_S_IPOS;
768 if (icase)
769 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200770
glepnirf31cfa22025-03-06 21:59:13 +0100771 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100772 vim_free(tofree);
773 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100774}
775
776/*
glepnirf31cfa22025-03-06 21:59:13 +0100777 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
778 */
779 static int
780cfc_has_mode(void)
781{
glepnir58760162025-03-13 21:39:51 +0100782 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
783 return (cfc_flags & CFC_KEYWORD) != 0;
784 else if (ctrl_x_mode_files())
785 return (cfc_flags & CFC_FILES) != 0;
786 else if (ctrl_x_mode_whole_line())
787 return (cfc_flags & CFC_WHOLELINE) != 0;
788 else
789 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100790}
791
792/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000793 * Add a match to the list of matches. The arguments are:
794 * str - text of the match to add
795 * len - length of "str". If -1, then the length of "str" is
796 * computed.
797 * fname - file name to associate with this match.
798 * cptext - list of strings to use with this match (for abbr, menu, info
799 * and kind)
800 * user_data - user supplied data (any vim type) for this match
801 * cdir - match direction. If 0, use "compl_direction".
802 * flags_arg - match flags (cp_flags)
803 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100804 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000805 * If "cdir" is FORWARD, then the match is added after the current match.
806 * Otherwise, it is added before the current match.
807 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100808 * If the given string is already in the list of completions, then return
809 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
810 * maybe because alloc() returns NULL, then FAIL is returned.
811 */
812 static int
813ins_compl_add(
814 char_u *str,
815 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100816 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100817 char_u **cptext, // extra text for popup menu or NULL
818 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100819 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200820 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200821 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100822 int *user_hl, // user abbr/kind hlattr
823 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100824{
glepnirf31cfa22025-03-06 21:59:13 +0100825 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100826 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200827 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100828 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100829
Bram Moolenaarceb06192021-04-04 15:05:22 +0200830 if (flags & CP_FAST)
831 fast_breakcheck();
832 else
833 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100834 if (got_int)
835 return FAIL;
836 if (len < 0)
837 len = (int)STRLEN(str);
838
839 // If the same match is already present, don't add it.
840 if (compl_first_match != NULL && !adup)
841 {
842 match = compl_first_match;
843 do
844 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000845 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100846 && STRNCMP(match->cp_str.string, str, len) == 0
847 && ((int)match->cp_str.length <= len
848 || match->cp_str.string[len] == NUL))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100849 return NOTDONE;
850 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000851 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100852 }
853
854 // Remove any popup menu before changing the list of matches.
855 ins_compl_del_pum();
856
857 // Allocate a new match structure.
858 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200859 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100860 if (match == NULL)
861 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100862 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100863 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100864 {
865 vim_free(match);
866 return FAIL;
867 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100868
John Marriott5e6ea922024-11-23 14:01:57 +0100869 match->cp_str.length = len;
870
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100871 // match-fname is:
872 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200873 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100874 // - NULL otherwise. --Acevedo
875 if (fname != NULL
876 && compl_curr_match != NULL
877 && compl_curr_match->cp_fname != NULL
878 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
879 match->cp_fname = compl_curr_match->cp_fname;
880 else if (fname != NULL)
881 {
882 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200883 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100884 }
885 else
886 match->cp_fname = NULL;
887 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100888 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
889 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100890 match->cp_score = score;
Girish Palyacbe53192025-04-14 22:13:15 +0200891 match->cp_cpt_value_idx = cpt_value_idx;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100892
893 if (cptext != NULL)
894 {
895 int i;
896
897 for (i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100898 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100899 if (cptext[i] != NULL && *cptext[i] != NUL)
900 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100901 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100902 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100903#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100904 if (user_data != NULL)
905 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100906#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100907
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000908 // Link the new match structure after (FORWARD) or before (BACKWARD) the
909 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100910 if (compl_first_match == NULL)
911 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +0100912 else if (cfc_has_mode() && score > 0 && compl_get_longest)
913 {
914 current = compl_first_match->cp_next;
915 prev = compl_first_match;
916 inserted = FALSE;
917 // The direction is ignored when using longest and
918 // completefuzzycollect, because matches are inserted
919 // and sorted by score.
920 while (current != NULL && current != compl_first_match)
921 {
922 if (current->cp_score < score)
923 {
924 match->cp_next = current;
925 match->cp_prev = current->cp_prev;
926 if (current->cp_prev)
927 current->cp_prev->cp_next = match;
928 current->cp_prev = match;
929 inserted = TRUE;
930 break;
931 }
932 prev = current;
933 current = current->cp_next;
934 }
935 if (!inserted)
936 {
937 prev->cp_next = match;
938 match->cp_prev = prev;
939 match->cp_next = compl_first_match;
940 compl_first_match->cp_prev = match;
941 }
942 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100943 else if (dir == FORWARD)
944 {
945 match->cp_next = compl_curr_match->cp_next;
946 match->cp_prev = compl_curr_match;
947 }
948 else // BACKWARD
949 {
950 match->cp_next = compl_curr_match;
951 match->cp_prev = compl_curr_match->cp_prev;
952 }
953 if (match->cp_next)
954 match->cp_next->cp_prev = match;
955 if (match->cp_prev)
956 match->cp_prev->cp_next = match;
957 else // if there's nothing before, it is the first match
958 compl_first_match = match;
959 compl_curr_match = match;
960
961 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +0100962 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100963 ins_compl_longest_match(match);
964
965 return OK;
966}
967
968/*
969 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200970 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100971 */
972 static int
973ins_compl_equal(compl_T *match, char_u *str, int len)
974{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200975 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200976 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200977 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +0100978 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
979 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100980}
981
982/*
glepnir6a38aff2024-12-16 21:56:16 +0100983 * when len is -1 mean use whole length of p otherwise part of p
984 */
985 static void
986ins_compl_insert_bytes(char_u *p, int len)
987{
988 if (len == -1)
989 len = (int)STRLEN(p);
990 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +0100991 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +0100992}
993
994/*
zeertzjqd32bf0a2024-12-17 20:55:13 +0100995 * Checks if the column is within the currently inserted completion text
996 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +0100997 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +0100998 */
999 int
glepnir76bdb822025-02-08 19:04:51 +01001000ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001001{
glepnir76bdb822025-02-08 19:04:51 +01001002 int start_col;
1003 int attr;
1004
1005 if ((get_cot_flags() & COT_FUZZY)
1006 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001007 return -1;
1008
glepnir76bdb822025-02-08 19:04:51 +01001009 start_col = compl_col + (int)ins_compl_leader_len();
1010 if (!ins_compl_has_multiple())
1011 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1012
1013 // Multiple lines
1014 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1015 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1016 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1017 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001018
1019 return -1;
1020}
1021
1022/*
glepnir76bdb822025-02-08 19:04:51 +01001023 * Returns TRUE if the current completion string contains newline characters,
1024 * indicating it's a multi-line completion.
1025 */
1026 static int
1027ins_compl_has_multiple(void)
1028{
1029 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1030}
1031
1032/*
1033 * Returns TRUE if the given line number falls within the range of a multi-line
1034 * completion, i.e. between the starting line (compl_lnum) and current cursor
1035 * line. Always returns FALSE for single-line completions.
1036 */
1037 int
1038ins_compl_lnum_in_range(linenr_T lnum)
1039{
1040 if (!ins_compl_has_multiple())
1041 return FALSE;
1042 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1043}
1044
1045/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001046 * Reduce the longest common string for match "match".
1047 */
1048 static void
1049ins_compl_longest_match(compl_T *match)
1050{
1051 char_u *p, *s;
1052 int c1, c2;
1053 int had_match;
1054
John Marriott5e6ea922024-11-23 14:01:57 +01001055 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001056 {
1057 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001058 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1059 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001060 return;
1061
John Marriott5e6ea922024-11-23 14:01:57 +01001062 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001063 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001064 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001065
1066 // When the match isn't there (to avoid matching itself) remove it
1067 // again after redrawing.
1068 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001069 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001070 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001071
1072 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001073 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001074
1075 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001076 p = compl_leader.string;
1077 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001078 while (*p != NUL)
1079 {
1080 if (has_mbyte)
1081 {
1082 c1 = mb_ptr2char(p);
1083 c2 = mb_ptr2char(s);
1084 }
1085 else
1086 {
1087 c1 = *p;
1088 c2 = *s;
1089 }
1090 if ((match->cp_flags & CP_ICASE)
1091 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1092 break;
1093 if (has_mbyte)
1094 {
1095 MB_PTR_ADV(p);
1096 MB_PTR_ADV(s);
1097 }
1098 else
1099 {
1100 ++p;
1101 ++s;
1102 }
1103 }
1104
1105 if (*p != NUL)
1106 {
1107 // Leader was shortened, need to change the inserted text.
1108 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001109 compl_leader.length = (size_t)(p - compl_leader.string);
1110
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001111 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001112 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001113
1114 // When the match isn't there (to avoid matching itself) remove it
1115 // again after redrawing.
1116 if (!had_match)
1117 ins_compl_delete();
1118 }
1119
1120 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001121}
1122
1123/*
1124 * Add an array of matches to the list of matches.
1125 * Frees matches[].
1126 */
1127 static void
1128ins_compl_add_matches(
1129 int num_matches,
1130 char_u **matches,
1131 int icase)
1132{
1133 int i;
1134 int add_r = OK;
1135 int dir = compl_direction;
1136
1137 for (i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001138 {
1139 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001140 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001141 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001142 // if dir was BACKWARD then honor it just once
1143 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001144 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001145 FreeWild(num_matches, matches);
1146}
1147
1148/*
1149 * Make the completion list cyclic.
1150 * Return the number of matches (excluding the original).
1151 */
1152 static int
1153ins_compl_make_cyclic(void)
1154{
1155 compl_T *match;
1156 int count = 0;
1157
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001158 if (compl_first_match == NULL)
1159 return 0;
1160
1161 // Find the end of the list.
1162 match = compl_first_match;
1163 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001164 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001165 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001166 match = match->cp_next;
1167 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001168 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001169 match->cp_next = compl_first_match;
1170 compl_first_match->cp_prev = match;
1171
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001172 return count;
1173}
1174
1175/*
1176 * Return whether there currently is a shown match.
1177 */
1178 int
1179ins_compl_has_shown_match(void)
1180{
1181 return compl_shown_match == NULL
1182 || compl_shown_match != compl_shown_match->cp_next;
1183}
1184
1185/*
1186 * Return whether the shown match is long enough.
1187 */
1188 int
1189ins_compl_long_shown_match(void)
1190{
John Marriott5e6ea922024-11-23 14:01:57 +01001191 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001192 > curwin->w_cursor.col - compl_col;
1193}
1194
1195/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001196 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001197 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001198 unsigned int
1199get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001200{
zeertzjq529b9ad2024-06-05 20:27:06 +02001201 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001202}
1203
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001204/*
1205 * Update the screen and when there is any scrolling remove the popup menu.
1206 */
1207 static void
1208ins_compl_upd_pum(void)
1209{
1210 int h;
1211
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001212 if (compl_match_array == NULL)
1213 return;
1214
1215 h = curwin->w_cline_height;
1216 // Update the screen later, before drawing the popup menu over it.
1217 pum_call_update_screen();
1218 if (h != curwin->w_cline_height)
1219 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001220}
1221
1222/*
1223 * Remove any popup menu.
1224 */
1225 static void
1226ins_compl_del_pum(void)
1227{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001228 if (compl_match_array == NULL)
1229 return;
1230
1231 pum_undisplay();
1232 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001233}
1234
1235/*
1236 * Return TRUE if the popup menu should be displayed.
1237 */
1238 int
1239pum_wanted(void)
1240{
1241 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001242 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001243 return FALSE;
1244
1245 // The display looks bad on a B&W display.
1246 if (t_colors < 8
1247#ifdef FEAT_GUI
1248 && !gui.in_use
1249#endif
1250 )
1251 return FALSE;
1252 return TRUE;
1253}
1254
1255/*
1256 * Return TRUE if there are two or more matches to be shown in the popup menu.
1257 * One if 'completopt' contains "menuone".
1258 */
1259 static int
1260pum_enough_matches(void)
1261{
1262 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001263 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001264
1265 // Don't display the popup menu if there are no matches or there is only
1266 // one (ignoring the original text).
1267 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001268 do
1269 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001270 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001271 break;
1272 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001273 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001274
zeertzjq529b9ad2024-06-05 20:27:06 +02001275 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001276 return (i >= 1);
1277 return (i >= 2);
1278}
1279
Bram Moolenaar3075a452021-11-17 15:51:52 +00001280#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001281/*
1282 * Allocate Dict for the completed item.
1283 * { word, abbr, menu, kind, info }
1284 */
1285 static dict_T *
1286ins_compl_dict_alloc(compl_T *match)
1287{
1288 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1289
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001290 if (dict == NULL)
1291 return NULL;
1292
John Marriott5e6ea922024-11-23 14:01:57 +01001293 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001294 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1295 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1296 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1297 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1298 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1299 dict_add_string(dict, "user_data", (char_u *)"");
1300 else
1301 dict_add_tv(dict, "user_data", &match->cp_user_data);
1302
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001303 return dict;
1304}
1305
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001306/*
1307 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1308 * completion menu is changed.
1309 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001310 static void
1311trigger_complete_changed_event(int cur)
1312{
1313 dict_T *v_event;
1314 dict_T *item;
1315 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001316 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001317
1318 if (recursive)
1319 return;
1320
glepnir40891ba2025-02-10 22:18:00 +01001321 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001322 if (item == NULL)
1323 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001324 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001325 dict_add_dict(v_event, "completed_item", item);
1326 pum_set_event_info(v_event);
1327 dict_set_items_ro(v_event);
1328
1329 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001330 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001331 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001332 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001333 recursive = FALSE;
1334
Bram Moolenaar3075a452021-11-17 15:51:52 +00001335 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001336}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001337#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001338
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001339/*
glepnira218cc62024-06-03 19:32:39 +02001340 * pumitem qsort compare func
1341 */
1342 static int
zeertzjq8e567472024-06-14 20:04:42 +02001343ins_compl_fuzzy_cmp(const void *a, const void *b)
glepnira218cc62024-06-03 19:32:39 +02001344{
1345 const int sa = (*(pumitem_T *)a).pum_score;
1346 const int sb = (*(pumitem_T *)b).pum_score;
zeertzjq8e567472024-06-14 20:04:42 +02001347 const int ia = (*(pumitem_T *)a).pum_idx;
1348 const int ib = (*(pumitem_T *)b).pum_idx;
1349 return sa == sb ? (ia == ib ? 0 : (ia < ib ? -1 : 1)) : (sa < sb ? 1 : -1);
glepnira218cc62024-06-03 19:32:39 +02001350}
1351
1352/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001353 * Build a popup menu to show the completion matches.
1354 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1355 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001356 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001357 static int
1358ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001359{
1360 compl_T *compl;
1361 compl_T *shown_compl = NULL;
1362 int did_find_shown_match = FALSE;
1363 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001364 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001365 int cur = -1;
glepnira218cc62024-06-03 19:32:39 +02001366 int max_fuzzy_score = 0;
zeertzjqaa925ee2024-06-09 18:24:05 +02001367 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001368 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001369 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
1370 int fuzzy_sort = fuzzy_filter && !(cur_cot_flags & COT_NOSORT);
glepnir80b66202024-11-27 21:53:53 +01001371 compl_T *match_head = NULL;
1372 compl_T *match_tail = NULL;
1373 compl_T *match_next = NULL;
glepnire4e4d1c2025-04-02 20:18:25 +02001374 int update_shown_match = fuzzy_filter;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001375
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001376 // Need to build the popup menu list.
1377 compl_match_arraysize = 0;
1378 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001379
glepnira49c0772024-11-30 10:56:30 +01001380 // If the current match is the original text don't find the first
1381 // match after it, don't highlight anything.
1382 if (match_at_original_text(compl_shown_match))
1383 shown_match_ok = TRUE;
1384
glepnire4e4d1c2025-04-02 20:18:25 +02001385 if (fuzzy_filter && ctrl_x_mode_normal() && compl_leader.string == NULL
1386 && compl_shown_match->cp_score > 0)
1387 update_shown_match = FALSE;
1388
glepnira49c0772024-11-30 10:56:30 +01001389 if (compl_leader.string != NULL
1390 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1391 && shown_match_ok == FALSE)
1392 compl_shown_match = compl_no_select ? compl_first_match
1393 : compl_first_match->cp_next;
1394
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001395 do
1396 {
glepnird4088ed2024-12-31 10:55:22 +01001397 compl->cp_in_match_array = FALSE;
zeertzjq551d8c32024-06-05 19:53:32 +02001398 // When 'completeopt' contains "fuzzy" and leader is not NULL or empty,
1399 // set the cp_score for later comparisons.
glepnirf400a0c2025-01-23 19:55:14 +01001400 if (fuzzy_filter && compl_leader.string != NULL && compl_leader.length > 0)
John Marriott5e6ea922024-11-23 14:01:57 +01001401 compl->cp_score = fuzzy_match_str(compl->cp_str.string, compl_leader.string);
glepnira218cc62024-06-03 19:32:39 +02001402
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001403 if (!match_at_original_text(compl)
John Marriott5e6ea922024-11-23 14:01:57 +01001404 && (compl_leader.string == NULL
1405 || ins_compl_equal(compl, compl_leader.string, (int)compl_leader.length)
glepnirf400a0c2025-01-23 19:55:14 +01001406 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001407 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001408 ++compl_match_arraysize;
glepnird4088ed2024-12-31 10:55:22 +01001409 compl->cp_in_match_array = TRUE;
glepnir80b66202024-11-27 21:53:53 +01001410 if (match_head == NULL)
1411 match_head = compl;
1412 else
glepnira49c0772024-11-30 10:56:30 +01001413 match_tail->cp_match_next = compl;
glepnir80b66202024-11-27 21:53:53 +01001414 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001415
glepnirf400a0c2025-01-23 19:55:14 +01001416 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001417 {
1418 if (compl == compl_shown_match || did_find_shown_match)
1419 {
1420 // This item is the shown match or this is the
1421 // first displayed item after the shown match.
1422 compl_shown_match = compl;
1423 did_find_shown_match = TRUE;
1424 shown_match_ok = TRUE;
1425 }
1426 else
1427 // Remember this displayed match for when the
1428 // shown match is just below it.
1429 shown_compl = compl;
1430 cur = i;
1431 }
glepnirf400a0c2025-01-23 19:55:14 +01001432 else if (fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001433 {
1434 if (i == 0)
1435 shown_compl = compl;
1436 // Update the maximum fuzzy score and the shown match
1437 // if the current item's score is higher
glepnire4e4d1c2025-04-02 20:18:25 +02001438 if (fuzzy_sort && compl->cp_score > max_fuzzy_score
1439 && update_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001440 {
1441 did_find_shown_match = TRUE;
1442 max_fuzzy_score = compl->cp_score;
1443 if (!compl_no_select)
1444 compl_shown_match = compl;
1445 }
1446
glepnir3af0a8d2025-02-20 22:06:16 +01001447 if (!shown_match_ok && compl == compl_shown_match)
glepnira49c0772024-11-30 10:56:30 +01001448 {
1449 cur = i;
1450 shown_match_ok = TRUE;
1451 }
1452 }
1453 i++;
glepnir80b66202024-11-27 21:53:53 +01001454 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001455
glepnirf400a0c2025-01-23 19:55:14 +01001456 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001457 {
1458 did_find_shown_match = TRUE;
1459
1460 // When the original text is the shown match don't set
1461 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001462 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001463 shown_match_ok = TRUE;
1464
1465 if (!shown_match_ok && shown_compl != NULL)
1466 {
1467 // The shown match isn't displayed, set it to the
1468 // previously displayed match.
1469 compl_shown_match = shown_compl;
1470 shown_match_ok = TRUE;
1471 }
1472 }
glepnira49c0772024-11-30 10:56:30 +01001473 compl = compl->cp_next;
1474 } while (compl != NULL && !is_first_match(compl));
1475
1476 if (compl_match_arraysize == 0)
1477 return -1;
1478
glepnirc0b7ca42025-02-13 20:27:44 +01001479 if (fuzzy_filter && !fuzzy_sort && !compl_no_select && !shown_match_ok)
1480 {
1481 compl_shown_match = shown_compl;
1482 shown_match_ok = TRUE;
1483 cur = 0;
1484 }
1485
glepnira49c0772024-11-30 10:56:30 +01001486 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1487 if (compl_match_array == NULL)
1488 return -1;
1489
1490 compl = match_head;
1491 i = 0;
1492 while (compl != NULL)
1493 {
glepnir6e199932024-12-14 21:13:27 +01001494 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1495 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001496 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1497 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1498 compl_match_array[i].pum_score = compl->cp_score;
1499 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1500 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001501 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1502 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001503 match_next = compl->cp_match_next;
1504 compl->cp_match_next = NULL;
1505 compl = match_next;
1506 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001507
zeertzjqd65aa1b2025-01-25 15:29:03 +01001508 if (fuzzy_sort && compl_leader.string != NULL && compl_leader.length > 0)
zeertzjq8e567472024-06-14 20:04:42 +02001509 {
1510 for (i = 0; i < compl_match_arraysize; i++)
1511 compl_match_array[i].pum_idx = i;
glepnira218cc62024-06-03 19:32:39 +02001512 // sort by the largest score of fuzzy match
zeertzjq8e567472024-06-14 20:04:42 +02001513 qsort(compl_match_array, (size_t)compl_match_arraysize,
1514 sizeof(pumitem_T), ins_compl_fuzzy_cmp);
glepnir65407ce2024-07-06 16:09:19 +02001515 shown_match_ok = TRUE;
zeertzjq8e567472024-06-14 20:04:42 +02001516 }
glepnira218cc62024-06-03 19:32:39 +02001517
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001518 if (!shown_match_ok) // no displayed match at all
1519 cur = -1;
1520
1521 return cur;
1522}
1523
1524/*
1525 * Show the popup menu for the list of matches.
1526 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1527 */
1528 void
1529ins_compl_show_pum(void)
1530{
1531 int i;
1532 int cur = -1;
1533 colnr_T col;
1534
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001535 if (!pum_wanted() || !pum_enough_matches())
1536 return;
1537
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001538 // Update the screen later, before drawing the popup menu over it.
1539 pum_call_update_screen();
1540
1541 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001542 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001543 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001544 else
1545 {
1546 // popup menu already exists, only need to find the current item.
1547 for (i = 0; i < compl_match_arraysize; ++i)
John Marriott5e6ea922024-11-23 14:01:57 +01001548 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001549 || compl_match_array[i].pum_text
1550 == compl_shown_match->cp_text[CPT_ABBR])
1551 {
1552 cur = i;
1553 break;
1554 }
1555 }
1556
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001557 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001558 {
1559#ifdef FEAT_EVAL
1560 if (compl_started && has_completechanged())
1561 trigger_complete_changed_event(cur);
1562#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001563 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001564 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001565
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001566 // In Replace mode when a $ is displayed at the end of the line only
1567 // part of the screen would be updated. We do need to redraw here.
1568 dollar_vcol = -1;
1569
1570 // Compute the screen column of the start of the completed text.
1571 // Use the cursor to get all wrapping and other settings right.
1572 col = curwin->w_cursor.col;
1573 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001574 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001575 pum_display(compl_match_array, compl_match_arraysize, cur);
1576 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001577
glepnircbb46b42024-02-03 18:11:13 +01001578 // After adding leader, set the current match to shown match.
1579 if (compl_started && compl_curr_match != compl_shown_match)
1580 compl_curr_match = compl_shown_match;
1581
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001582#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001583 if (has_completechanged())
1584 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001585#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001586}
1587
1588#define DICT_FIRST (1) // use just first element in "dict"
1589#define DICT_EXACT (2) // "dict" is the exact name of a file
1590
1591/*
glepnir40c1c332024-06-11 19:37:04 +02001592 * Get current completion leader
1593 */
1594 char_u *
1595ins_compl_leader(void)
1596{
John Marriott5e6ea922024-11-23 14:01:57 +01001597 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1598}
1599
1600/*
1601 * Get current completion leader length
1602 */
1603 size_t
1604ins_compl_leader_len(void)
1605{
1606 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001607}
1608
1609/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001610 * Add any identifiers that match the given pattern "pat" in the list of
1611 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001612 */
1613 static void
1614ins_compl_dictionaries(
1615 char_u *dict_start,
1616 char_u *pat,
1617 int flags, // DICT_FIRST and/or DICT_EXACT
1618 int thesaurus) // Thesaurus completion
1619{
1620 char_u *dict = dict_start;
1621 char_u *ptr;
1622 char_u *buf;
1623 regmatch_T regmatch;
1624 char_u **files;
1625 int count;
1626 int save_p_scs;
1627 int dir = compl_direction;
1628
1629 if (*dict == NUL)
1630 {
1631#ifdef FEAT_SPELL
1632 // When 'dictionary' is empty and spell checking is enabled use
1633 // "spell".
1634 if (!thesaurus && curwin->w_p_spell)
1635 dict = (char_u *)"spell";
1636 else
1637#endif
1638 return;
1639 }
1640
1641 buf = alloc(LSIZE);
1642 if (buf == NULL)
1643 return;
1644 regmatch.regprog = NULL; // so that we can goto theend
1645
1646 // If 'infercase' is set, don't use 'smartcase' here
1647 save_p_scs = p_scs;
1648 if (curbuf->b_p_inf)
1649 p_scs = FALSE;
1650
1651 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1652 // to only match at the start of a line. Otherwise just match the
1653 // pattern. Also need to double backslashes.
1654 if (ctrl_x_mode_line_or_eval())
1655 {
1656 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1657 size_t len;
1658
1659 if (pat_esc == NULL)
1660 goto theend;
1661 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001662 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001663 if (ptr == NULL)
1664 {
1665 vim_free(pat_esc);
1666 goto theend;
1667 }
1668 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1669 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1670 vim_free(pat_esc);
1671 vim_free(ptr);
1672 }
1673 else
1674 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001675 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001676 if (regmatch.regprog == NULL)
1677 goto theend;
1678 }
1679
1680 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1681 regmatch.rm_ic = ignorecase(pat);
1682 while (*dict != NUL && !got_int && !compl_interrupted)
1683 {
1684 // copy one dictionary file name into buf
1685 if (flags == DICT_EXACT)
1686 {
1687 count = 1;
1688 files = &dict;
1689 }
1690 else
1691 {
1692 // Expand wildcards in the dictionary name, but do not allow
1693 // backticks (for security, the 'dict' option may have been set in
1694 // a modeline).
1695 copy_option_part(&dict, buf, LSIZE, ",");
1696# ifdef FEAT_SPELL
1697 if (!thesaurus && STRCMP(buf, "spell") == 0)
1698 count = -1;
1699 else
1700# endif
1701 if (vim_strchr(buf, '`') != NULL
1702 || expand_wildcards(1, &buf, &count, &files,
1703 EW_FILE|EW_SILENT) != OK)
1704 count = 0;
1705 }
1706
1707# ifdef FEAT_SPELL
1708 if (count == -1)
1709 {
1710 // Complete from active spelling. Skip "\<" in the pattern, we
1711 // don't use it as a RE.
1712 if (pat[0] == '\\' && pat[1] == '<')
1713 ptr = pat + 2;
1714 else
1715 ptr = pat;
1716 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1717 }
1718 else
1719# endif
1720 if (count > 0) // avoid warning for using "files" uninit
1721 {
1722 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001723 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001724 if (flags != DICT_EXACT)
1725 FreeWild(count, files);
1726 }
1727 if (flags != 0)
1728 break;
1729 }
1730
1731theend:
1732 p_scs = save_p_scs;
1733 vim_regfree(regmatch.regprog);
1734 vim_free(buf);
1735}
1736
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001737/*
1738 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1739 * skipping the word at 'skip_word'. Returns OK on success.
1740 */
1741 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001742thesaurus_add_words_in_line(
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001743 char_u *fname,
1744 char_u **buf_arg,
1745 int dir,
1746 char_u *skip_word)
1747{
1748 int status = OK;
1749 char_u *ptr;
1750 char_u *wstart;
1751
1752 // Add the other matches on the line
1753 ptr = *buf_arg;
1754 while (!got_int)
1755 {
1756 // Find start of the next word. Skip white
1757 // space and punctuation.
1758 ptr = find_word_start(ptr);
1759 if (*ptr == NUL || *ptr == NL)
1760 break;
1761 wstart = ptr;
1762
1763 // Find end of the word.
1764 if (has_mbyte)
1765 // Japanese words may have characters in
1766 // different classes, only separate words
1767 // with single-byte non-word characters.
1768 while (*ptr != NUL)
1769 {
1770 int l = (*mb_ptr2len)(ptr);
1771
1772 if (l < 2 && !vim_iswordc(*ptr))
1773 break;
1774 ptr += l;
1775 }
1776 else
1777 ptr = find_word_end(ptr);
1778
1779 // Add the word. Skip the regexp match.
1780 if (wstart != skip_word)
1781 {
1782 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001783 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001784 if (status == FAIL)
1785 break;
1786 }
1787 }
1788
1789 *buf_arg = ptr;
1790 return status;
1791}
1792
1793/*
1794 * Process "count" dictionary/thesaurus "files" and add the text matching
1795 * "regmatch".
1796 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001797 static void
1798ins_compl_files(
1799 int count,
1800 char_u **files,
1801 int thesaurus,
1802 int flags,
1803 regmatch_T *regmatch,
1804 char_u *buf,
1805 int *dir)
1806{
1807 char_u *ptr;
1808 int i;
1809 FILE *fp;
1810 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01001811 char_u *leader = NULL;
1812 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01001813 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01001814 int score = 0;
1815 int len = 0;
1816 char_u *line_end = NULL;
1817
1818 if (in_fuzzy_collect)
1819 {
1820 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02001821 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01001822 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001823
1824 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1825 {
1826 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01001827 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001828 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001829 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001830 vim_snprintf((char *)IObuff, IOSIZE,
1831 _("Scanning dictionary: %s"), (char *)files[i]);
1832 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1833 }
1834
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001835 if (fp == NULL)
1836 continue;
1837
1838 // Read dictionary file line by line.
1839 // Check each line for a match.
1840 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001841 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001842 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01001843 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001844 {
glepnirf31cfa22025-03-06 21:59:13 +01001845 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001846 {
glepnirf31cfa22025-03-06 21:59:13 +01001847 ptr = regmatch->startp[0];
1848 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
1849 : find_word_end(ptr);
1850 add_r = ins_compl_add_infercase(regmatch->startp[0],
1851 (int)(ptr - regmatch->startp[0]),
1852 p_ic, files[i], *dir, FALSE, 0);
1853 if (thesaurus)
1854 {
1855 // For a thesaurus, add all the words in the line
1856 ptr = buf;
1857 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
1858 regmatch->startp[0]);
1859 }
1860 if (add_r == OK)
1861 // if dir was BACKWARD then honor it just once
1862 *dir = FORWARD;
1863 else if (add_r == FAIL)
1864 break;
1865 // avoid expensive call to vim_regexec() when at end
1866 // of line
1867 if (*ptr == '\n' || got_int)
1868 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001869 }
glepnirf31cfa22025-03-06 21:59:13 +01001870 }
1871 else if (in_fuzzy_collect && leader_len > 0)
1872 {
1873 line_end = find_line_end(ptr);
1874 while (ptr < line_end)
1875 {
1876 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
1877 {
1878 char_u *end_ptr = ctrl_x_mode_line_or_eval()
1879 ? find_line_end(ptr) : find_word_end(ptr);
1880 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
1881 p_ic, files[i], *dir, FALSE, score);
1882 if (add_r == FAIL)
1883 break;
1884 ptr = end_ptr; // start from next word
1885 if (compl_get_longest && ctrl_x_mode_normal()
1886 && compl_first_match->cp_next
1887 && score == compl_first_match->cp_next->cp_score)
1888 compl_num_bests++;
1889 }
glepnirf31cfa22025-03-06 21:59:13 +01001890 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001891 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001892 line_breakcheck();
1893 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001894 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001895 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001896 }
1897}
1898
1899/*
1900 * Find the start of the next word.
1901 * Returns a pointer to the first char of the word. Also stops at a NUL.
1902 */
1903 char_u *
1904find_word_start(char_u *ptr)
1905{
1906 if (has_mbyte)
1907 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1908 ptr += (*mb_ptr2len)(ptr);
1909 else
1910 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1911 ++ptr;
1912 return ptr;
1913}
1914
1915/*
1916 * Find the end of the word. Assumes it starts inside a word.
1917 * Returns a pointer to just after the word.
1918 */
1919 char_u *
1920find_word_end(char_u *ptr)
1921{
1922 int start_class;
1923
1924 if (has_mbyte)
1925 {
1926 start_class = mb_get_class(ptr);
1927 if (start_class > 1)
1928 while (*ptr != NUL)
1929 {
1930 ptr += (*mb_ptr2len)(ptr);
1931 if (mb_get_class(ptr) != start_class)
1932 break;
1933 }
1934 }
1935 else
1936 while (vim_iswordc(*ptr))
1937 ++ptr;
1938 return ptr;
1939}
1940
1941/*
1942 * Find the end of the line, omitting CR and NL at the end.
1943 * Returns a pointer to just after the line.
1944 */
glepnirdd42b052025-03-08 16:52:55 +01001945 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001946find_line_end(char_u *ptr)
1947{
1948 char_u *s;
1949
1950 s = ptr + STRLEN(ptr);
1951 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1952 --s;
1953 return s;
1954}
1955
1956/*
Girish Palyacbe53192025-04-14 22:13:15 +02001957 * Free a completion item in the list
1958 */
1959 static void
1960ins_compl_item_free(compl_T *match)
1961{
1962 int i;
1963
1964 VIM_CLEAR_STRING(match->cp_str);
1965 // several entries may use the same fname, free it just once.
1966 if (match->cp_flags & CP_FREE_FNAME)
1967 vim_free(match->cp_fname);
1968 for (i = 0; i < CPT_COUNT; ++i)
1969 vim_free(match->cp_text[i]);
1970#ifdef FEAT_EVAL
1971 clear_tv(&match->cp_user_data);
1972#endif
1973 vim_free(match);
1974}
1975
1976/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001977 * Free the list of completions
1978 */
1979 static void
1980ins_compl_free(void)
1981{
1982 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001983
John Marriott5e6ea922024-11-23 14:01:57 +01001984 VIM_CLEAR_STRING(compl_pattern);
1985 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001986
1987 if (compl_first_match == NULL)
1988 return;
1989
1990 ins_compl_del_pum();
1991 pum_clear();
1992
1993 compl_curr_match = compl_first_match;
1994 do
1995 {
1996 match = compl_curr_match;
1997 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02001998 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001999 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002000 compl_first_match = compl_curr_match = NULL;
2001 compl_shown_match = NULL;
2002 compl_old_match = NULL;
2003}
2004
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002005/*
2006 * Reset/clear the completion state.
2007 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002008 void
2009ins_compl_clear(void)
2010{
2011 compl_cont_status = 0;
2012 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002013 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002014 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002015 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002016 compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +01002017 VIM_CLEAR_STRING(compl_pattern);
2018 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002019 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002020 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002021 compl_enter_selects = FALSE;
Girish Palyacbe53192025-04-14 22:13:15 +02002022 cpt_compl_src_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002023#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002024 // clear v:completed_item
2025 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002026#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002027}
2028
2029/*
2030 * Return TRUE when Insert completion is active.
2031 */
2032 int
2033ins_compl_active(void)
2034{
2035 return compl_started;
2036}
2037
2038/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002039 * Return True when wp is the actual completion window
2040 */
2041 int
2042ins_compl_win_active(win_T *wp UNUSED)
2043{
2044 return ins_compl_active()
2045#if defined(FEAT_QUICKFIX)
2046 && (!wp->w_p_pvw
2047# ifdef FEAT_PROP_POPUP
2048 && !(wp->w_popup_flags & POPF_INFO)
2049# endif
2050 )
2051#endif
2052 ;
2053}
2054
2055/*
Girish Palyacbe53192025-04-14 22:13:15 +02002056 * Selected one of the matches. When FALSE, the match was either edited or
2057 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002058 */
2059 int
2060ins_compl_used_match(void)
2061{
2062 return compl_used_match;
2063}
2064
2065/*
2066 * Initialize get longest common string.
2067 */
2068 void
2069ins_compl_init_get_longest(void)
2070{
2071 compl_get_longest = FALSE;
2072}
2073
2074/*
2075 * Returns TRUE when insert completion is interrupted.
2076 */
2077 int
2078ins_compl_interrupted(void)
2079{
2080 return compl_interrupted;
2081}
2082
2083/*
2084 * Returns TRUE if the <Enter> key selects a match in the completion popup
2085 * menu.
2086 */
2087 int
2088ins_compl_enter_selects(void)
2089{
2090 return compl_enter_selects;
2091}
2092
2093/*
2094 * Return the column where the text starts that is being completed
2095 */
2096 colnr_T
2097ins_compl_col(void)
2098{
2099 return compl_col;
2100}
2101
2102/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002103 * Return the length in bytes of the text being completed
2104 */
2105 int
2106ins_compl_len(void)
2107{
2108 return compl_length;
2109}
2110
2111/*
glepnir94a045e2025-03-01 16:12:23 +01002112 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2113 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002114 */
2115 static int
2116ins_compl_has_preinsert(void)
2117{
glepnira2c55592025-02-28 17:43:42 +01002118 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002119 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2120 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002121}
2122
2123/*
2124 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2125 * the `compl_ins_end_col` range.
2126 */
2127 int
2128ins_compl_preinsert_effect(void)
2129{
2130 if (!ins_compl_has_preinsert())
2131 return FALSE;
2132
2133 return curwin->w_cursor.col < compl_ins_end_col;
2134}
2135
2136/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002137 * Delete one character before the cursor and show the subset of the matches
2138 * that match the word that is now before the cursor.
2139 * Returns the character to be used, NUL if the work is done and another char
2140 * to be got from the user.
2141 */
2142 int
2143ins_compl_bs(void)
2144{
2145 char_u *line;
2146 char_u *p;
2147
glepniredd4ac32025-01-29 18:53:51 +01002148 if (ins_compl_preinsert_effect())
2149 ins_compl_delete();
2150
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002151 line = ml_get_curline();
2152 p = line + curwin->w_cursor.col;
2153 MB_PTR_BACK(line, p);
2154
2155 // Stop completion when the whole word was deleted. For Omni completion
2156 // allow the word to be deleted, we won't match everything.
2157 // Respect the 'backspace' option.
2158 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002159 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2160 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002161 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2162 - compl_length < 0))
2163 return K_BS;
2164
2165 // Deleted more than what was used to find matches or didn't finish
2166 // finding all matches: need to look for matches all over again.
2167 if (curwin->w_cursor.col <= compl_col + compl_length
2168 || ins_compl_need_restart())
2169 ins_compl_restart();
2170
John Marriott5e6ea922024-11-23 14:01:57 +01002171 VIM_CLEAR_STRING(compl_leader);
2172 compl_leader.length = (size_t)((p - line) - compl_col);
2173 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2174 if (compl_leader.string == NULL)
2175 {
2176 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002177 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002178 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002179
2180 ins_compl_new_leader();
2181 if (compl_shown_match != NULL)
2182 // Make sure current match is not a hidden item.
2183 compl_curr_match = compl_shown_match;
2184 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002185}
2186
2187/*
2188 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2189 * be called.
2190 */
2191 static int
2192ins_compl_need_restart(void)
2193{
2194 // Return TRUE if we didn't complete finding matches or when the
2195 // 'completefunc' returned "always" in the "refresh" dictionary item.
2196 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002197 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002198 && compl_opt_refresh_always);
2199}
2200
2201/*
2202 * Called after changing "compl_leader".
2203 * Show the popup menu with a different set of matches.
2204 * May also search for matches again if the previous search was interrupted.
2205 */
2206 static void
2207ins_compl_new_leader(void)
2208{
2209 ins_compl_del_pum();
2210 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002211 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002212 compl_used_match = FALSE;
2213
2214 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002215 {
John Marriott5e6ea922024-11-23 14:01:57 +01002216 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002217 if (is_cpt_func_refresh_always())
2218 cpt_compl_refresh();
2219 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002220 else
2221 {
2222#ifdef FEAT_SPELL
2223 spell_bad_len = 0; // need to redetect bad word
2224#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002225 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002226 // the popup menu display the changed text before the cursor. Set
2227 // "compl_restarting" to avoid that the first match is inserted.
2228 pum_call_update_screen();
2229#ifdef FEAT_GUI
2230 if (gui.in_use)
2231 {
2232 // Show the cursor after the match, not after the redrawn text.
2233 setcursor();
2234 out_flush_cursor(FALSE, FALSE);
2235 }
2236#endif
2237 compl_restarting = TRUE;
2238 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2239 compl_cont_status = 0;
2240 compl_restarting = FALSE;
2241 }
2242
glepnir44180412025-02-20 22:09:48 +01002243 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002244
2245 // Show the popup menu with a different set of matches.
2246 ins_compl_show_pum();
2247
2248 // Don't let Enter select the original text when there is no popup menu.
2249 if (compl_match_array == NULL)
2250 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002251 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
2252 ins_compl_insert(FALSE, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002253}
2254
2255/*
2256 * Return the length of the completion, from the completion start column to
2257 * the cursor column. Making sure it never goes below zero.
2258 */
2259 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002260get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002261{
2262 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002263 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002264}
2265
2266/*
2267 * Append one character to the match leader. May reduce the number of
2268 * matches.
2269 */
2270 void
2271ins_compl_addleader(int c)
2272{
2273 int cc;
2274
glepniredd4ac32025-01-29 18:53:51 +01002275 if (ins_compl_preinsert_effect())
2276 ins_compl_delete();
2277
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002278 if (stop_arrow() == FAIL)
2279 return;
2280 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2281 {
2282 char_u buf[MB_MAXBYTES + 1];
2283
2284 (*mb_char2bytes)(c, buf);
2285 buf[cc] = NUL;
2286 ins_char_bytes(buf, cc);
2287 if (compl_opt_refresh_always)
2288 AppendToRedobuff(buf);
2289 }
2290 else
2291 {
2292 ins_char(c);
2293 if (compl_opt_refresh_always)
2294 AppendCharToRedobuff(c);
2295 }
2296
2297 // If we didn't complete finding matches we must search again.
2298 if (ins_compl_need_restart())
2299 ins_compl_restart();
2300
2301 // When 'always' is set, don't reset compl_leader. While completing,
2302 // cursor doesn't point original position, changing compl_leader would
2303 // break redo.
2304 if (!compl_opt_refresh_always)
2305 {
John Marriott5e6ea922024-11-23 14:01:57 +01002306 VIM_CLEAR_STRING(compl_leader);
2307 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2308 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2309 compl_leader.length);
2310 if (compl_leader.string == NULL)
2311 {
2312 compl_leader.length = 0;
2313 return;
2314 }
2315
2316 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002317 }
2318}
2319
2320/*
2321 * Setup for finding completions again without leaving CTRL-X mode. Used when
2322 * BS or a key was typed while still searching for matches.
2323 */
2324 static void
2325ins_compl_restart(void)
2326{
2327 ins_compl_free();
2328 compl_started = FALSE;
2329 compl_matches = 0;
2330 compl_cont_status = 0;
2331 compl_cont_mode = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02002332 cpt_compl_src_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002333}
2334
2335/*
2336 * Set the first match, the original text.
2337 */
2338 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002339ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002340{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002341 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002342 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2343 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002344 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002345 {
John Marriott5e6ea922024-11-23 14:01:57 +01002346 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002347 if (p != NULL)
2348 {
John Marriott5e6ea922024-11-23 14:01:57 +01002349 VIM_CLEAR_STRING(compl_first_match->cp_str);
2350 compl_first_match->cp_str.string = p;
2351 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002352 }
2353 }
2354 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002355 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002356 {
John Marriott5e6ea922024-11-23 14:01:57 +01002357 char_u *p = vim_strnsave(str, len);
2358 if (p != NULL)
2359 {
2360 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2361 compl_first_match->cp_prev->cp_str.string = p;
2362 compl_first_match->cp_prev->cp_str.length = len;
2363 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002364 }
2365}
2366
2367/*
2368 * Append one character to the match leader. May reduce the number of
2369 * matches.
2370 */
2371 void
2372ins_compl_addfrommatch(void)
2373{
2374 char_u *p;
2375 int len = (int)curwin->w_cursor.col - (int)compl_col;
2376 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002377
John Marriott5e6ea922024-11-23 14:01:57 +01002378 p = compl_shown_match->cp_str.string;
2379 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002380 {
John Marriott5e6ea922024-11-23 14:01:57 +01002381 size_t plen;
2382 compl_T *cp;
2383
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002384 // When still at the original match use the first entry that matches
2385 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002386 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002387 return;
2388
2389 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002390 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002391 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002392 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002393 {
John Marriott5e6ea922024-11-23 14:01:57 +01002394 if (compl_leader.string == NULL
2395 || ins_compl_equal(cp, compl_leader.string,
2396 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002397 {
John Marriott5e6ea922024-11-23 14:01:57 +01002398 p = cp->cp_str.string;
2399 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002400 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002401 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002402 }
John Marriott5e6ea922024-11-23 14:01:57 +01002403 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002404 return;
2405 }
2406 p += len;
2407 c = PTR2CHAR(p);
2408 ins_compl_addleader(c);
2409}
2410
2411/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002412 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002413 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2414 * compl_cont_mode and compl_cont_status.
2415 * Returns TRUE when the character is not to be inserted.
2416 */
2417 static int
2418set_ctrl_x_mode(int c)
2419{
2420 int retval = FALSE;
2421
2422 switch (c)
2423 {
2424 case Ctrl_E:
2425 case Ctrl_Y:
2426 // scroll the window one line up or down
2427 ctrl_x_mode = CTRL_X_SCROLL;
2428 if (!(State & REPLACE_FLAG))
2429 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2430 else
2431 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2432 edit_submode_pre = NULL;
2433 showmode();
2434 break;
2435 case Ctrl_L:
2436 // complete whole line
2437 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2438 break;
2439 case Ctrl_F:
2440 // complete filenames
2441 ctrl_x_mode = CTRL_X_FILES;
2442 break;
2443 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002444 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002445 ctrl_x_mode = CTRL_X_DICTIONARY;
2446 break;
2447 case Ctrl_R:
2448 // Register insertion without exiting CTRL-X mode
2449 // Simply allow ^R to happen without affecting ^X mode
2450 break;
2451 case Ctrl_T:
2452 // complete words from a thesaurus
2453 ctrl_x_mode = CTRL_X_THESAURUS;
2454 break;
2455#ifdef FEAT_COMPL_FUNC
2456 case Ctrl_U:
2457 // user defined completion
2458 ctrl_x_mode = CTRL_X_FUNCTION;
2459 break;
2460 case Ctrl_O:
2461 // omni completion
2462 ctrl_x_mode = CTRL_X_OMNI;
2463 break;
2464#endif
2465 case 's':
2466 case Ctrl_S:
2467 // complete spelling suggestions
2468 ctrl_x_mode = CTRL_X_SPELL;
2469#ifdef FEAT_SPELL
2470 ++emsg_off; // Avoid getting the E756 error twice.
2471 spell_back_to_badword();
2472 --emsg_off;
2473#endif
2474 break;
2475 case Ctrl_RSB:
2476 // complete tag names
2477 ctrl_x_mode = CTRL_X_TAGS;
2478 break;
2479#ifdef FEAT_FIND_ID
2480 case Ctrl_I:
2481 case K_S_TAB:
2482 // complete keywords from included files
2483 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2484 break;
2485 case Ctrl_D:
2486 // complete definitions from included files
2487 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2488 break;
2489#endif
2490 case Ctrl_V:
2491 case Ctrl_Q:
2492 // complete vim commands
2493 ctrl_x_mode = CTRL_X_CMDLINE;
2494 break;
2495 case Ctrl_Z:
2496 // stop completion
2497 ctrl_x_mode = CTRL_X_NORMAL;
2498 edit_submode = NULL;
2499 showmode();
2500 retval = TRUE;
2501 break;
2502 case Ctrl_P:
2503 case Ctrl_N:
2504 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2505 // just started ^X mode, or there were enough ^X's to cancel
2506 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2507 // do normal expansion when interrupting a different mode (say
2508 // ^X^F^X^P or ^P^X^X^P, see below)
2509 // nothing changes if interrupting mode 0, (eg, the flag
2510 // doesn't change when going to ADDING mode -- Acevedo
2511 if (!(compl_cont_status & CONT_INTRPT))
2512 compl_cont_status |= CONT_LOCAL;
2513 else if (compl_cont_mode != 0)
2514 compl_cont_status &= ~CONT_LOCAL;
2515 // FALLTHROUGH
2516 default:
2517 // If we have typed at least 2 ^X's... for modes != 0, we set
2518 // compl_cont_status = 0 (eg, as if we had just started ^X
2519 // mode).
2520 // For mode 0, we set "compl_cont_mode" to an impossible
2521 // value, in both cases ^X^X can be used to restart the same
2522 // mode (avoiding ADDING mode).
2523 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2524 // 'complete' and local ^P expansions respectively.
2525 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2526 // mode -- Acevedo
2527 if (c == Ctrl_X)
2528 {
2529 if (compl_cont_mode != 0)
2530 compl_cont_status = 0;
2531 else
2532 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2533 }
2534 ctrl_x_mode = CTRL_X_NORMAL;
2535 edit_submode = NULL;
2536 showmode();
2537 break;
2538 }
2539
2540 return retval;
2541}
2542
2543/*
glepnir1c5a1202024-12-04 20:27:34 +01002544 * Trigger CompleteDone event and adds relevant information to v:event
2545 */
2546 static void
2547trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2548{
2549#if defined(FEAT_EVAL)
2550 save_v_event_T save_v_event;
2551 dict_T *v_event = get_v_event(&save_v_event);
2552 char_u *mode_str = NULL;
2553
2554 mode = mode & ~CTRL_X_WANT_IDENT;
2555 if (ctrl_x_mode_names[mode])
2556 mode_str = (char_u *)ctrl_x_mode_names[mode];
2557
2558 (void)dict_add_string(v_event, "complete_word",
2559 word == NULL ? (char_u *)"" : word);
2560 (void)dict_add_string(v_event, "complete_type",
2561 mode_str != NULL ? mode_str : (char_u *)"");
2562
2563 dict_set_items_ro(v_event);
2564#endif
2565 ins_apply_autocmds(EVENT_COMPLETEDONE);
2566
2567#if defined(FEAT_EVAL)
2568 restore_v_event(v_event, &save_v_event);
2569#endif
2570}
2571
2572/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002573 * Stop insert completion mode
2574 */
2575 static int
2576ins_compl_stop(int c, int prev_mode, int retval)
2577{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002578 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002579 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002580
glepnir84a75032025-03-15 09:59:22 +01002581 // Remove pre-inserted text when present.
2582 if (ins_compl_preinsert_effect())
2583 ins_compl_delete();
2584
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002585 // Get here when we have finished typing a sequence of ^N and
2586 // ^P or other completion characters in CTRL-X mode. Free up
2587 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002588 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002589 {
glepnir40891ba2025-02-10 22:18:00 +01002590 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002591
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002592 // If any of the original typed text has been changed, eg when
2593 // ignorecase is set, we must add back-spaces to the redo
2594 // buffer. We add as few as necessary to delete just the part
2595 // of the original text that has changed.
2596 // When using the longest match, edited the match or used
2597 // CTRL-E then don't use the current match.
2598 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002599 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002600 ins_compl_fixRedoBufForLeader(ptr);
2601 }
2602
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002603 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002604
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002605 // When completing whole lines: fix indent for 'cindent'.
2606 // Otherwise, break line if it's too long.
2607 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2608 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002609 // re-indent the current line
2610 if (want_cindent)
2611 {
2612 do_c_expr_indent();
2613 want_cindent = FALSE; // don't do it again
2614 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002615 }
2616 else
2617 {
2618 int prev_col = curwin->w_cursor.col;
2619
2620 // put the cursor on the last char, for 'tw' formatting
2621 if (prev_col > 0)
2622 dec_cursor();
2623 // only format when something was inserted
2624 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2625 insertchar(NUL, 0, -1);
2626 if (prev_col > 0
2627 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2628 inc_cursor();
2629 }
2630
2631 // If the popup menu is displayed pressing CTRL-Y means accepting
2632 // the selection without inserting anything. When
2633 // compl_enter_selects is set the Enter key does the same.
2634 if ((c == Ctrl_Y || (compl_enter_selects
2635 && (c == CAR || c == K_KENTER || c == NL)))
2636 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002637 {
2638 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002639 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002640 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002641
2642 // CTRL-E means completion is Ended, go back to the typed text.
2643 // but only do this, if the Popup is still visible
2644 if (c == Ctrl_E)
2645 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002646 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002647 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002648
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002649 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002650 if (compl_leader.string != NULL)
2651 {
2652 p = compl_leader.string;
2653 plen = compl_leader.length;
2654 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002655 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002656 {
2657 p = compl_orig_text.string;
2658 plen = compl_orig_text.length;
2659 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002660 if (p != NULL)
2661 {
2662 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002663
John Marriott5e6ea922024-11-23 14:01:57 +01002664 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002665 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002666 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002667 retval = TRUE;
2668 }
2669
glepnir001c26c2025-02-02 09:36:22 +01002670 if ((c == Ctrl_W || c == Ctrl_U) && ins_compl_preinsert_effect())
2671 ins_compl_delete();
2672
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002673 auto_format(FALSE, TRUE);
2674
2675 // Trigger the CompleteDonePre event to give scripts a chance to
2676 // act upon the completion before clearing the info, and restore
2677 // ctrl_x_mode, so that complete_info() can be used.
2678 ctrl_x_mode = prev_mode;
2679 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2680
2681 ins_compl_free();
2682 compl_started = FALSE;
2683 compl_matches = 0;
2684 if (!shortmess(SHM_COMPLETIONMENU))
2685 msg_clr_cmdline(); // necessary for "noshowmode"
2686 ctrl_x_mode = CTRL_X_NORMAL;
2687 compl_enter_selects = FALSE;
2688 if (edit_submode != NULL)
2689 {
2690 edit_submode = NULL;
2691 showmode();
2692 }
2693
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002694 if (c == Ctrl_C && cmdwin_type != 0)
2695 // Avoid the popup menu remains displayed when leaving the
2696 // command line window.
2697 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002698 // Indent now if a key was typed that is in 'cinkeys'.
2699 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2700 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002701 // Trigger the CompleteDone event to give scripts a chance to act
2702 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002703 trigger_complete_done_event(prev_mode, word);
2704 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002705
2706 return retval;
2707}
2708
2709/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002710 * Prepare for Insert mode completion, or stop it.
2711 * Called just after typing a character in Insert mode.
2712 * Returns TRUE when the character is not to be inserted;
2713 */
2714 int
2715ins_compl_prep(int c)
2716{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002717 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002718 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002719
2720 // Forget any previous 'special' messages if this is actually
2721 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2722 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2723 edit_submode_extra = NULL;
2724
zeertzjq440d4cb2023-03-02 17:51:32 +00002725 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002726 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002727 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002728 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002729 return retval;
2730
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002731#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002732 // Ignore mouse events in a popup window
2733 if (is_mouse_key(c))
2734 {
2735 // Ignore drag and release events, the position does not need to be in
2736 // the popup and it may have just closed.
2737 if (c == K_LEFTRELEASE
2738 || c == K_LEFTRELEASE_NM
2739 || c == K_MIDDLERELEASE
2740 || c == K_RIGHTRELEASE
2741 || c == K_X1RELEASE
2742 || c == K_X2RELEASE
2743 || c == K_LEFTDRAG
2744 || c == K_MIDDLEDRAG
2745 || c == K_RIGHTDRAG
2746 || c == K_X1DRAG
2747 || c == K_X2DRAG)
2748 return retval;
2749 if (popup_visible)
2750 {
2751 int row = mouse_row;
2752 int col = mouse_col;
2753 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2754
2755 if (wp != NULL && WIN_IS_POPUP(wp))
2756 return retval;
2757 }
2758 }
2759#endif
2760
zeertzjqdca29d92021-08-31 19:12:51 +02002761 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2762 {
2763 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2764 || !vim_is_ctrl_x_key(c))
2765 {
2766 // Not starting another completion mode.
2767 ctrl_x_mode = CTRL_X_CMDLINE;
2768
2769 // CTRL-X CTRL-Z should stop completion without inserting anything
2770 if (c == Ctrl_Z)
2771 retval = TRUE;
2772 }
2773 else
2774 {
2775 ctrl_x_mode = CTRL_X_CMDLINE;
2776
2777 // Other CTRL-X keys first stop completion, then start another
2778 // completion mode.
2779 ins_compl_prep(' ');
2780 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2781 }
2782 }
2783
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002784 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002785 if (ctrl_x_mode_not_defined_yet()
2786 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002787 {
zeertzjq529b9ad2024-06-05 20:27:06 +02002788 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002789 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002790 }
2791
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002792 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002793 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2794 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002795 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002796 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002797 {
2798 // We're already in CTRL-X mode, do we stay in it?
2799 if (!vim_is_ctrl_x_key(c))
2800 {
glepnir40891ba2025-02-10 22:18:00 +01002801 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002802 edit_submode = NULL;
2803 }
2804 showmode();
2805 }
2806
2807 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2808 {
2809 // Show error message from attempted keyword completion (probably
2810 // 'Pattern not found') until another key is hit, then go back to
2811 // showing what mode we are in.
2812 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002813 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002814 && c != Ctrl_R && !ins_compl_pum_key(c))
2815 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002816 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002817 }
2818 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2819 // Trigger the CompleteDone event to give scripts a chance to act
2820 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01002821 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002822
LemonBoy2bf52dd2022-04-09 18:17:34 +01002823 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002824
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002825 // reset continue_* if we left expansion-mode, if we stay they'll be
2826 // (re)set properly in ins_complete()
2827 if (!vim_is_ctrl_x_key(c))
2828 {
2829 compl_cont_status = 0;
2830 compl_cont_mode = 0;
2831 }
2832
2833 return retval;
2834}
2835
2836/*
2837 * Fix the redo buffer for the completion leader replacing some of the typed
2838 * text. This inserts backspaces and appends the changed text.
2839 * "ptr" is the known leader text or NUL.
2840 */
2841 static void
2842ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2843{
John Marriott5e6ea922024-11-23 14:01:57 +01002844 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002845 char_u *p;
2846 char_u *ptr = ptr_arg;
2847
2848 if (ptr == NULL)
2849 {
John Marriott5e6ea922024-11-23 14:01:57 +01002850 if (compl_leader.string != NULL)
2851 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002852 else
2853 return; // nothing to do
2854 }
John Marriott5e6ea922024-11-23 14:01:57 +01002855 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002856 {
John Marriott5e6ea922024-11-23 14:01:57 +01002857 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01002858 // Find length of common prefix between original text and new completion
2859 while (p[len] != NUL && p[len] == ptr[len])
2860 len++;
2861 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002862 if (len > 0)
2863 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01002864 // Add backspace characters for each remaining character in
2865 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002866 for (p += len; *p != NUL; MB_PTR_ADV(p))
2867 AppendCharToRedobuff(K_BS);
2868 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002869 if (ptr != NULL)
2870 AppendToRedobuffLit(ptr + len, -1);
2871}
2872
2873/*
2874 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2875 * (depending on flag) starting from buf and looking for a non-scanned
2876 * buffer (other than curbuf). curbuf is special, if it is called with
2877 * buf=curbuf then it has to be the first call for a given flag/expansion.
2878 *
2879 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2880 */
2881 static buf_T *
2882ins_compl_next_buf(buf_T *buf, int flag)
2883{
2884 static win_T *wp = NULL;
glepnir40891ba2025-02-10 22:18:00 +01002885 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002886
2887 if (flag == 'w') // just windows
2888 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01002889 if (buf == curbuf || !win_valid(wp))
2890 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002891 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01002892
2893 while (TRUE)
2894 {
2895 // Move to next window (wrap to first window if at the end)
2896 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
2897 // Break if we're back at start or found an unscanned buffer
2898 if (wp == curwin || !wp->w_buffer->b_scanned)
2899 break;
2900 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002901 buf = wp->w_buffer;
2902 }
2903 else
glepnir40891ba2025-02-10 22:18:00 +01002904 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002905 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2906 // (unlisted buffers)
2907 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01002908 while (TRUE)
2909 {
2910 // Move to next buffer (wrap to first buffer if at the end)
2911 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
2912 // Break if we're back at start buffer
2913 if (buf == curbuf)
2914 break;
2915
2916 // Check buffer conditions based on flag
2917 if (flag == 'U')
2918 skip_buffer = buf->b_p_bl;
2919 else
2920 skip_buffer = !buf->b_p_bl ||
2921 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
2922
2923 // Break if we found a buffer that matches our criteria
2924 if (!skip_buffer && !buf->b_scanned)
2925 break;
2926 }
2927 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002928 return buf;
2929}
2930
2931#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002932
2933# ifdef FEAT_EVAL
2934static callback_T cfu_cb; // 'completefunc' callback function
2935static callback_T ofu_cb; // 'omnifunc' callback function
2936static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2937# endif
2938
2939/*
2940 * Copy a global callback function to a buffer local callback.
2941 */
2942 static void
2943copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2944{
2945 free_callback(bufcb);
2946 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2947 copy_callback(bufcb, globcb);
2948}
2949
2950/*
2951 * Parse the 'completefunc' option value and set the callback function.
2952 * Invoked when the 'completefunc' option is set. The option value can be a
2953 * name of a function (string), or function(<name>) or funcref(<name>) or a
2954 * lambda expression.
2955 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002956 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002957did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002958{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002959 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
2960 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002961
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002962 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002963
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002964 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002965}
2966
2967/*
2968 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002969 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002970 */
2971 void
2972set_buflocal_cfu_callback(buf_T *buf UNUSED)
2973{
2974# ifdef FEAT_EVAL
2975 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2976# endif
2977}
2978
2979/*
2980 * Parse the 'omnifunc' option value and set the callback function.
2981 * Invoked when the 'omnifunc' option is set. The option value can be a
2982 * name of a function (string), or function(<name>) or funcref(<name>) or a
2983 * lambda expression.
2984 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002985 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00002986did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002987{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002988 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
2989 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002990
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00002991 set_buflocal_ofu_callback(curbuf);
2992 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002993}
2994
2995/*
2996 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002997 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002998 */
2999 void
3000set_buflocal_ofu_callback(buf_T *buf UNUSED)
3001{
3002# ifdef FEAT_EVAL
3003 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3004# endif
3005}
3006
3007/*
3008 * Parse the 'thesaurusfunc' option value and set the callback function.
3009 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3010 * name of a function (string), or function(<name>) or funcref(<name>) or a
3011 * lambda expression.
3012 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003013 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003014did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003015{
3016 int retval;
3017
zeertzjq6eda2692024-11-03 09:23:33 +01003018 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003019 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003020 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3021 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003022 else
3023 {
3024 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003025 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003026 // when using :set, free the local callback
3027 if (!(args->os_flags & OPT_GLOBAL))
3028 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003029 }
3030
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003031 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003032}
3033
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003034/*
3035 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003036 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003037 */
3038 int
3039set_ref_in_insexpand_funcs(int copyID)
3040{
3041 int abort = FALSE;
3042
3043 abort = set_ref_in_callback(&cfu_cb, copyID);
3044 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3045 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3046
3047 return abort;
3048}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003049
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003050/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003051 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003052 */
3053 static char_u *
3054get_complete_funcname(int type)
3055{
3056 switch (type)
3057 {
3058 case CTRL_X_FUNCTION:
3059 return curbuf->b_p_cfu;
3060 case CTRL_X_OMNI:
3061 return curbuf->b_p_ofu;
3062 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003063 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003064 default:
3065 return (char_u *)"";
3066 }
3067}
3068
3069/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003070 * Get the callback to use for insert mode completion.
3071 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003072 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003073get_insert_callback(int type)
3074{
3075 if (type == CTRL_X_FUNCTION)
3076 return &curbuf->b_cfu_cb;
3077 if (type == CTRL_X_OMNI)
3078 return &curbuf->b_ofu_cb;
3079 // CTRL_X_THESAURUS
3080 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3081}
3082
3083/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003084 * Execute user defined complete function 'completefunc', 'omnifunc' or
3085 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003086 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3087 * Callback function "cb" is set if triggered by a function in the 'cpt'
3088 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003089 */
3090 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003091expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003092{
3093 list_T *matchlist = NULL;
3094 dict_T *matchdict = NULL;
3095 typval_T args[3];
3096 char_u *funcname;
3097 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003098 typval_T rettv;
3099 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003100 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003101 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003102
Girish Palyacbe53192025-04-14 22:13:15 +02003103 if (!is_cpt_function)
3104 {
3105 funcname = get_complete_funcname(type);
3106 if (*funcname == NUL)
3107 return;
3108 cb = get_insert_callback(type);
3109 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003110
3111 // Call 'completefunc' to obtain the list of matches.
3112 args[0].v_type = VAR_NUMBER;
3113 args[0].vval.v_number = 0;
3114 args[1].v_type = VAR_STRING;
3115 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3116 args[2].v_type = VAR_UNKNOWN;
3117
3118 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003119 // Lock the text to avoid weird things from happening. Also disallow
3120 // switching to another window, it should not be needed and may end up in
3121 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003122 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003123
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003124 retval = call_callback(cb, 0, &rettv, 2, args);
3125
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003126 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003127 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003128 {
3129 switch (rettv.v_type)
3130 {
3131 case VAR_LIST:
3132 matchlist = rettv.vval.v_list;
3133 break;
3134 case VAR_DICT:
3135 matchdict = rettv.vval.v_dict;
3136 break;
3137 case VAR_SPECIAL:
3138 if (rettv.vval.v_number == VVAL_NONE)
3139 compl_opt_suppress_empty = TRUE;
3140 // FALLTHROUGH
3141 default:
3142 // TODO: Give error message?
3143 clear_tv(&rettv);
3144 break;
3145 }
3146 }
zeertzjqcfe45652022-05-27 17:26:55 +01003147 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003148
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003149 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003150 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003151 validate_cursor();
3152 if (!EQUAL_POS(curwin->w_cursor, pos))
3153 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003154 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003155 goto theend;
3156 }
3157
3158 if (matchlist != NULL)
3159 ins_compl_add_list(matchlist);
3160 else if (matchdict != NULL)
3161 ins_compl_add_dict(matchdict);
3162
3163theend:
3164 // Restore State, it might have been changed.
3165 State = save_State;
3166
3167 if (matchdict != NULL)
3168 dict_unref(matchdict);
3169 if (matchlist != NULL)
3170 list_unref(matchlist);
3171}
3172#endif // FEAT_COMPL_FUNC
3173
3174#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003175
3176 static inline int
3177get_user_highlight_attr(char_u *hlname)
3178{
3179 if (hlname != NULL && *hlname != NUL)
3180 return syn_name2attr(hlname);
3181 return -1;
3182}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003183/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003184 * Add a match to the list of matches from a typeval_T.
3185 * If the given string is already in the list of completions, then return
3186 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3187 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003188 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003189 */
3190 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003191ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003192{
3193 char_u *word;
3194 int dup = FALSE;
3195 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003196 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003197 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003198 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003199 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003200 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003201 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003202 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003203
Bram Moolenaar08928322020-01-04 14:32:48 +01003204 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003205 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3206 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003207 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3208 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3209 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3210 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3211 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003212
glepnir0fe17f82024-10-08 22:26:44 +02003213 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003214 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003215
3216 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003217 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003218
Bram Moolenaard61efa52022-07-23 09:52:04 +01003219 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3220 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3221 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003222 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003223 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3224 dup = dict_get_number(tv->vval.v_dict, "dup");
3225 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3226 empty = dict_get_number(tv->vval.v_dict, "empty");
3227 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3228 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003229 flags |= CP_EQUAL;
3230 }
3231 else
3232 {
3233 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003234 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003235 }
3236 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003237 {
3238 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003239 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003240 }
glepnir508e7852024-07-25 21:39:08 +02003241 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003242 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003243 if (status != OK)
3244 clear_tv(&user_data);
3245 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003246}
3247
3248/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003249 * Add completions from a list.
3250 */
3251 static void
3252ins_compl_add_list(list_T *list)
3253{
3254 listitem_T *li;
3255 int dir = compl_direction;
3256
3257 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003258 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003259 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003260 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003261 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003262 // if dir was BACKWARD then honor it just once
3263 dir = FORWARD;
3264 else if (did_emsg)
3265 break;
3266 }
3267}
3268
3269/*
3270 * Add completions from a dict.
3271 */
3272 static void
3273ins_compl_add_dict(dict_T *dict)
3274{
3275 dictitem_T *di_refresh;
3276 dictitem_T *di_words;
3277
3278 // Check for optional "refresh" item.
3279 compl_opt_refresh_always = FALSE;
3280 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3281 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3282 {
3283 char_u *v = di_refresh->di_tv.vval.v_string;
3284
3285 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3286 compl_opt_refresh_always = TRUE;
3287 }
3288
3289 // Add completions from a "words" list.
3290 di_words = dict_find(dict, (char_u *)"words", 5);
3291 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3292 ins_compl_add_list(di_words->di_tv.vval.v_list);
3293}
3294
3295/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003296 * Start completion for the complete() function.
3297 * "startcol" is where the matched text starts (1 is first column).
3298 * "list" is the list of matches.
3299 */
3300 static void
3301set_completion(colnr_T startcol, list_T *list)
3302{
3303 int save_w_wrow = curwin->w_wrow;
3304 int save_w_leftcol = curwin->w_leftcol;
3305 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003306 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003307 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3308 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3309 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003310
3311 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003312 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003313 ins_compl_prep(' ');
3314 ins_compl_clear();
3315 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003316 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003317
3318 compl_direction = FORWARD;
3319 if (startcol > curwin->w_cursor.col)
3320 startcol = curwin->w_cursor.col;
3321 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003322 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003323 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3324 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003325 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3326 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003327 if (p_ic)
3328 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003329 if (compl_orig_text.string == NULL)
3330 {
3331 compl_orig_text.length = 0;
3332 return;
3333 }
3334 compl_orig_text.length = (size_t)compl_length;
3335 if (ins_compl_add(compl_orig_text.string,
3336 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
glepnirf31cfa22025-03-06 21:59:13 +01003337 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003338 return;
3339
3340 ctrl_x_mode = CTRL_X_EVAL;
3341
3342 ins_compl_add_list(list);
3343 compl_matches = ins_compl_make_cyclic();
3344 compl_started = TRUE;
3345 compl_used_match = TRUE;
3346 compl_cont_status = 0;
3347
3348 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003349 int no_select = compl_no_select || compl_longest;
3350 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003351 {
3352 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003353 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003354 // Down/Up has no real effect.
3355 ins_complete(K_UP, FALSE);
3356 }
3357 else
3358 ins_complete(Ctrl_N, FALSE);
3359 compl_enter_selects = compl_no_insert;
3360
3361 // Lazily show the popup menu, unless we got interrupted.
3362 if (!compl_interrupted)
3363 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003364 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003365 out_flush();
3366}
3367
3368/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003369 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003370 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003371 void
3372f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003373{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003374 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003375
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003376 if (in_vim9script()
3377 && (check_for_number_arg(argvars, 0) == FAIL
3378 || check_for_list_arg(argvars, 1) == FAIL))
3379 return;
3380
Bram Moolenaar24959102022-05-07 20:01:16 +01003381 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003382 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003383 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003384 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003385 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003386
3387 // Check for undo allowed here, because if something was already inserted
3388 // the line was already saved for undo and this check isn't done.
3389 if (!undo_allowed())
3390 return;
3391
Bram Moolenaard83392a2022-09-01 12:22:46 +01003392 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003393 {
3394 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
3395 if (startcol > 0)
3396 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003397 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003398}
3399
3400/*
3401 * "complete_add()" function
3402 */
3403 void
3404f_complete_add(typval_T *argvars, typval_T *rettv)
3405{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003406 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003407 return;
3408
Bram Moolenaar440cf092021-04-03 20:13:30 +02003409 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003410}
3411
3412/*
3413 * "complete_check()" function
3414 */
3415 void
3416f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3417{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003418 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003419 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003420
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003421 ins_compl_check_keys(0, TRUE);
3422 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003423
3424 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003425}
3426
3427/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003428 * Return Insert completion mode name string
3429 */
3430 static char_u *
3431ins_compl_mode(void)
3432{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003433 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003434 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3435
3436 return (char_u *)"";
3437}
3438
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003439/*
3440 * Assign the sequence number to all the completion matches which don't have
3441 * one assigned yet.
3442 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003443 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003444ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003445{
3446 int number = 0;
3447 compl_T *match;
3448
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003449 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003450 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003451 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003452 // This should normally succeed already at the first loop
3453 // cycle, so it's fast!
3454 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003455 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003456 if (match->cp_number != -1)
3457 {
3458 number = match->cp_number;
3459 break;
3460 }
3461 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003462 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003463 for (match = match->cp_next;
3464 match != NULL && match->cp_number == -1;
3465 match = match->cp_next)
3466 match->cp_number = ++number;
3467 }
3468 else // BACKWARD
3469 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003470 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003471 // number. This should normally succeed already at the
3472 // first loop cycle, so it's fast!
3473 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003474 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003475 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003476 if (match->cp_number != -1)
3477 {
3478 number = match->cp_number;
3479 break;
3480 }
glepnir40891ba2025-02-10 22:18:00 +01003481 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003482 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003483 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003484 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003485 for (match = match->cp_prev; match
3486 && match->cp_number == -1;
3487 match = match->cp_prev)
3488 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003489 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003490 }
3491}
3492
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003493/*
glepnir037b0282025-01-16 14:37:44 +01003494 * Fill the dict of complete_info
3495 */
3496 static void
3497fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3498{
3499 dict_add_string(di, "word", match->cp_str.string);
3500 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3501 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3502 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3503 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3504 if (add_match)
3505 dict_add_bool(di, "match", match->cp_in_match_array);
3506 if (match->cp_user_data.v_type == VAR_UNKNOWN)
3507 // Add an empty string for backwards compatibility
3508 dict_add_string(di, "user_data", (char_u *)"");
3509 else
3510 dict_add_tv(di, "user_data", &match->cp_user_data);
3511}
3512
3513/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003514 * Get complete information
3515 */
3516 static void
3517get_complete_info(list_T *what_list, dict_T *retdict)
3518{
3519 int ret = OK;
3520 listitem_T *item;
3521#define CI_WHAT_MODE 0x01
3522#define CI_WHAT_PUM_VISIBLE 0x02
3523#define CI_WHAT_ITEMS 0x04
3524#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003525#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003526#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003527#define CI_WHAT_ALL 0xff
3528 int what_flag;
3529
3530 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003531 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003532 else
3533 {
3534 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003535 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003536 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003537 {
3538 char_u *what = tv_get_string(&item->li_tv);
3539
3540 if (STRCMP(what, "mode") == 0)
3541 what_flag |= CI_WHAT_MODE;
3542 else if (STRCMP(what, "pum_visible") == 0)
3543 what_flag |= CI_WHAT_PUM_VISIBLE;
3544 else if (STRCMP(what, "items") == 0)
3545 what_flag |= CI_WHAT_ITEMS;
3546 else if (STRCMP(what, "selected") == 0)
3547 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003548 else if (STRCMP(what, "completed") == 0)
3549 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003550 else if (STRCMP(what, "matches") == 0)
3551 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003552 }
3553 }
3554
3555 if (ret == OK && (what_flag & CI_WHAT_MODE))
3556 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3557
3558 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3559 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3560
glepnir037b0282025-01-16 14:37:44 +01003561 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3562 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003563 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003564 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003565 dict_T *di;
3566 compl_T *match;
3567 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003568 int has_items = what_flag & CI_WHAT_ITEMS;
3569 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003570 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003571
glepnird4088ed2024-12-31 10:55:22 +01003572 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003573 {
3574 li = list_alloc();
3575 if (li == NULL)
3576 return;
glepnird4088ed2024-12-31 10:55:22 +01003577 ret = dict_add_list(retdict, (has_matches && !has_items)
3578 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003579 }
3580 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3581 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3582 ins_compl_update_sequence_numbers();
3583 if (ret == OK && compl_first_match != NULL)
3584 {
3585 int list_idx = 0;
3586 match = compl_first_match;
3587 do
3588 {
3589 if (!match_at_original_text(match))
3590 {
glepnird4088ed2024-12-31 10:55:22 +01003591 if (has_items
3592 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003593 {
3594 di = dict_alloc();
3595 if (di == NULL)
3596 return;
3597 ret = list_append_dict(li, di);
3598 if (ret != OK)
3599 return;
glepnir037b0282025-01-16 14:37:44 +01003600 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003601 }
glepnird4088ed2024-12-31 10:55:22 +01003602 if (compl_curr_match != NULL
3603 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003604 selected_idx = list_idx;
3605 list_idx += 1;
3606 }
3607 match = match->cp_next;
3608 }
3609 while (match != NULL && !is_first_match(match));
3610 }
3611 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3612 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003613
glepnir037b0282025-01-16 14:37:44 +01003614 if (ret == OK && selected_idx != -1 && has_completed)
3615 {
3616 di = dict_alloc();
3617 if (di == NULL)
3618 return;
3619 fill_complete_info_dict(di, compl_curr_match, FALSE);
3620 ret = dict_add_dict(retdict, "completed", di);
3621 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003622 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003623}
3624
3625/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003626 * "complete_info()" function
3627 */
3628 void
3629f_complete_info(typval_T *argvars, typval_T *rettv)
3630{
3631 list_T *what_list = NULL;
3632
Bram Moolenaar93a10962022-06-16 11:42:09 +01003633 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003634 return;
3635
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003636 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
3637 return;
3638
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003639 if (argvars[0].v_type != VAR_UNKNOWN)
3640 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01003641 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003642 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003643 what_list = argvars[0].vval.v_list;
3644 }
3645 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003646}
3647#endif
3648
3649/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003650 * Returns TRUE when using a user-defined function for thesaurus completion.
3651 */
3652 static int
3653thesaurus_func_complete(int type UNUSED)
3654{
3655#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003656 return type == CTRL_X_THESAURUS
3657 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003658#else
3659 return FALSE;
3660#endif
3661}
3662
3663/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003664 * Return value of process_next_cpt_value()
3665 */
3666enum
3667{
3668 INS_COMPL_CPT_OK = 1,
3669 INS_COMPL_CPT_CONT,
3670 INS_COMPL_CPT_END
3671};
3672
3673/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003674 * state information used for getting the next set of insert completion
3675 * matches.
3676 */
3677typedef struct
3678{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003679 char_u *e_cpt_copy; // copy of 'complete'
3680 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003681 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003682 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003683 pos_T prev_match_pos; // previous match position
3684 int set_match_pos; // save first_match_pos/last_match_pos
3685 pos_T first_match_pos; // first match position
3686 pos_T last_match_pos; // last match position
3687 int found_all; // found all matches of a certain type.
3688 char_u *dict; // dictionary file to search
3689 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02003690 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003691} ins_compl_next_state_T;
3692
3693/*
3694 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003695 *
3696 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003697 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003698 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003699 * st->found_all - all matches of this type are found
3700 * st->ins_buf - search for completions in this buffer
3701 * st->first_match_pos - position of the first completion match
3702 * st->last_match_pos - position of the last completion match
3703 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01003704 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003705 * st->dict - name of the dictionary or thesaurus file to search
3706 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003707 *
3708 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003709 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
3710 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003711 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003712 */
3713 static int
3714process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003715 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003716 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02003717 pos_T *start_match_pos,
glepnir53b14572025-03-12 21:28:39 +01003718 int fuzzy_collect)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003719{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003720 int compl_type = -1;
3721 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003722
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003723 st->found_all = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003724
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003725 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
3726 st->e_cpt++;
3727
3728 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003729 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003730 st->ins_buf = curbuf;
3731 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003732 // Move the cursor back one character so that ^N can match the
3733 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01003734 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003735 {
3736 // Move the cursor to after the last character in the
3737 // buffer, so that word at start of buffer is found
3738 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003739 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01003740 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003741 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003742 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003743 compl_type = 0;
3744
3745 // Remember the first match so that the loop stops when we
3746 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003747 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003748 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003749 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003750 && (st->ins_buf = ins_compl_next_buf(
3751 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003752 {
3753 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003754 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003755 {
3756 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003757 st->first_match_pos.col = st->last_match_pos.col = 0;
3758 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
3759 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003760 compl_type = 0;
3761 }
3762 else // unloaded buffer, scan like dictionary
3763 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003764 st->found_all = TRUE;
3765 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003766 {
3767 status = INS_COMPL_CPT_CONT;
3768 goto done;
3769 }
3770 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003771 st->dict = st->ins_buf->b_fname;
3772 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003773 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003774 if (!shortmess(SHM_COMPLETIONSCAN))
3775 {
3776 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3777 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3778 st->ins_buf->b_fname == NULL
3779 ? buf_spname(st->ins_buf)
3780 : st->ins_buf->b_sfname == NULL
3781 ? st->ins_buf->b_fname
3782 : st->ins_buf->b_sfname);
3783 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3784 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003785 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003786 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003787 status = INS_COMPL_CPT_END;
3788 else
3789 {
3790 if (ctrl_x_mode_line_or_eval())
3791 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003792 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003793 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003794 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003795 compl_type = CTRL_X_DICTIONARY;
3796 else
3797 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003798 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003799 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003800 st->dict = st->e_cpt;
3801 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003802 }
3803 }
Girish Palyacbe53192025-04-14 22:13:15 +02003804#ifdef FEAT_COMPL_FUNC
3805 else if (*st->e_cpt == 'f' || *st->e_cpt == 'o')
3806 {
3807 compl_type = CTRL_X_FUNCTION;
3808 if (*st->e_cpt == 'o')
3809 st->func_cb = &curbuf->b_ofu_cb;
3810 else
3811 st->func_cb = (*++st->e_cpt != ',' && *st->e_cpt != NUL)
3812 ? get_cpt_func_callback(st->e_cpt) : &curbuf->b_cfu_cb;
3813 if (!st->func_cb)
3814 compl_type = -1;
3815 }
3816#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003817#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003818 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003819 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003820 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003821 compl_type = CTRL_X_PATH_DEFINES;
3822#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003823 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003824 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003825 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01003826 if (!shortmess(SHM_COMPLETIONSCAN))
3827 {
3828 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3829 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3830 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3831 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003832 }
3833 else
3834 compl_type = -1;
3835
3836 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003837 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003838
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003839 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003840 if (compl_type == -1)
3841 status = INS_COMPL_CPT_CONT;
3842 }
3843
3844done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003845 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003846 return status;
3847}
3848
3849#ifdef FEAT_FIND_ID
3850/*
3851 * Get the next set of identifiers or defines matching "compl_pattern" in
3852 * included files.
3853 */
3854 static void
3855get_next_include_file_completion(int compl_type)
3856{
John Marriott5e6ea922024-11-23 14:01:57 +01003857 find_pattern_in_path(compl_pattern.string, compl_direction,
3858 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003859 (compl_type == CTRL_X_PATH_DEFINES
3860 && !(compl_cont_status & CONT_SOL))
3861 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01003862 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003863}
3864#endif
3865
3866/*
3867 * Get the next set of words matching "compl_pattern" in dictionary or
3868 * thesaurus files.
3869 */
3870 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003871get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003872{
3873#ifdef FEAT_COMPL_FUNC
3874 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02003875 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003876 else
3877#endif
3878 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003879 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003880 : (compl_type == CTRL_X_THESAURUS
3881 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3882 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01003883 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00003884 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003885 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003886}
3887
3888/*
3889 * Get the next set of tag names matching "compl_pattern".
3890 */
3891 static void
3892get_next_tag_completion(void)
3893{
3894 int save_p_ic;
3895 char_u **matches;
3896 int num_matches;
3897
3898 // set p_ic according to p_ic, p_scs and pat for find_tags().
3899 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01003900 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003901
3902 // Find up to TAG_MANY matches. Avoids that an enormous number
3903 // of matches is found when compl_pattern is empty
3904 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01003905 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003906 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003907 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003908 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3909 ins_compl_add_matches(num_matches, matches, p_ic);
3910 g_tag_at_cursor = FALSE;
3911 p_ic = save_p_ic;
3912}
3913
3914/*
glepnir8159fb12024-07-17 20:32:54 +02003915 * Compare function for qsort
3916 */
glepnirf31cfa22025-03-06 21:59:13 +01003917 static int
3918compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02003919{
3920 int idx_a = *(const int *)a;
3921 int idx_b = *(const int *)b;
3922 int score_a = compl_fuzzy_scores[idx_a];
3923 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02003924 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
3925 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02003926}
3927
3928/*
glepnirf31cfa22025-03-06 21:59:13 +01003929 * insert prefix with redraw
3930 */
3931 static void
3932ins_compl_longest_insert(char_u *prefix)
3933{
3934 ins_compl_delete();
3935 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
3936 ins_redraw(FALSE);
3937}
3938
3939/*
3940 * Calculate the longest common prefix among the best fuzzy matches
3941 * stored in compl_best_matches, and insert it as the longest.
3942 */
3943 static void
3944fuzzy_longest_match(void)
3945{
3946 char_u *prefix = NULL;
3947 int prefix_len = 0;
3948 int i = 0;
3949 int j = 0;
3950 char_u *match_str = NULL;
3951 char_u *prefix_ptr = NULL;
3952 char_u *match_ptr = NULL;
3953 char_u *leader = NULL;
3954 size_t leader_len = 0;
3955 compl_T *compl = NULL;
3956 int more_candidates = FALSE;
3957 compl_T *nn_compl = NULL;
3958
3959 if (compl_num_bests == 0)
3960 return;
3961
3962 nn_compl = compl_first_match->cp_next->cp_next;
3963 if (nn_compl && nn_compl != compl_first_match)
3964 more_candidates = TRUE;
3965
3966 compl = ctrl_x_mode_whole_line() ? compl_first_match
3967 : compl_first_match->cp_next;
3968 if (compl_num_bests == 1)
3969 {
3970 // no more candidates insert the match str
3971 if (!more_candidates)
3972 {
3973 ins_compl_longest_insert(compl->cp_str.string);
3974 compl_num_bests = 0;
3975 }
3976 compl_num_bests = 0;
3977 return;
3978 }
3979
3980 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
3981 if (compl_best_matches == NULL)
3982 return;
3983 while (compl != NULL && i < compl_num_bests)
3984 {
3985 compl_best_matches[i] = compl;
3986 compl = compl->cp_next;
3987 i++;
3988 }
3989
3990 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01003991 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01003992
3993 for (i = 1; i < compl_num_bests; i++)
3994 {
3995 match_str = compl_best_matches[i]->cp_str.string;
3996 prefix_ptr = prefix;
3997 match_ptr = match_str;
3998 j = 0;
3999
4000 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4001 {
4002 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4003 break;
4004
4005 MB_PTR_ADV(prefix_ptr);
4006 MB_PTR_ADV(match_ptr);
4007 j++;
4008 }
4009
4010 if (j > 0)
4011 prefix_len = j;
4012 }
4013
4014 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004015 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004016
4017 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004018 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004019 goto end;
4020
zeertzjq4422de62025-03-07 19:06:02 +01004021 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004022 if (prefix != NULL)
4023 {
4024 ins_compl_longest_insert(prefix);
4025 compl_cfc_longest_ins = TRUE;
4026 vim_free(prefix);
4027 }
4028
4029end:
4030 vim_free(compl_best_matches);
4031 compl_best_matches = NULL;
4032 compl_num_bests = 0;
4033}
4034
4035/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004036 * Get the next set of filename matching "compl_pattern".
4037 */
4038 static void
4039get_next_filename_completion(void)
4040{
4041 char_u **matches;
4042 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004043 char_u *ptr;
4044 garray_T fuzzy_indices;
4045 int i;
4046 int score;
4047 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004048 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004049 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004050 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004051 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004052 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4053 int max_score = 0;
4054 int current_score = 0;
4055 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004056
glepnirb9de1a02024-08-02 19:14:38 +02004057#ifdef BACKSLASH_IN_FILENAME
4058 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4059 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4060#else
4061 char pathsep = PATHSEP;
4062#endif
4063
glepnirf31cfa22025-03-06 21:59:13 +01004064 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004065 {
glepnirb9de1a02024-08-02 19:14:38 +02004066#ifdef BACKSLASH_IN_FILENAME
4067 if (curbuf->b_p_csl[0] == 's')
4068 {
John Marriott5e6ea922024-11-23 14:01:57 +01004069 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004070 {
4071 if (leader[i] == '\\')
4072 leader[i] = '/';
4073 }
4074 }
4075 else if (curbuf->b_p_csl[0] == 'b')
4076 {
John Marriott5e6ea922024-11-23 14:01:57 +01004077 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004078 {
4079 if (leader[i] == '/')
4080 leader[i] = '\\';
4081 }
4082 }
4083#endif
4084 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004085 if (last_sep == NULL)
4086 {
4087 // No path separator or separator is the last character,
4088 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004089 VIM_CLEAR_STRING(compl_pattern);
4090 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4091 if (compl_pattern.string == NULL)
4092 return;
4093 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004094 }
4095 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004096 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004097 else
4098 {
4099 // Split leader into path and file parts
4100 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004101 char_u *path_with_wildcard;
4102
4103 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004104 if (path_with_wildcard != NULL)
4105 {
John Marriott5e6ea922024-11-23 14:01:57 +01004106 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4107 VIM_CLEAR_STRING(compl_pattern);
4108 compl_pattern.string = path_with_wildcard;
4109 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004110
4111 // Move leader to the file part
4112 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004113 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004114 }
4115 }
glepnir8159fb12024-07-17 20:32:54 +02004116 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004117
John Marriott5e6ea922024-11-23 14:01:57 +01004118 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004119 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4120 return;
4121
4122 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004123 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004124#ifdef BACKSLASH_IN_FILENAME
4125 if (curbuf->b_p_csl[0] != NUL)
4126 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004127 for (i = 0; i < num_matches; ++i)
4128 {
glepnir8159fb12024-07-17 20:32:54 +02004129 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004130 while (*ptr != NUL)
4131 {
4132 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4133 *ptr = '/';
4134 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4135 *ptr = '\\';
4136 ptr += (*mb_ptr2len)(ptr);
4137 }
4138 }
4139 }
4140#endif
glepnir8159fb12024-07-17 20:32:54 +02004141
glepnirf31cfa22025-03-06 21:59:13 +01004142 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004143 {
4144 ga_init2(&fuzzy_indices, sizeof(int), 10);
4145 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4146
4147 for (i = 0; i < num_matches; i++)
4148 {
4149 ptr = matches[i];
4150 score = fuzzy_match_str(ptr, leader);
4151 if (score > 0)
4152 {
4153 if (ga_grow(&fuzzy_indices, 1) == OK)
4154 {
4155 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4156 compl_fuzzy_scores[i] = score;
4157 fuzzy_indices.ga_len++;
4158 }
4159 }
4160 }
4161
Christian Brabandt220474d2024-07-20 13:26:44 +02004162 // prevent qsort from deref NULL pointer
4163 if (fuzzy_indices.ga_len > 0)
4164 {
glepnirf31cfa22025-03-06 21:59:13 +01004165 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004166 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4167 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004168
Christian Brabandt220474d2024-07-20 13:26:44 +02004169 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004170 {
4171 match = matches[fuzzy_indices_data[i]];
4172 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4173 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
4174 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4175 FALSE, NULL, current_score) == OK)
4176 dir = FORWARD;
4177
4178 if (need_collect_bests)
4179 {
4180 if (i == 0 || current_score == max_score)
4181 {
4182 compl_num_bests++;
4183 max_score = current_score;
4184 }
4185 }
4186 }
glepnir8159fb12024-07-17 20:32:54 +02004187
Christian Brabandt220474d2024-07-20 13:26:44 +02004188 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004189 }
glepnir6b6280c2024-07-27 16:25:45 +02004190 else if (leader_len > 0)
4191 {
4192 FreeWild(num_matches, matches);
4193 num_matches = 0;
4194 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004195
glepnir8159fb12024-07-17 20:32:54 +02004196 vim_free(compl_fuzzy_scores);
4197 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004198
4199 if (compl_num_bests > 0 && compl_get_longest)
4200 fuzzy_longest_match();
4201 return;
glepnir8159fb12024-07-17 20:32:54 +02004202 }
4203
glepnir6b6280c2024-07-27 16:25:45 +02004204 if (num_matches > 0)
4205 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004206}
4207
4208/*
4209 * Get the next set of command-line completions matching "compl_pattern".
4210 */
4211 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004212get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004213{
4214 char_u **matches;
4215 int num_matches;
4216
John Marriott5e6ea922024-11-23 14:01:57 +01004217 if (expand_cmdline(&compl_xp, compl_pattern.string,
4218 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004219 ins_compl_add_matches(num_matches, matches, FALSE);
4220}
4221
4222/*
4223 * Get the next set of spell suggestions matching "compl_pattern".
4224 */
4225 static void
4226get_next_spell_completion(linenr_T lnum UNUSED)
4227{
4228#ifdef FEAT_SPELL
4229 char_u **matches;
4230 int num_matches;
4231
John Marriott5e6ea922024-11-23 14:01:57 +01004232 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004233 if (num_matches > 0)
4234 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004235 else
4236 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004237#endif
4238}
4239
4240/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004241 * Return the next word or line from buffer "ins_buf" at position
4242 * "cur_match_pos" for completion. The length of the match is set in "len".
4243 */
4244 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004245ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004246 buf_T *ins_buf, // buffer being scanned
4247 pos_T *cur_match_pos, // current match position
4248 int *match_len,
4249 int *cont_s_ipos) // next ^X<> will set initial_pos
4250{
4251 char_u *ptr;
4252 int len;
4253
4254 *match_len = 0;
4255 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4256 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004257 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004258 if (ctrl_x_mode_line_or_eval())
4259 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004260 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004261 {
4262 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4263 return NULL;
4264 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004265 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004266 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004267 {
4268 char_u *tmp_ptr = ptr;
4269
4270 ptr = skipwhite(tmp_ptr);
4271 len -= (int)(ptr - tmp_ptr);
4272 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004273 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004274 }
4275 else
4276 {
4277 char_u *tmp_ptr = ptr;
4278
John Marriott5e6ea922024-11-23 14:01:57 +01004279 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004280 {
4281 tmp_ptr += compl_length;
4282 // Skip if already inside a word.
4283 if (vim_iswordp(tmp_ptr))
4284 return NULL;
4285 // Find start of next word.
4286 tmp_ptr = find_word_start(tmp_ptr);
4287 }
4288 // Find end of this word.
4289 tmp_ptr = find_word_end(tmp_ptr);
4290 len = (int)(tmp_ptr - ptr);
4291
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004292 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004293 {
4294 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4295 {
4296 // Try next line, if any. the new word will be
4297 // "join" as if the normal command "J" was used.
4298 // IOSIZE is always greater than
4299 // compl_length, so the next STRNCPY always
4300 // works -- Acevedo
4301 STRNCPY(IObuff, ptr, len);
4302 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4303 tmp_ptr = ptr = skipwhite(ptr);
4304 // Find start of next word.
4305 tmp_ptr = find_word_start(tmp_ptr);
4306 // Find end of next word.
4307 tmp_ptr = find_word_end(tmp_ptr);
4308 if (tmp_ptr > ptr)
4309 {
4310 if (*ptr != ')' && IObuff[len - 1] != TAB)
4311 {
4312 if (IObuff[len - 1] != ' ')
4313 IObuff[len++] = ' ';
4314 // IObuf =~ "\k.* ", thus len >= 2
4315 if (p_js
4316 && (IObuff[len - 2] == '.'
4317 || (vim_strchr(p_cpo, CPO_JOINSP)
4318 == NULL
4319 && (IObuff[len - 2] == '?'
4320 || IObuff[len - 2] == '!'))))
4321 IObuff[len++] = ' ';
4322 }
4323 // copy as much as possible of the new word
4324 if (tmp_ptr - ptr >= IOSIZE - len)
4325 tmp_ptr = ptr + IOSIZE - len - 1;
4326 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4327 len += (int)(tmp_ptr - ptr);
4328 *cont_s_ipos = TRUE;
4329 }
4330 IObuff[len] = NUL;
4331 ptr = IObuff;
4332 }
4333 if (len == compl_length)
4334 return NULL;
4335 }
4336 }
4337
4338 *match_len = len;
4339 return ptr;
4340}
4341
4342/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004343 * Get the next set of words matching "compl_pattern" for default completion(s)
4344 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004345 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4346 * position "st->start_pos" in the "compl_direction" direction. If
4347 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4348 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004349 * Returns OK if a new next match is found, otherwise returns FAIL.
4350 */
4351 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004352get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004353{
4354 int found_new_match = FAIL;
4355 int save_p_scs;
4356 int save_p_ws;
4357 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004358 char_u *ptr = NULL;
4359 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004360 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004361 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004362 int score = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004363
4364 // If 'infercase' is set, don't use 'smartcase' here
4365 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004366 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004367 p_scs = FALSE;
4368
4369 // Buffers other than curbuf are scanned from the beginning or the
4370 // end but never from the middle, thus setting nowrapscan in this
4371 // buffer is a good idea, on the other hand, we always set
4372 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4373 save_p_ws = p_ws;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004374 if (st->ins_buf != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004375 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004376 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004377 p_ws = TRUE;
4378 looped_around = FALSE;
4379 for (;;)
4380 {
4381 int cont_s_ipos = FALSE;
4382
4383 ++msg_silent; // Don't want messages for wrapscan.
4384
glepnirf31cfa22025-03-06 21:59:13 +01004385 if (in_collect)
4386 {
glepnir8159fb12024-07-17 20:32:54 +02004387 found_new_match = search_for_fuzzy_match(st->ins_buf,
4388 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004389 start_pos, &len, &ptr, &score);
4390 }
4391 // ctrl_x_mode_line_or_eval() || word-wise search that
4392 // has added a word that was at the beginning of the line
4393 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4394 found_new_match = search_for_exact_line(st->ins_buf,
4395 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004396 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004397 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004398 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004399 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004400 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004401 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004402 {
4403 // set "compl_started" even on fail
4404 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004405 st->first_match_pos = *st->cur_match_pos;
4406 st->last_match_pos = *st->cur_match_pos;
4407 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004408 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004409 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4410 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004411 {
4412 found_new_match = FAIL;
4413 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004414 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004415 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4416 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4417 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004418 {
4419 if (looped_around)
4420 found_new_match = FAIL;
4421 else
4422 looped_around = TRUE;
4423 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004424 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004425 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4426 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4427 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004428 {
4429 if (looped_around)
4430 found_new_match = FAIL;
4431 else
4432 looped_around = TRUE;
4433 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004434 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004435 if (found_new_match == FAIL)
4436 break;
4437
4438 // when ADDING, the text before the cursor matches, skip it
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004439 if (compl_status_adding() && st->ins_buf == curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004440 && start_pos->lnum == st->cur_match_pos->lnum
4441 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004442 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004443
glepnirf31cfa22025-03-06 21:59:13 +01004444 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004445 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4446 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004447 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004448 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004449
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004450 if (ins_compl_add_infercase(ptr, len, p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01004451 st->ins_buf == curbuf ? NULL : st->ins_buf->b_sfname,
4452 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004453 {
glepnirf31cfa22025-03-06 21:59:13 +01004454 if (in_collect && score == compl_first_match->cp_next->cp_score)
4455 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004456 found_new_match = OK;
4457 break;
4458 }
4459 }
4460 p_scs = save_p_scs;
4461 p_ws = save_p_ws;
4462
4463 return found_new_match;
4464}
4465
4466/*
Girish Palyacbe53192025-04-14 22:13:15 +02004467 * Return the callback function associated with "funcname".
4468 */
4469#ifdef FEAT_COMPL_FUNC
4470 static callback_T *
4471get_cpt_func_callback(char_u *funcname)
4472{
4473 static callback_T cb;
4474 char_u buf[LSIZE];
4475 int slen;
4476
4477 slen = copy_option_part(&funcname, buf, LSIZE, ",");
4478 if (slen > 0 && option_set_callback_func(buf, &cb))
4479 return &cb;
4480 return NULL;
4481}
4482
4483/*
4484 * Retrieve new completion matches by invoking callback "cb".
4485 */
4486 static void
4487expand_cpt_function(callback_T *cb)
4488{
4489 // Re-insert the text removed by ins_compl_delete().
4490 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
4491 // Get matches
4492 get_cpt_func_completion_matches(cb);
4493 // Undo insertion
4494 ins_compl_delete();
4495}
4496#endif
4497
4498/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004499 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004500 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004501 */
4502 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004503get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004504{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004505 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004506
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004507 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004508 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004509 case -1:
4510 break;
4511#ifdef FEAT_FIND_ID
4512 case CTRL_X_PATH_PATTERNS:
4513 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004514 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004515 break;
4516#endif
4517
4518 case CTRL_X_DICTIONARY:
4519 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004520 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
4521 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004522 break;
4523
4524 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004525 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004526 break;
4527
4528 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004529 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004530 break;
4531
4532 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02004533 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004534 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004535 break;
4536
4537#ifdef FEAT_COMPL_FUNC
4538 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02004539 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
4540 expand_cpt_function(st->func_cb);
4541 else
4542 expand_by_function(type, compl_pattern.string, NULL);
4543 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004544 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02004545 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004546 break;
4547#endif
4548
4549 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004550 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004551 break;
4552
4553 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004554 found_new_match = get_next_default_completion(st, ini);
4555 if (found_new_match == FAIL && st->ins_buf == curbuf)
4556 st->found_all = TRUE;
4557 }
4558
4559 // check if compl_curr_match has changed, (e.g. other type of
4560 // expansion added something)
4561 if (type != 0 && compl_curr_match != compl_old_match)
4562 found_new_match = OK;
4563
4564 return found_new_match;
4565}
4566
4567/*
4568 * Get the next expansion(s), using "compl_pattern".
4569 * The search starts at position "ini" in curbuf and in the direction
4570 * compl_direction.
4571 * When "compl_started" is FALSE start at that position, otherwise continue
4572 * where we stopped searching before.
4573 * This may return before finding all the matches.
4574 * Return the total number of matches or -1 if still unknown -- Acevedo
4575 */
4576 static int
4577ins_compl_get_exp(pos_T *ini)
4578{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004579 static ins_compl_next_state_T st;
4580 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004581 int i;
4582 int found_new_match;
4583 int type = ctrl_x_mode;
4584
4585 if (!compl_started)
4586 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004587 buf_T *buf;
4588
4589 FOR_ALL_BUFFERS(buf)
4590 buf->b_scanned = 0;
4591 if (!st_cleared)
4592 {
4593 CLEAR_FIELD(st);
4594 st_cleared = TRUE;
4595 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004596 st.found_all = FALSE;
4597 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004598 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02004599 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004600 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
4601 ? (char_u *)"." : curbuf->b_p_cpt);
4602 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004603 st.last_match_pos = st.first_match_pos = *ini;
Girish Palyacbe53192025-04-14 22:13:15 +02004604
4605 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
4606 && !cpt_compl_src_init(st.e_cpt))
4607 return FAIL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004608 }
4609 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
4610 st.ins_buf = curbuf; // In case the buffer was wiped out.
4611
4612 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02004613 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02004614 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004615
4616 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palyacbe53192025-04-14 22:13:15 +02004617 for (cpt_value_idx = 0;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004618 {
4619 found_new_match = FAIL;
4620 st.set_match_pos = FALSE;
4621
4622 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
4623 // or if found_all says this entry is done. For ^X^L only use the
4624 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004625 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004626 && (!compl_started || st.found_all))
4627 {
glepnir53b14572025-03-12 21:28:39 +01004628 int status = process_next_cpt_value(&st, &type, ini, cfc_has_mode());
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004629
4630 if (status == INS_COMPL_CPT_END)
4631 break;
4632 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02004633 {
4634 cpt_value_idx++;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004635 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02004636 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004637 }
4638
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004639 // If complete() was called then compl_pattern has been reset. The
4640 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01004641 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004642 break;
4643
4644 // get the next set of completion matches
4645 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004646
Girish Palyacbe53192025-04-14 22:13:15 +02004647 if (type > 0)
4648 cpt_value_idx++;
4649
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004650 // break the loop for specialized modes (use 'complete' just for the
4651 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
4652 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004653 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
4654 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004655 {
4656 if (got_int)
4657 break;
4658 // Fill the popup menu as soon as possible.
4659 if (type != -1)
4660 ins_compl_check_keys(0, FALSE);
4661
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004662 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004663 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
4664 break;
4665 compl_started = TRUE;
4666 }
4667 else
4668 {
4669 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02004670 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004671 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004672
4673 compl_started = FALSE;
4674 }
4675 }
Girish Palyacbe53192025-04-14 22:13:15 +02004676 cpt_value_idx = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004677 compl_started = TRUE;
4678
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004679 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004680 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004681 found_new_match = FAIL;
4682
4683 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004684 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004685 && !ctrl_x_mode_line_or_eval()))
4686 i = ins_compl_make_cyclic();
4687
glepnirf31cfa22025-03-06 21:59:13 +01004688 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
4689 fuzzy_longest_match();
4690
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004691 if (compl_old_match != NULL)
4692 {
4693 // If several matches were added (FORWARD) or the search failed and has
4694 // just been made cyclic then we have to move compl_curr_match to the
4695 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004696 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004697 : compl_old_match->cp_prev;
4698 if (compl_curr_match == NULL)
4699 compl_curr_match = compl_old_match;
4700 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01004701 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01004702
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004703 return i;
4704}
4705
4706/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004707 * Update "compl_shown_match" to the actually shown match, it may differ when
4708 * "compl_leader" is used to omit some of the matches.
4709 */
4710 static void
4711ins_compl_update_shown_match(void)
4712{
4713 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004714 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004715 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004716 && !is_first_match(compl_shown_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004717 compl_shown_match = compl_shown_match->cp_next;
4718
4719 // If we didn't find it searching forward, and compl_shows_dir is
4720 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004721 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004722 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004723 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004724 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004725 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004726 {
4727 while (!ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01004728 compl_leader.string, (int)compl_leader.length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004729 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004730 && !is_first_match(compl_shown_match->cp_prev))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004731 compl_shown_match = compl_shown_match->cp_prev;
4732 }
4733}
4734
4735/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004736 * Delete the old text being completed.
4737 */
4738 void
4739ins_compl_delete(void)
4740{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004741 // In insert mode: Delete the typed part.
4742 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01004743 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01004744 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01004745 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01004746 int has_preinsert = ins_compl_preinsert_effect();
4747 if (has_preinsert)
4748 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02004749 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01004750 curwin->w_cursor.col = compl_ins_end_col;
4751 }
4752
glepnir76bdb822025-02-08 19:04:51 +01004753 if (curwin->w_cursor.lnum > compl_lnum)
4754 {
4755 if (curwin->w_cursor.col < ml_get_curline_len())
4756 {
John Marriottf4b36412025-02-23 09:09:59 +01004757 char_u *line = ml_get_cursor();
4758 remaining.length = ml_get_cursor_len();
4759 remaining.string = vim_strnsave(line, remaining.length);
4760 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01004761 return;
4762 }
4763 while (curwin->w_cursor.lnum > compl_lnum)
4764 {
4765 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
4766 {
John Marriottf4b36412025-02-23 09:09:59 +01004767 if (remaining.string)
4768 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004769 return;
4770 }
zeertzjq060e6552025-02-21 20:06:26 +01004771 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01004772 curwin->w_cursor.lnum--;
4773 }
4774 // move cursor to end of line
4775 curwin->w_cursor.col = ml_get_curline_len();
4776 }
4777
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004778 if ((int)curwin->w_cursor.col > col)
4779 {
4780 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01004781 {
John Marriottf4b36412025-02-23 09:09:59 +01004782 if (remaining.string)
4783 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004784 return;
glepnire3647c82025-02-10 21:16:32 +01004785 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004786 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01004787 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004788 }
4789
John Marriottf4b36412025-02-23 09:09:59 +01004790 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01004791 {
4792 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01004793 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01004794 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01004795 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01004796 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004797 // TODO: is this sufficient for redrawing? Redrawing everything causes
4798 // flicker, thus we can't do that.
4799 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004800#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004801 // clear v:completed_item
4802 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004803#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004804}
4805
4806/*
glepnir76bdb822025-02-08 19:04:51 +01004807 * Insert a completion string that contains newlines.
4808 * The string is split and inserted line by line.
4809 */
4810 static void
4811ins_compl_expand_multiple(char_u *str)
4812{
4813 char_u *start = str;
4814 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01004815 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01004816
4817 while (*curr != NUL)
4818 {
4819 if (*curr == '\n')
4820 {
4821 // Insert the text chunk before newline
4822 if (curr > start)
4823 ins_char_bytes(start, (int)(curr - start));
4824
4825 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01004826 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01004827 start = curr + 1;
4828 }
4829 curr++;
4830 }
4831
4832 // Handle remaining text after last newline (if any)
4833 if (curr > start)
4834 ins_char_bytes(start, (int)(curr - start));
4835
4836 compl_ins_end_col = curwin->w_cursor.col;
4837}
4838
4839/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004840 * Insert the new text being completed.
4841 * "in_compl_func" is TRUE when called from complete_check().
glepniredd4ac32025-01-29 18:53:51 +01004842 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
4843 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004844 */
4845 void
glepniredd4ac32025-01-29 18:53:51 +01004846ins_compl_insert(int in_compl_func, int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004847{
glepnir76bdb822025-02-08 19:04:51 +01004848 int compl_len = get_compl_len();
4849 int preinsert = ins_compl_has_preinsert();
4850 char_u *cp_str = compl_shown_match->cp_str.string;
4851 size_t cp_str_len = compl_shown_match->cp_str.length;
4852 size_t leader_len = ins_compl_leader_len();
4853 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00004854
4855 // Make sure we don't go over the end of the string, this can happen with
4856 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01004857 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01004858 {
glepnir76bdb822025-02-08 19:04:51 +01004859 if (has_multiple)
4860 ins_compl_expand_multiple(cp_str + compl_len);
4861 else
4862 {
4863 ins_compl_insert_bytes(cp_str + compl_len, -1);
4864 if (preinsert && move_cursor)
4865 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
4866 }
glepniredd4ac32025-01-29 18:53:51 +01004867 }
4868 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004869 compl_used_match = FALSE;
4870 else
4871 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02004872#ifdef FEAT_EVAL
4873 {
4874 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
4875
4876 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
4877 }
4878#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004879 if (!in_compl_func)
4880 compl_curr_match = compl_shown_match;
4881}
4882
4883/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004884 * show the file name for the completion match (if any). Truncate the file
4885 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004886 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004887 static void
4888ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004889{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004890 char *lead = _("match in file");
4891 int space = sc_col - vim_strsize((char_u *)lead) - 2;
4892 char_u *s;
4893 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004894
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004895 if (space <= 0)
4896 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004897
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004898 // We need the tail that fits. With double-byte encoding going
4899 // back from the end is very slow, thus go from the start and keep
4900 // the text that fits in "space" between "s" and "e".
4901 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004902 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004903 space -= ptr2cells(e);
4904 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004905 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004906 space += ptr2cells(s);
4907 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004908 }
4909 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004910 msg_hist_off = TRUE;
4911 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
4912 s > compl_shown_match->cp_fname ? "<" : "", s);
4913 msg((char *)IObuff);
4914 msg_hist_off = FALSE;
4915 redraw_cmdline = FALSE; // don't overwrite!
4916}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004917
glepnirdca57fb2024-06-04 22:01:21 +02004918/*
zeertzjq551d8c32024-06-05 19:53:32 +02004919 * Find a completion item when 'completeopt' contains "fuzzy".
glepnirdca57fb2024-06-04 22:01:21 +02004920 */
glepnira218cc62024-06-03 19:32:39 +02004921 static compl_T *
4922find_comp_when_fuzzy(void)
4923{
4924 int score;
4925 char_u* str;
4926 int target_idx = -1;
4927 int is_forward = compl_shows_dir_forward();
4928 int is_backward = compl_shows_dir_backward();
4929 compl_T *comp = NULL;
4930
glepnir43eef882024-06-19 20:20:48 +02004931 if ((is_forward && compl_selected_item == compl_match_arraysize - 1)
glepnira218cc62024-06-03 19:32:39 +02004932 || (is_backward && compl_selected_item == 0))
glepnir3e50a282025-04-03 21:17:06 +02004933 return compl_first_match != compl_shown_match ?
4934 (is_forward ? compl_shown_match->cp_next : compl_first_match) :
glepnir65407ce2024-07-06 16:09:19 +02004935 (compl_first_match->cp_prev ? compl_first_match->cp_prev : NULL);
glepnira218cc62024-06-03 19:32:39 +02004936
4937 if (is_forward)
4938 target_idx = compl_selected_item + 1;
4939 else if (is_backward)
4940 target_idx = compl_selected_item == -1 ? compl_match_arraysize - 1
glepnirdca57fb2024-06-04 22:01:21 +02004941 : compl_selected_item - 1;
glepnira218cc62024-06-03 19:32:39 +02004942
4943 score = compl_match_array[target_idx].pum_score;
4944 str = compl_match_array[target_idx].pum_text;
4945
4946 comp = compl_first_match;
4947 do {
John Marriott5e6ea922024-11-23 14:01:57 +01004948 if (comp->cp_score == score && (str == comp->cp_str.string || str == comp->cp_text[CPT_ABBR]))
glepnira218cc62024-06-03 19:32:39 +02004949 return comp;
4950 comp = comp->cp_next;
4951 } while (comp != NULL && !is_first_match(comp));
4952
4953 return NULL;
4954}
4955
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004956/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004957 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004958 * times. The number of matches found is returned in 'num_matches'.
4959 *
4960 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
4961 * get more completions. If it is FALSE, then do nothing when there are no more
4962 * completions in the given direction.
4963 *
4964 * If "advance" is TRUE, then completion will move to the first match.
4965 * Otherwise, the original text will be shown.
4966 *
4967 * Returns OK on success and -1 if the number of matches are unknown.
4968 */
4969 static int
4970find_next_completion_match(
4971 int allow_get_expansion,
4972 int todo, // repeat completion this many times
4973 int advance,
4974 int *num_matches)
4975{
4976 int found_end = FALSE;
4977 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02004978 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02004979 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
4980 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004981
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004982 while (--todo >= 0)
4983 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004984 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004985 {
glepniraced8c22024-06-15 15:13:05 +02004986 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4987 ? find_comp_when_fuzzy() : compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004988 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004989 && (is_first_match(compl_shown_match->cp_next)
4990 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004991 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004992 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004993 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004994 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004995 found_end = is_first_match(compl_shown_match);
glepniraced8c22024-06-15 15:13:05 +02004996 compl_shown_match = compl_fuzzy_match && compl_match_array != NULL
4997 ? find_comp_when_fuzzy() : compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004998 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004999 }
5000 else
5001 {
5002 if (!allow_get_expansion)
5003 {
5004 if (advance)
5005 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005006 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005007 compl_pending -= todo + 1;
5008 else
5009 compl_pending += todo + 1;
5010 }
5011 return -1;
5012 }
5013
5014 if (!compl_no_select && advance)
5015 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005016 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005017 --compl_pending;
5018 else
5019 ++compl_pending;
5020 }
5021
5022 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005023 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005024
5025 // handle any pending completions
5026 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005027 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005028 {
5029 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5030 {
5031 compl_shown_match = compl_shown_match->cp_next;
5032 --compl_pending;
5033 }
5034 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5035 {
5036 compl_shown_match = compl_shown_match->cp_prev;
5037 ++compl_pending;
5038 }
5039 else
5040 break;
5041 }
5042 found_end = FALSE;
5043 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005044 if (!match_at_original_text(compl_shown_match)
John Marriott5e6ea922024-11-23 14:01:57 +01005045 && compl_leader.string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005046 && !ins_compl_equal(compl_shown_match,
John Marriott5e6ea922024-11-23 14:01:57 +01005047 compl_leader.string, (int)compl_leader.length)
glepnira218cc62024-06-03 19:32:39 +02005048 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005049 ++todo;
5050 else
5051 // Remember a matching item.
5052 found_compl = compl_shown_match;
5053
5054 // Stop at the end of the list when we found a usable match.
5055 if (found_end)
5056 {
5057 if (found_compl != NULL)
5058 {
5059 compl_shown_match = found_compl;
5060 break;
5061 }
5062 todo = 1; // use first usable match after wrapping around
5063 }
5064 }
5065
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005066 return OK;
5067}
5068
5069/*
5070 * Fill in the next completion in the current direction.
5071 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5072 * get more completions. If it is FALSE, then we just do nothing when there
5073 * are no more completions in a given direction. The latter case is used when
5074 * we are still in the middle of finding completions, to allow browsing
5075 * through the ones found so far.
5076 * Return the total number of matches, or -1 if still unknown -- webb.
5077 *
5078 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5079 * compl_shown_match here.
5080 *
5081 * Note that this function may be called recursively once only. First with
5082 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5083 * calls this function with "allow_get_expansion" FALSE.
5084 */
5085 static int
5086ins_compl_next(
5087 int allow_get_expansion,
5088 int count, // repeat completion this many times; should
5089 // be at least 1
5090 int insert_match, // Insert the newly selected match
5091 int in_compl_func) // called from complete_check()
5092{
5093 int num_matches = -1;
5094 int todo = count;
5095 int advance;
5096 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005097 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005098 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005099 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5100 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005101 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005102
5103 // When user complete function return -1 for findstart which is next
5104 // time of 'always', compl_shown_match become NULL.
5105 if (compl_shown_match == NULL)
5106 return -1;
5107
John Marriott5e6ea922024-11-23 14:01:57 +01005108 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005109 && !match_at_original_text(compl_shown_match)
5110 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005111 // Update "compl_shown_match" to the actually shown match
5112 ins_compl_update_shown_match();
5113
5114 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005115 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005116 // Delete old text to be replaced
5117 ins_compl_delete();
5118
5119 // When finding the longest common text we stick at the original text,
5120 // don't let CTRL-N or CTRL-P move to the first match.
5121 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5122
5123 // When restarting the search don't insert the first match either.
5124 if (compl_restarting)
5125 {
5126 advance = FALSE;
5127 compl_restarting = FALSE;
5128 }
5129
5130 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5131 // around.
5132 if (find_next_completion_match(allow_get_expansion, todo, advance,
5133 &num_matches) == -1)
5134 return -1;
5135
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005136 if (curbuf != orig_curbuf)
5137 {
5138 // In case some completion function switched buffer, don't want to
5139 // insert the completion elsewhere.
5140 return -1;
5141 }
5142
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005143 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005144 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005145 {
glepnir6a38aff2024-12-16 21:56:16 +01005146 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005147 compl_used_match = FALSE;
5148 }
5149 else if (insert_match)
5150 {
5151 if (!compl_get_longest || compl_used_match)
glepniredd4ac32025-01-29 18:53:51 +01005152 ins_compl_insert(in_compl_func, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005153 else
glepnir6a38aff2024-12-16 21:56:16 +01005154 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005155 }
5156 else
5157 compl_used_match = FALSE;
5158
5159 if (!allow_get_expansion)
5160 {
5161 // may undisplay the popup menu first
5162 ins_compl_upd_pum();
5163
5164 if (pum_enough_matches())
5165 // Will display the popup menu, don't redraw yet to avoid flicker.
5166 pum_call_update_screen();
5167 else
5168 // Not showing the popup menu yet, redraw to show the user what was
5169 // inserted.
5170 update_screen(0);
5171
5172 // display the updated popup menu
5173 ins_compl_show_pum();
5174#ifdef FEAT_GUI
5175 if (gui.in_use)
5176 {
5177 // Show the cursor after the match, not after the redrawn text.
5178 setcursor();
5179 out_flush_cursor(FALSE, FALSE);
5180 }
5181#endif
5182
5183 // Delete old text to be replaced, since we're still searching and
5184 // don't want to match ourselves!
5185 ins_compl_delete();
5186 }
5187
5188 // Enter will select a match when the match wasn't inserted and the popup
5189 // menu is visible.
5190 if (compl_no_insert && !started)
5191 compl_enter_selects = TRUE;
5192 else
5193 compl_enter_selects = !insert_match && compl_match_array != NULL;
5194
5195 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005196 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005197 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005198
5199 return num_matches;
5200}
5201
5202/*
5203 * Call this while finding completions, to check whether the user has hit a key
5204 * that should change the currently displayed completion, or exit completion
5205 * mode. Also, when compl_pending is not zero, show a completion as soon as
5206 * possible. -- webb
5207 * "frequency" specifies out of how many calls we actually check.
5208 * "in_compl_func" is TRUE when called from complete_check(), don't set
5209 * compl_curr_match.
5210 */
5211 void
5212ins_compl_check_keys(int frequency, int in_compl_func)
5213{
5214 static int count = 0;
5215 int c;
5216
5217 // Don't check when reading keys from a script, :normal or feedkeys().
5218 // That would break the test scripts. But do check for keys when called
5219 // from complete_check().
5220 if (!in_compl_func && (using_script() || ex_normal_busy))
5221 return;
5222
5223 // Only do this at regular intervals
5224 if (++count < frequency)
5225 return;
5226 count = 0;
5227
5228 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5229 // can't do its work correctly.
5230 c = vpeekc_any();
5231 if (c != NUL)
5232 {
5233 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5234 {
5235 c = safe_vgetc(); // Eat the character
5236 compl_shows_dir = ins_compl_key2dir(c);
5237 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
5238 c != K_UP && c != K_DOWN, in_compl_func);
5239 }
5240 else
5241 {
5242 // Need to get the character to have KeyTyped set. We'll put it
5243 // back with vungetc() below. But skip K_IGNORE.
5244 c = safe_vgetc();
5245 if (c != K_IGNORE)
5246 {
5247 // Don't interrupt completion when the character wasn't typed,
5248 // e.g., when doing @q to replay keys.
5249 if (c != Ctrl_R && KeyTyped)
5250 compl_interrupted = TRUE;
5251
5252 vungetc(c);
5253 }
5254 }
5255 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005256 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005257 {
5258 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5259
5260 compl_pending = 0;
5261 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
5262 }
5263}
5264
5265/*
5266 * Decide the direction of Insert mode complete from the key typed.
5267 * Returns BACKWARD or FORWARD.
5268 */
5269 static int
5270ins_compl_key2dir(int c)
5271{
5272 if (c == Ctrl_P || c == Ctrl_L
5273 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5274 return BACKWARD;
5275 return FORWARD;
5276}
5277
5278/*
5279 * Return TRUE for keys that are used for completion only when the popup menu
5280 * is visible.
5281 */
5282 static int
5283ins_compl_pum_key(int c)
5284{
5285 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5286 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5287 || c == K_UP || c == K_DOWN);
5288}
5289
5290/*
5291 * Decide the number of completions to move forward.
5292 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5293 */
5294 static int
5295ins_compl_key2count(int c)
5296{
5297 int h;
5298
5299 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5300 {
5301 h = pum_get_height();
5302 if (h > 3)
5303 h -= 2; // keep some context
5304 return h;
5305 }
5306 return 1;
5307}
5308
5309/*
5310 * Return TRUE if completion with "c" should insert the match, FALSE if only
5311 * to change the currently selected completion.
5312 */
5313 static int
5314ins_compl_use_match(int c)
5315{
5316 switch (c)
5317 {
5318 case K_UP:
5319 case K_DOWN:
5320 case K_PAGEDOWN:
5321 case K_KPAGEDOWN:
5322 case K_S_DOWN:
5323 case K_PAGEUP:
5324 case K_KPAGEUP:
5325 case K_S_UP:
5326 return FALSE;
5327 }
5328 return TRUE;
5329}
5330
5331/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005332 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5333 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005334 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005335 * Uses the global variables: compl_cont_status and ctrl_x_mode
5336 */
5337 static int
5338get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
5339{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005340 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005341 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005342 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005343 {
5344 while (--startcol >= 0 && vim_isIDc(line[startcol]))
5345 ;
5346 compl_col += ++startcol;
5347 compl_length = curs_col - startcol;
5348 }
5349 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005350 {
John Marriott5e6ea922024-11-23 14:01:57 +01005351 compl_pattern.string = str_foldcase(line + compl_col,
5352 compl_length, NULL, 0);
5353 if (compl_pattern.string == NULL)
5354 {
5355 compl_pattern.length = 0;
5356 return FAIL;
5357 }
5358 compl_pattern.length = STRLEN(compl_pattern.string);
5359 }
5360 else
5361 {
5362 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5363 if (compl_pattern.string == NULL)
5364 {
5365 compl_pattern.length = 0;
5366 return FAIL;
5367 }
5368 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02005369 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005370 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005371 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005372 {
5373 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02005374 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01005375 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005376
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005377 if (!vim_iswordp(line + compl_col)
5378 || (compl_col > 0
5379 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02005380 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005381 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02005382 prefixlen = 0;
5383 }
John Marriott5e6ea922024-11-23 14:01:57 +01005384
5385 // we need up to 2 extra chars for the prefix
5386 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
5387 compl_pattern.string = alloc(n);
5388 if (compl_pattern.string == NULL)
5389 {
5390 compl_pattern.length = 0;
5391 return FAIL;
5392 }
5393 STRCPY((char *)compl_pattern.string, prefix);
5394 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005395 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005396 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005397 }
5398 else if (--startcol < 0
5399 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
5400 {
John Marriott5e6ea922024-11-23 14:01:57 +01005401 size_t len = STRLEN_LITERAL("\\<\\k\\k");
5402
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005403 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01005404 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
5405 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005406 {
John Marriott5e6ea922024-11-23 14:01:57 +01005407 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005408 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005409 }
John Marriott5e6ea922024-11-23 14:01:57 +01005410 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005411 compl_col += curs_col;
5412 compl_length = 0;
5413 }
5414 else
5415 {
5416 // Search the point of change class of multibyte character
5417 // or not a word single byte character backward.
5418 if (has_mbyte)
5419 {
5420 int base_class;
5421 int head_off;
5422
5423 startcol -= (*mb_head_off)(line, line + startcol);
5424 base_class = mb_get_class(line + startcol);
5425 while (--startcol >= 0)
5426 {
5427 head_off = (*mb_head_off)(line, line + startcol);
5428 if (base_class != mb_get_class(line + startcol
5429 - head_off))
5430 break;
5431 startcol -= head_off;
5432 }
5433 }
5434 else
5435 while (--startcol >= 0 && vim_iswordc(line[startcol]))
5436 ;
5437 compl_col += ++startcol;
5438 compl_length = (int)curs_col - startcol;
5439 if (compl_length == 1)
5440 {
5441 // Only match word with at least two chars -- webb
5442 // there's no need to call quote_meta,
5443 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01005444 compl_pattern.string = alloc(7);
5445 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005446 {
John Marriott5e6ea922024-11-23 14:01:57 +01005447 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005448 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005449 }
John Marriott5e6ea922024-11-23 14:01:57 +01005450 STRCPY((char *)compl_pattern.string, "\\<");
5451 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
5452 STRCAT((char *)compl_pattern.string, "\\k");
5453 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005454 }
5455 else
5456 {
John Marriott5e6ea922024-11-23 14:01:57 +01005457 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
5458
5459 compl_pattern.string = alloc(n);
5460 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005461 {
John Marriott5e6ea922024-11-23 14:01:57 +01005462 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005463 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005464 }
John Marriott5e6ea922024-11-23 14:01:57 +01005465 STRCPY((char *)compl_pattern.string, "\\<");
5466 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005467 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01005468 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005469 }
5470 }
5471
5472 return OK;
5473}
5474
5475/*
5476 * Get the pattern, column and length for whole line completion or for the
5477 * complete() function.
5478 * Sets the global variables: compl_col, compl_length and compl_pattern.
5479 */
5480 static int
5481get_wholeline_compl_info(char_u *line, colnr_T curs_col)
5482{
5483 compl_col = (colnr_T)getwhitecols(line);
5484 compl_length = (int)curs_col - (int)compl_col;
5485 if (compl_length < 0) // cursor in indent: empty pattern
5486 compl_length = 0;
5487 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02005488 {
John Marriott5e6ea922024-11-23 14:01:57 +01005489 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
5490 NULL, 0);
5491 if (compl_pattern.string == NULL)
5492 {
5493 compl_pattern.length = 0;
5494 return FAIL;
5495 }
5496 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02005497 }
John Marriott5e6ea922024-11-23 14:01:57 +01005498 else
5499 {
5500 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5501 if (compl_pattern.string == NULL)
5502 {
5503 compl_pattern.length = 0;
5504 return FAIL;
5505 }
5506 compl_pattern.length = (size_t)compl_length;
5507 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005508
5509 return OK;
5510}
5511
5512/*
5513 * Get the pattern, column and length for filename completion.
5514 * Sets the global variables: compl_col, compl_length and compl_pattern.
5515 */
5516 static int
5517get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
5518{
5519 // Go back to just before the first filename character.
5520 if (startcol > 0)
5521 {
5522 char_u *p = line + startcol;
5523
5524 MB_PTR_BACK(line, p);
5525 while (p > line && vim_isfilec(PTR2CHAR(p)))
5526 MB_PTR_BACK(line, p);
5527 if (p == line && vim_isfilec(PTR2CHAR(p)))
5528 startcol = 0;
5529 else
5530 startcol = (int)(p - line) + 1;
5531 }
5532
5533 compl_col += startcol;
5534 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01005535 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
5536 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005537 {
John Marriott5e6ea922024-11-23 14:01:57 +01005538 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005539 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005540 }
5541
John Marriott5e6ea922024-11-23 14:01:57 +01005542 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005543
5544 return OK;
5545}
5546
5547/*
5548 * Get the pattern, column and length for command-line completion.
5549 * Sets the global variables: compl_col, compl_length and compl_pattern.
5550 */
5551 static int
5552get_cmdline_compl_info(char_u *line, colnr_T curs_col)
5553{
John Marriott5e6ea922024-11-23 14:01:57 +01005554 compl_pattern.string = vim_strnsave(line, curs_col);
5555 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005556 {
John Marriott5e6ea922024-11-23 14:01:57 +01005557 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005558 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005559 }
John Marriott5e6ea922024-11-23 14:01:57 +01005560 compl_pattern.length = curs_col;
5561 set_cmd_context(&compl_xp, compl_pattern.string,
5562 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005563 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
5564 || compl_xp.xp_context == EXPAND_NOTHING)
5565 // No completion possible, use an empty pattern to get a
5566 // "pattern not found" message.
5567 compl_col = curs_col;
5568 else
John Marriott5e6ea922024-11-23 14:01:57 +01005569 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005570 compl_length = curs_col - compl_col;
5571
5572 return OK;
5573}
5574
5575/*
5576 * Get the pattern, column and length for user defined completion ('omnifunc',
5577 * 'completefunc' and 'thesaurusfunc')
5578 * Sets the global variables: compl_col, compl_length and compl_pattern.
5579 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02005580 * Callback function "cb" is set if triggered by a function in the 'cpt'
5581 * option; otherwise, it is NULL.
5582 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005583 */
5584 static int
Girish Palyacbe53192025-04-14 22:13:15 +02005585get_userdefined_compl_info(colnr_T curs_col UNUSED, callback_T *cb UNUSED,
5586 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005587{
5588 int ret = FAIL;
5589
5590#ifdef FEAT_COMPL_FUNC
5591 // Call user defined function 'completefunc' with "a:findstart"
5592 // set to 1 to obtain the length of text to use for completion.
5593 char_u *line;
5594 typval_T args[3];
5595 int col;
5596 char_u *funcname;
5597 pos_T pos;
5598 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02005599 int len;
5600 string_T *compl_pat;
5601 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005602
Girish Palyacbe53192025-04-14 22:13:15 +02005603 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005604 {
Girish Palyacbe53192025-04-14 22:13:15 +02005605 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
5606 // length as a string
5607 funcname = get_complete_funcname(ctrl_x_mode);
5608 if (*funcname == NUL)
5609 {
5610 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
5611 ? "completefunc" : "omnifunc");
5612 return FAIL;
5613 }
5614 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005615 }
5616
5617 args[0].v_type = VAR_NUMBER;
5618 args[0].vval.v_number = 1;
5619 args[1].v_type = VAR_STRING;
5620 args[1].vval.v_string = (char_u *)"";
5621 args[2].v_type = VAR_UNKNOWN;
5622 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01005623 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005624 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01005625 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005626
5627 State = save_State;
5628 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02005629 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005630 validate_cursor();
5631 if (!EQUAL_POS(curwin->w_cursor, pos))
5632 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00005633 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005634 return FAIL;
5635 }
5636
Girish Palyacbe53192025-04-14 22:13:15 +02005637 if (startcol != NULL)
5638 *startcol = col;
5639
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005640 // Return value -2 means the user complete function wants to cancel the
5641 // complete without an error, do the same if the function did not execute
5642 // successfully.
5643 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005644 return FAIL;
LemonBoy9bcb9ca2022-05-26 15:23:26 +01005645 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005646 if (col == -3)
5647 {
Girish Palyacbe53192025-04-14 22:13:15 +02005648 if (is_cpt_function)
5649 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005650 ctrl_x_mode = CTRL_X_NORMAL;
5651 edit_submode = NULL;
5652 if (!shortmess(SHM_COMPLETIONMENU))
5653 msg_clr_cmdline();
5654 return FAIL;
5655 }
5656
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00005657 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005658 // completion.
5659 compl_opt_refresh_always = FALSE;
5660 compl_opt_suppress_empty = FALSE;
5661
Girish Palyacbe53192025-04-14 22:13:15 +02005662 if (col < 0 || col > curs_col)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005663 col = curs_col;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005664
5665 // Setup variables for completion. Need to obtain "line" again,
5666 // it may have become invalid.
5667 line = ml_get(curwin->w_cursor.lnum);
Girish Palyacbe53192025-04-14 22:13:15 +02005668 len = curs_col - col;
5669 compl_pat = is_cpt_function ? &cpt_compl_pattern : &compl_pattern;
5670 compl_pat->string = vim_strnsave(line + col, (size_t)len);
5671 if (compl_pat->string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005672 {
Girish Palyacbe53192025-04-14 22:13:15 +02005673 compl_pat->length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005674 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005675 }
Girish Palyacbe53192025-04-14 22:13:15 +02005676 compl_pat->length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005677
Girish Palyacbe53192025-04-14 22:13:15 +02005678 if (!is_cpt_function)
5679 {
5680 compl_col = col;
5681 compl_length = len;
5682 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005683 ret = OK;
5684#endif
5685
5686 return ret;
5687}
5688
5689/*
5690 * Get the pattern, column and length for spell completion.
5691 * Sets the global variables: compl_col, compl_length and compl_pattern.
5692 * Uses the global variable: spell_bad_len
5693 */
5694 static int
5695get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
5696{
5697 int ret = FAIL;
5698#ifdef FEAT_SPELL
5699 char_u *line;
5700
5701 if (spell_bad_len > 0)
5702 compl_col = curs_col - spell_bad_len;
5703 else
5704 compl_col = spell_word_start(startcol);
5705 if (compl_col >= (colnr_T)startcol)
5706 {
5707 compl_length = 0;
5708 compl_col = curs_col;
5709 }
5710 else
5711 {
5712 spell_expand_check_cap(compl_col);
5713 compl_length = (int)curs_col - compl_col;
5714 }
5715 // Need to obtain "line" again, it may have become invalid.
5716 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01005717 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
5718 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02005719 {
John Marriott5e6ea922024-11-23 14:01:57 +01005720 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005721 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02005722 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005723
John Marriott5e6ea922024-11-23 14:01:57 +01005724 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005725 ret = OK;
5726#endif
5727
5728 return ret;
5729}
5730
5731/*
5732 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005733 * "startcol" - start column number of the completion pattern/text
5734 * "cur_col" - current cursor column
5735 * On return, "line_invalid" is set to TRUE, if the current line may have
5736 * become invalid and needs to be fetched again.
5737 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005738 */
5739 static int
5740compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
5741{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005742 if (ctrl_x_mode_normal()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005743 || (ctrl_x_mode & CTRL_X_WANT_IDENT
5744 && !thesaurus_func_complete(ctrl_x_mode)))
5745 {
5746 return get_normal_compl_info(line, startcol, curs_col);
5747 }
5748 else if (ctrl_x_mode_line_or_eval())
5749 {
5750 return get_wholeline_compl_info(line, curs_col);
5751 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005752 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005753 {
5754 return get_filename_compl_info(line, startcol, curs_col);
5755 }
5756 else if (ctrl_x_mode == CTRL_X_CMDLINE)
5757 {
5758 return get_cmdline_compl_info(line, curs_col);
5759 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005760 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005761 || thesaurus_func_complete(ctrl_x_mode))
5762 {
Girish Palyacbe53192025-04-14 22:13:15 +02005763 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005764 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005765 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005766 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005767 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005768 {
5769 if (get_spell_compl_info(startcol, curs_col) == FAIL)
5770 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005771 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005772 }
5773 else
5774 {
5775 internal_error("ins_complete()");
5776 return FAIL;
5777 }
5778
5779 return OK;
5780}
5781
5782/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005783 * Continue an interrupted completion mode search in "line".
5784 *
5785 * If this same ctrl_x_mode has been interrupted use the text from
5786 * "compl_startpos" to the cursor as a pattern to add a new word instead of
5787 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
5788 * the same line as the cursor then fix it (the line has been split because it
5789 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
5790 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005791 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005792 static void
5793ins_compl_continue_search(char_u *line)
5794{
5795 // it is a continued search
5796 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005797 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
5798 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005799 {
5800 if (compl_startpos.lnum != curwin->w_cursor.lnum)
5801 {
5802 // line (probably) wrapped, set compl_startpos to the
5803 // first non_blank in the line, if it is not a wordchar
5804 // include it to get a better pattern, but then we don't
5805 // want the "\\<" prefix, check it below
5806 compl_col = (colnr_T)getwhitecols(line);
5807 compl_startpos.col = compl_col;
5808 compl_startpos.lnum = curwin->w_cursor.lnum;
5809 compl_cont_status &= ~CONT_SOL; // clear SOL if present
5810 }
5811 else
5812 {
5813 // S_IPOS was set when we inserted a word that was at the
5814 // beginning of the line, which means that we'll go to SOL
5815 // mode but first we need to redefine compl_startpos
5816 if (compl_cont_status & CONT_S_IPOS)
5817 {
5818 compl_cont_status |= CONT_SOL;
5819 compl_startpos.col = (colnr_T)(skipwhite(
5820 line + compl_length
5821 + compl_startpos.col) - line);
5822 }
5823 compl_col = compl_startpos.col;
5824 }
5825 compl_length = curwin->w_cursor.col - (int)compl_col;
5826 // IObuff is used to add a "word from the next line" would we
5827 // have enough space? just being paranoid
5828#define MIN_SPACE 75
5829 if (compl_length > (IOSIZE - MIN_SPACE))
5830 {
5831 compl_cont_status &= ~CONT_SOL;
5832 compl_length = (IOSIZE - MIN_SPACE);
5833 compl_col = curwin->w_cursor.col - compl_length;
5834 }
5835 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
5836 if (compl_length < 1)
5837 compl_cont_status &= CONT_LOCAL;
5838 }
5839 else if (ctrl_x_mode_line_or_eval())
5840 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
5841 else
5842 compl_cont_status = 0;
5843}
5844
5845/*
5846 * start insert mode completion
5847 */
5848 static int
5849ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005850{
5851 char_u *line;
5852 int startcol = 0; // column where searched text starts
5853 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005854 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005855 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02005856 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005857
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005858 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005859
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005860 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005861 did_si = FALSE;
5862 can_si = FALSE;
5863 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005864 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005865 return FAIL;
5866
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005867 line = ml_get(curwin->w_cursor.lnum);
5868 curs_col = curwin->w_cursor.col;
5869 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01005870 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005871
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005872 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
5873 && compl_cont_mode == ctrl_x_mode)
5874 // this same ctrl-x_mode was interrupted previously. Continue the
5875 // completion.
5876 ins_compl_continue_search(line);
5877 else
5878 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005879
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005880 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005881 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005882 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005883 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005884 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
5885 compl_cont_status = 0;
5886 compl_cont_status |= CONT_N_ADDS;
5887 compl_startpos = curwin->w_cursor;
5888 startcol = (int)curs_col;
5889 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005890 }
5891
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005892 // Work out completion pattern and original text -- webb
5893 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
5894 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005895 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
5896 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005897 // restore did_ai, so that adding comment leader works
5898 did_ai = save_did_ai;
5899 return FAIL;
5900 }
5901 // If "line" was changed while getting completion info get it again.
5902 if (line_invalid)
5903 line = ml_get(curwin->w_cursor.lnum);
5904
glepnir7cfe6932024-09-15 20:06:28 +02005905 int in_fuzzy = get_cot_flags() & COT_FUZZY;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005906 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005907 {
5908 edit_submode_pre = (char_u *)_(" Adding");
5909 if (ctrl_x_mode_line_or_eval())
5910 {
5911 // Insert a new line, keep indentation but ignore 'comments'.
5912 char_u *old = curbuf->b_p_com;
5913
5914 curbuf->b_p_com = (char_u *)"";
5915 compl_startpos.lnum = curwin->w_cursor.lnum;
5916 compl_startpos.col = compl_col;
5917 ins_eol('\r');
5918 curbuf->b_p_com = old;
5919 compl_length = 0;
5920 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01005921 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005922 }
glepnir7cfe6932024-09-15 20:06:28 +02005923 else if (ctrl_x_mode_normal() && in_fuzzy)
5924 {
5925 compl_startpos = curwin->w_cursor;
5926 compl_cont_status &= CONT_S_IPOS;
5927 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005928 }
5929 else
5930 {
5931 edit_submode_pre = NULL;
5932 compl_startpos.col = compl_col;
5933 }
5934
5935 if (compl_cont_status & CONT_LOCAL)
5936 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
5937 else
5938 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
5939
5940 // If any of the original typed text has been changed we need to fix
5941 // the redo buffer.
5942 ins_compl_fixRedoBufForLeader(NULL);
5943
5944 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01005945 VIM_CLEAR_STRING(compl_orig_text);
5946 compl_orig_text.length = (size_t)compl_length;
5947 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005948 if (p_ic)
5949 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01005950 if (compl_orig_text.string == NULL
5951 || ins_compl_add(compl_orig_text.string,
5952 (int)compl_orig_text.length,
5953 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005954 {
John Marriott5e6ea922024-11-23 14:01:57 +01005955 VIM_CLEAR_STRING(compl_pattern);
5956 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005957 return FAIL;
5958 }
5959
5960 // showmode might reset the internal line pointers, so it must
5961 // be called before line = ml_get(), or when this address is no
5962 // longer needed. -- Acevedo.
5963 edit_submode_extra = (char_u *)_("-- Searching...");
5964 edit_submode_highl = HLF_COUNT;
5965 showmode();
5966 edit_submode_extra = NULL;
5967 out_flush();
5968
5969 return OK;
5970}
5971
5972/*
5973 * display the completion status message
5974 */
5975 static void
5976ins_compl_show_statusmsg(void)
5977{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005978 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005979 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005980 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005981 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00005982 ? (char_u *)_("Hit end of paragraph")
5983 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005984 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005985 }
5986
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005987 if (edit_submode_extra == NULL)
5988 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005989 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005990 {
5991 edit_submode_extra = (char_u *)_("Back at original");
5992 edit_submode_highl = HLF_W;
5993 }
5994 else if (compl_cont_status & CONT_S_IPOS)
5995 {
5996 edit_submode_extra = (char_u *)_("Word from other line");
5997 edit_submode_highl = HLF_COUNT;
5998 }
5999 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6000 {
6001 edit_submode_extra = (char_u *)_("The only match");
6002 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006003 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006004 }
6005 else
6006 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006007#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006008 // Update completion sequence number when needed.
6009 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006010 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006011#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006012 // The match should always have a sequence number now, this is
6013 // just a safety check.
6014 if (compl_curr_match->cp_number != -1)
6015 {
6016 // Space for 10 text chars. + 2x10-digit no.s = 31.
6017 // Translations may need more than twice that.
6018 static char_u match_ref[81];
6019
6020 if (compl_matches > 0)
6021 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006022 _("match %d of %d"),
6023 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006024 else
6025 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006026 _("match %d"),
6027 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006028 edit_submode_extra = match_ref;
6029 edit_submode_highl = HLF_R;
6030 if (dollar_vcol >= 0)
6031 curs_columns(FALSE);
6032 }
6033 }
6034 }
6035
6036 // Show a message about what (completion) mode we're in.
6037 if (!compl_opt_suppress_empty)
6038 {
6039 showmode();
6040 if (!shortmess(SHM_COMPLETIONMENU))
6041 {
6042 if (edit_submode_extra != NULL)
6043 {
6044 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006045 {
6046 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006047 msg_attr((char *)edit_submode_extra,
6048 edit_submode_highl < HLF_COUNT
6049 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006050 msg_hist_off = FALSE;
6051 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006052 }
6053 else
6054 msg_clr_cmdline(); // necessary for "noshowmode"
6055 }
6056 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006057}
6058
6059/*
6060 * Do Insert mode completion.
6061 * Called when character "c" was typed, which has a meaning for completion.
6062 * Returns OK if completion was done, FAIL if something failed (out of mem).
6063 */
6064 int
6065ins_complete(int c, int enable_pum)
6066{
6067 int n;
6068 int save_w_wrow;
6069 int save_w_leftcol;
6070 int insert_match;
6071
6072 compl_direction = ins_compl_key2dir(c);
6073 insert_match = ins_compl_use_match(c);
6074
6075 if (!compl_started)
6076 {
6077 if (ins_compl_start() == FAIL)
6078 return FAIL;
6079 }
6080 else if (insert_match && stop_arrow() == FAIL)
6081 return FAIL;
6082
6083 compl_shown_match = compl_curr_match;
6084 compl_shows_dir = compl_direction;
6085
6086 // Find next match (and following matches).
6087 save_w_wrow = curwin->w_wrow;
6088 save_w_leftcol = curwin->w_leftcol;
6089 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
6090
6091 // may undisplay the popup menu
6092 ins_compl_upd_pum();
6093
6094 if (n > 1) // all matches have been found
6095 compl_matches = n;
6096 compl_curr_match = compl_shown_match;
6097 compl_direction = compl_shows_dir;
6098
6099 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6100 // mode.
6101 if (got_int && !global_busy)
6102 {
6103 (void)vgetc();
6104 got_int = FALSE;
6105 }
6106
6107 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006108 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006109 {
6110 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6111 // because we couldn't expand anything at first place, but if we used
6112 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6113 // (such as M in M'exico) if not tried already. -- Acevedo
6114 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006115 || compl_status_adding()
6116 || (ctrl_x_mode_not_default()
6117 && !ctrl_x_mode_path_patterns()
6118 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006119 compl_cont_status &= ~CONT_N_ADDS;
6120 }
6121
6122 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6123 compl_cont_status |= CONT_S_IPOS;
6124 else
6125 compl_cont_status &= ~CONT_S_IPOS;
6126
6127 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006128
6129 // Show the popup menu, unless we got interrupted.
6130 if (enable_pum && !compl_interrupted)
6131 show_pum(save_w_wrow, save_w_leftcol);
6132
6133 compl_was_interrupted = compl_interrupted;
6134 compl_interrupted = FALSE;
6135
6136 return OK;
6137}
6138
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006139/*
6140 * Remove (if needed) and show the popup menu
6141 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006142 static void
6143show_pum(int prev_w_wrow, int prev_w_leftcol)
6144{
6145 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006146 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006147 RedrawingDisabled = 0;
6148
6149 // If the cursor moved or the display scrolled we need to remove the pum
6150 // first.
6151 setcursor();
6152 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6153 ins_compl_del_pum();
6154
6155 ins_compl_show_pum();
6156 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006157
6158 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006159}
6160
6161/*
6162 * Looks in the first "len" chars. of "src" for search-metachars.
6163 * If dest is not NULL the chars. are copied there quoting (with
6164 * a backslash) the metachars, and dest would be NUL terminated.
6165 * Returns the length (needed) of dest
6166 */
6167 static unsigned
6168quote_meta(char_u *dest, char_u *src, int len)
6169{
6170 unsigned m = (unsigned)len + 1; // one extra for the NUL
6171
6172 for ( ; --len >= 0; src++)
6173 {
6174 switch (*src)
6175 {
6176 case '.':
6177 case '*':
6178 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006179 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006180 break;
6181 // FALLTHROUGH
6182 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006183 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006184 break;
6185 // FALLTHROUGH
6186 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006187 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006188 break;
6189 // FALLTHROUGH
6190 case '^': // currently it's not needed.
6191 case '$':
6192 m++;
6193 if (dest != NULL)
6194 *dest++ = '\\';
6195 break;
6196 }
6197 if (dest != NULL)
6198 *dest++ = *src;
6199 // Copy remaining bytes of a multibyte character.
6200 if (has_mbyte)
6201 {
6202 int i, mb_len;
6203
6204 mb_len = (*mb_ptr2len)(src) - 1;
6205 if (mb_len > 0 && len >= mb_len)
6206 for (i = 0; i < mb_len; ++i)
6207 {
6208 --len;
6209 ++src;
6210 if (dest != NULL)
6211 *dest++ = *src;
6212 }
6213 }
6214 }
6215 if (dest != NULL)
6216 *dest = NUL;
6217
6218 return m;
6219}
6220
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006221#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006222 void
6223free_insexpand_stuff(void)
6224{
John Marriott5e6ea922024-11-23 14:01:57 +01006225 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006226# ifdef FEAT_EVAL
6227 free_callback(&cfu_cb);
6228 free_callback(&ofu_cb);
6229 free_callback(&tsrfu_cb);
6230# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006231}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006232#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006233
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006234#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006235/*
6236 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6237 * spelled word, if there is one.
6238 */
6239 static void
6240spell_back_to_badword(void)
6241{
6242 pos_T tpos = curwin->w_cursor;
6243
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006244 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006245 if (curwin->w_cursor.col != tpos.col)
6246 start_arrow(&tpos);
6247}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006248#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006249
6250/*
6251 * Reset the info associated with completion sources.
6252 */
6253 static void
6254cpt_compl_src_clear(void)
6255{
6256 VIM_CLEAR(cpt_func_refresh_always);
6257 cpt_value_idx = -1;
6258 cpt_value_count = 0;
6259}
6260
6261/*
6262 * Initialize the info associated with completion sources.
6263 */
6264 static int
6265cpt_compl_src_init(char_u *cpt_str)
6266{
6267 int count = 0;
6268 char_u *p = cpt_str;
6269
6270 while (*p)
6271 {
6272 while (*p == ',' || *p == ' ') // Skip delimiters
6273 p++;
6274 if (*p) // If not end of string, count this segment
6275 {
6276 count++;
6277 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6278 }
6279 }
6280 cpt_compl_src_clear();
6281 cpt_value_count = count;
6282 if (count > 0)
6283 {
6284 cpt_func_refresh_always = ALLOC_CLEAR_MULT(int, count);
6285 if (cpt_func_refresh_always == NULL)
6286 {
6287 cpt_value_count = 0;
6288 return FAIL;
6289 }
6290 }
6291 return OK;
6292}
6293
6294/*
6295 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
6296 */
6297 static int
6298is_cpt_func_refresh_always(void)
6299{
6300#ifdef FEAT_COMPL_FUNC
6301 int i;
6302
6303 for (i = 0; i < cpt_value_count; i++)
6304 if (cpt_func_refresh_always[i])
6305 return TRUE;
6306#endif
6307 return FALSE;
6308}
6309
6310/*
6311 * Make the completion list non-cyclic.
6312 */
6313#ifdef FEAT_COMPL_FUNC
6314 static void
6315ins_compl_make_linear(void)
6316{
6317 compl_T *m;
6318
6319 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
6320 return;
6321 m = compl_first_match->cp_prev;
6322 m->cp_next = NULL;
6323 compl_first_match->cp_prev = NULL;
6324}
6325#endif
6326
6327/*
6328 * Remove the matches linked to the current completion source (as indicated by
6329 * cpt_value_idx) from the completion list.
6330 */
6331#ifdef FEAT_COMPL_FUNC
6332 static compl_T *
6333remove_old_matches(void)
6334{
6335 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
6336 compl_T *current, *next;
6337 int compl_shown_removed = FALSE;
6338 int forward = compl_dir_forward();
6339
6340 // Identify the sublist of old matches that needs removal
6341 for (current = compl_first_match; current != NULL; current = current->cp_next)
6342 {
6343 if (current->cp_cpt_value_idx < cpt_value_idx && (forward || (!forward && !insert_at)))
6344 insert_at = current;
6345
6346 if (current->cp_cpt_value_idx == cpt_value_idx)
6347 {
6348 if (!sublist_start)
6349 sublist_start = current;
6350 sublist_end = current;
6351 if (!compl_shown_removed && compl_shown_match == current)
6352 compl_shown_removed = TRUE;
6353 }
6354
6355 if ((forward && current->cp_cpt_value_idx > cpt_value_idx) || (!forward && insert_at))
6356 break;
6357 }
6358
6359 // Re-assign compl_shown_match if necessary
6360 if (compl_shown_removed)
6361 {
6362 if (forward)
6363 compl_shown_match = compl_first_match;
6364 else
6365 { // Last node will have the prefix that is being completed
6366 for (current = compl_first_match; current->cp_next != NULL; current = current->cp_next)
6367 ;
6368 compl_shown_match = current;
6369 }
6370 }
6371
6372 if (!sublist_start) // No nodes to remove
6373 return insert_at;
6374
6375 // Update links to remove sublist
6376 if (sublist_start->cp_prev)
6377 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
6378 else
6379 compl_first_match = sublist_end->cp_next;
6380
6381 if (sublist_end->cp_next)
6382 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
6383
6384 // Free all nodes in the sublist
6385 sublist_end->cp_next = NULL;
6386 for (current = sublist_start; current != NULL; current = next)
6387 {
6388 next = current->cp_next;
6389 ins_compl_item_free(current);
6390 }
6391
6392 return insert_at;
6393}
6394#endif
6395
6396/*
6397 * Retrieve completion matches using the callback function "cb" and store the
6398 * 'refresh:always' flag.
6399 */
6400#ifdef FEAT_COMPL_FUNC
6401 static void
6402get_cpt_func_completion_matches(callback_T *cb UNUSED)
6403{
6404 int ret;
6405 int startcol;
6406
6407 VIM_CLEAR_STRING(cpt_compl_pattern);
6408 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol);
6409 if (ret == FAIL && startcol == -3)
6410 cpt_func_refresh_always[cpt_value_idx] = FALSE;
6411 else if (ret == OK)
6412 {
6413 expand_by_function(0, cpt_compl_pattern.string, cb);
6414 cpt_func_refresh_always[cpt_value_idx] = compl_opt_refresh_always;
6415 compl_opt_refresh_always = FALSE;
6416 }
6417}
6418#endif
6419
6420/*
6421 * Retrieve completion matches from functions in the 'cpt' option where the
6422 * 'refresh:always' flag is set.
6423 */
6424 static void
6425cpt_compl_refresh(void)
6426{
6427#ifdef FEAT_COMPL_FUNC
6428 char_u *cpt;
6429 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02006430 callback_T *cb = NULL;
Girish Palyacbe53192025-04-14 22:13:15 +02006431
6432 // Make the completion list linear (non-cyclic)
6433 ins_compl_make_linear();
6434 // Make a copy of 'cpt' in case the buffer gets wiped out
6435 cpt = vim_strsave(curbuf->b_p_cpt);
6436
6437 cpt_value_idx = 0;
6438 for (p = cpt; *p; cpt_value_idx++)
6439 {
6440 while (*p == ',' || *p == ' ') // Skip delimiters
6441 p++;
6442
6443 if (cpt_func_refresh_always[cpt_value_idx])
6444 {
6445 if (*p == 'o')
6446 cb = &curbuf->b_ofu_cb;
6447 else if (*p == 'f')
6448 cb = (*(p + 1) != ',' && *(p + 1) != NUL)
6449 ? get_cpt_func_callback(p + 1) : &curbuf->b_cfu_cb;
6450 if (cb)
6451 {
6452 compl_curr_match = remove_old_matches();
6453 get_cpt_func_completion_matches(cb);
6454 }
6455 }
6456
6457 copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
6458 }
6459 cpt_value_idx = -1;
6460
6461 vim_free(cpt);
6462 // Make the list cyclic
6463 compl_matches = ins_compl_make_cyclic();
6464#endif
6465}