blob: 7e3de60e846060917700d38c3fc551ded3e283fb [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
glepnir05460682025-05-26 18:23:27 +020041# define CTRL_X_REGISTER 18 // complete words from registers
Bram Moolenaar7591bb32019-03-30 13:53:47 +010042
43# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
44
45// Message for CTRL-X mode, index is ctrl_x_mode.
46static char *ctrl_x_msgs[] =
47{
48 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
glepnir05460682025-05-26 18:23:27 +020049 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010050 NULL, // CTRL_X_SCROLL: depends on state
51 N_(" Whole line completion (^L^N^P)"),
52 N_(" File name completion (^F^N^P)"),
53 N_(" Tag completion (^]^N^P)"),
54 N_(" Path pattern completion (^N^P)"),
55 N_(" Definition completion (^D^N^P)"),
56 NULL, // CTRL_X_FINISHED
57 N_(" Dictionary completion (^K^N^P)"),
58 N_(" Thesaurus completion (^T^N^P)"),
59 N_(" Command-line completion (^V^N^P)"),
60 N_(" User defined completion (^U^N^P)"),
61 N_(" Omni completion (^O^N^P)"),
zeertzjq7002c052024-06-21 07:55:07 +020062 N_(" Spelling suggestion (^S^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010063 N_(" Keyword Local completion (^N^P)"),
64 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020065 N_(" Command-line completion (^V^N^P)"),
glepnir05460682025-05-26 18:23:27 +020066 N_(" Register completion (^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010067};
68
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020069#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010070static char *ctrl_x_mode_names[] = {
Hirohito Higashi355db992025-04-28 18:07:02 +020071 "keyword",
72 "ctrl_x",
73 "scroll",
74 "whole_line",
75 "files",
76 "tags",
77 "path_patterns",
78 "path_defines",
79 "unknown", // CTRL_X_FINISHED
80 "dictionary",
81 "thesaurus",
82 "cmdline",
83 "function",
84 "omni",
85 "spell",
86 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
87 "eval",
88 "cmdline",
glepnir05460682025-05-26 18:23:27 +020089 "register",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010090};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020091#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010092
93/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +010094 * Structure used to store one match for insert completion.
95 */
96typedef struct compl_S compl_T;
97struct compl_S
98{
99 compl_T *cp_next;
100 compl_T *cp_prev;
glepnir80b66202024-11-27 21:53:53 +0100101 compl_T *cp_match_next; // matched next compl_T
John Marriott5e6ea922024-11-23 14:01:57 +0100102 string_T cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200103 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100104#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100105 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100106#endif
glepnir0fe17f82024-10-08 22:26:44 +0200107 char_u *cp_fname; // file containing the match, allocated when
108 // cp_flags has CP_FREE_FNAME
109 int cp_flags; // CP_ values
110 int cp_number; // sequence number
Girish Palyab1565882025-04-15 20:16:00 +0200111 int cp_score; // fuzzy match score or proximity score
glepnird4088ed2024-12-31 10:55:22 +0100112 int cp_in_match_array; // collected by compl_match_array
glepnir7baa0142024-10-09 20:19:25 +0200113 int cp_user_abbr_hlattr; // highlight attribute for abbr
glepnir0fe17f82024-10-08 22:26:44 +0200114 int cp_user_kind_hlattr; // highlight attribute for kind
Girish Palya0ac1eb32025-04-16 20:18:33 +0200115 int cp_cpt_source_idx; // index of this match's source in 'cpt' option
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100116};
117
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200118// values for cp_flags
119# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
120# define CP_FREE_FNAME 2 // cp_fname is allocated
121# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
122# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
123# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar440cf092021-04-03 20:13:30 +0200124# define CP_FAST 32 // use fast_breakcheck instead of ui_breakcheck
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100125
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100126/*
127 * All the current matches are stored in a list.
128 * "compl_first_match" points to the start of the list.
129 * "compl_curr_match" points to the currently selected entry.
130 * "compl_shown_match" is different from compl_curr_match during
Girish Palyacbe53192025-04-14 22:13:15 +0200131 * ins_compl_get_exp(), when new matches are added to the list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000132 * "compl_old_match" points to previous "compl_curr_match".
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100133 */
134static compl_T *compl_first_match = NULL;
135static compl_T *compl_curr_match = NULL;
136static compl_T *compl_shown_match = NULL;
137static compl_T *compl_old_match = NULL;
138
glepnirf31cfa22025-03-06 21:59:13 +0100139// list used to store the compl_T which have the max score
140// used for completefuzzycollect
141static compl_T **compl_best_matches = NULL;
142static int compl_num_bests = 0;
143// inserted a longest when completefuzzycollect enabled
144static int compl_cfc_longest_ins = FALSE;
145
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100146// After using a cursor key <Enter> selects a match in the popup menu,
147// otherwise it inserts a line break.
148static int compl_enter_selects = FALSE;
149
150// When "compl_leader" is not NULL only matches that start with this string
151// are used.
John Marriott5e6ea922024-11-23 14:01:57 +0100152static string_T compl_leader = {NULL, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100153
154static int compl_get_longest = FALSE; // put longest common string
155 // in compl_leader
156
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100157// Selected one of the matches. When FALSE the match was edited or using the
158// longest common string.
159static int compl_used_match;
160
161// didn't finish finding completions.
162static int compl_was_interrupted = FALSE;
163
164// Set when character typed while looking for matches and it means we should
165// stop looking for matches.
166static int compl_interrupted = FALSE;
167
168static int compl_restarting = FALSE; // don't insert match
169
170// When the first completion is done "compl_started" is set. When it's
171// FALSE the word to be completed must be located.
172static int compl_started = FALSE;
173
174// Which Ctrl-X mode are we in?
175static int ctrl_x_mode = CTRL_X_NORMAL;
176
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000177static int compl_matches = 0; // number of completion matches
Girish Palyacbe53192025-04-14 22:13:15 +0200178static string_T compl_pattern = {NULL, 0}; // search pattern for matching items
179#ifdef FEAT_COMPL_FUNC
180static string_T cpt_compl_pattern = {NULL, 0}; // pattern returned by func in 'cpt'
181#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100182static int compl_direction = FORWARD;
183static int compl_shows_dir = FORWARD;
184static int compl_pending = 0; // > 1 for postponed CTRL-N
185static pos_T compl_startpos;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000186// Length in bytes of the text being completed (this is deleted to be replaced
187// by the match.)
188static int compl_length = 0;
glepnir76bdb822025-02-08 19:04:51 +0100189static linenr_T compl_lnum = 0; // lnum where the completion start
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100190static colnr_T compl_col = 0; // column where the text starts
191 // that is being completed
glepnir6a38aff2024-12-16 21:56:16 +0100192static colnr_T compl_ins_end_col = 0;
John Marriott5e6ea922024-11-23 14:01:57 +0100193static string_T compl_orig_text = {NULL, 0}; // text as it was before
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100194 // completion started
195static int compl_cont_mode = 0;
196static expand_T compl_xp;
197
glepnircf7f0122025-04-15 19:02:00 +0200198static win_T *compl_curr_win = NULL; // win where completion is active
199static buf_T *compl_curr_buf = NULL; // buf where completion is active
200
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000201// List of flags for method of completion.
202static int compl_cont_status = 0;
203# define CONT_ADDING 1 // "normal" or "adding" expansion
204# define CONT_INTRPT (2 + 4) // a ^X interrupted the current expansion
205 // it's set only iff N_ADDS is set
206# define CONT_N_ADDS 4 // next ^X<> will add-new or expand-current
207# define CONT_S_IPOS 8 // next ^X<> will set initial_pos?
208 // if so, word-wise-expansion will set SOL
209# define CONT_SOL 16 // pattern includes start of line, just for
210 // word-wise expansion, not set for ^X^L
211# define CONT_LOCAL 32 // for ctrl_x_mode 0, ^X^P/^X^N do a local
212 // expansion, (eg use complete=.)
213
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100214static int compl_opt_refresh_always = FALSE;
215static int compl_opt_suppress_empty = FALSE;
216
glepnira218cc62024-06-03 19:32:39 +0200217static int compl_selected_item = -1;
218
glepnir8159fb12024-07-17 20:32:54 +0200219static int *compl_fuzzy_scores;
220
Girish Palya0ac1eb32025-04-16 20:18:33 +0200221// Define the structure for completion source (in 'cpt' option) information
222typedef struct cpt_source_T
223{
Girish Palya98c29db2025-06-01 19:40:00 +0200224 int cs_refresh_always; // Whether 'refresh:always' is set for func
225 int cs_startcol; // Start column returned by func
226 int cs_max_matches; // Max items to display from this source
Girish Palya0ac1eb32025-04-16 20:18:33 +0200227} cpt_source_T;
228
Girish Palyaba11e782025-07-05 16:11:44 +0200229#define STARTCOL_NONE -9
Girish Palya0ac1eb32025-04-16 20:18:33 +0200230static cpt_source_T *cpt_sources_array; // Pointer to the array of completion sources
231static int cpt_sources_count; // Total number of completion sources specified in the 'cpt' option
Girish Palya7c621052025-05-26 19:41:59 +0200232static int cpt_sources_index = -1; // Index of the current completion source being expanded
Girish Palyacbe53192025-04-14 22:13:15 +0200233
glepnir6a38aff2024-12-16 21:56:16 +0100234// "compl_match_array" points the currently displayed list of entries in the
235// popup menu. It is NULL when there is no popup menu.
236static pumitem_T *compl_match_array = NULL;
237static int compl_match_arraysize;
238
glepnirf31cfa22025-03-06 21:59:13 +0100239static 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 +0100240static void ins_compl_longest_match(compl_T *match);
241static void ins_compl_del_pum(void);
242static 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 +0100243static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100244static int ins_compl_need_restart(void);
245static void ins_compl_new_leader(void);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000246static int get_compl_len(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100247static void ins_compl_restart(void);
John Marriott5e6ea922024-11-23 14:01:57 +0100248static void ins_compl_set_original_text(char_u *str, size_t len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100249static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
250# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
251static void ins_compl_add_list(list_T *list);
252static void ins_compl_add_dict(dict_T *dict);
Girish Palyacbe53192025-04-14 22:13:15 +0200253static int get_userdefined_compl_info(colnr_T curs_col, callback_T *cb, int *startcol);
Girish Palyaba11e782025-07-05 16:11:44 +0200254static void get_cpt_func_completion_matches(callback_T *cb);
Girish Palya98c29db2025-06-01 19:40:00 +0200255static callback_T *get_callback_if_cpt_func(char_u *p);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100256# endif
Girish Palya98c29db2025-06-01 19:40:00 +0200257static int setup_cpt_sources(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200258static int is_cpt_func_refresh_always(void);
Girish Palya0ac1eb32025-04-16 20:18:33 +0200259static void cpt_sources_clear(void);
Girish Palyacbe53192025-04-14 22:13:15 +0200260static void cpt_compl_refresh(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100261static int ins_compl_key2dir(int c);
262static int ins_compl_pum_key(int c);
263static int ins_compl_key2count(int c);
264static void show_pum(int prev_w_wrow, int prev_w_leftcol);
265static unsigned quote_meta(char_u *dest, char_u *str, int len);
glepnir76bdb822025-02-08 19:04:51 +0100266static int ins_compl_has_multiple(void);
267static void ins_compl_expand_multiple(char_u *str);
glepnirf31cfa22025-03-06 21:59:13 +0100268static void ins_compl_longest_insert(char_u *prefix);
Girish Palya8cd42a52025-06-05 21:04:29 +0200269static void ins_compl_make_linear(void);
270static int ins_compl_make_cyclic(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100271
272#ifdef FEAT_SPELL
273static void spell_back_to_badword(void);
274static int spell_bad_len = 0; // length of located bad word
275#endif
276
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100277/*
278 * CTRL-X pressed in Insert mode.
279 */
280 void
281ins_ctrl_x(void)
282{
zeertzjqdca29d92021-08-31 19:12:51 +0200283 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100284 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000285 // if the next ^X<> won't ADD nothing, then reset compl_cont_status
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100286 if (compl_cont_status & CONT_N_ADDS)
287 compl_cont_status |= CONT_INTRPT;
288 else
289 compl_cont_status = 0;
290 // We're not sure which CTRL-X mode it will be yet
291 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
292 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
293 edit_submode_pre = NULL;
294 showmode();
295 }
zeertzjqdca29d92021-08-31 19:12:51 +0200296 else
297 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
298 // CTRL-V look like CTRL-N
299 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100300
LemonBoy2bf52dd2022-04-09 18:17:34 +0100301 may_trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100302}
303
304/*
305 * Functions to check the current CTRL-X mode.
306 */
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000307int ctrl_x_mode_none(void)
308 { return ctrl_x_mode == 0; }
309int ctrl_x_mode_normal(void)
310 { return ctrl_x_mode == CTRL_X_NORMAL; }
311int ctrl_x_mode_scroll(void)
312 { return ctrl_x_mode == CTRL_X_SCROLL; }
313int ctrl_x_mode_whole_line(void)
314 { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
315int ctrl_x_mode_files(void)
316 { return ctrl_x_mode == CTRL_X_FILES; }
317int ctrl_x_mode_tags(void)
318 { return ctrl_x_mode == CTRL_X_TAGS; }
319int ctrl_x_mode_path_patterns(void)
320 { return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
321int ctrl_x_mode_path_defines(void)
322 { return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
323int ctrl_x_mode_dictionary(void)
324 { return ctrl_x_mode == CTRL_X_DICTIONARY; }
325int ctrl_x_mode_thesaurus(void)
326 { return ctrl_x_mode == CTRL_X_THESAURUS; }
327int ctrl_x_mode_cmdline(void)
328 { return ctrl_x_mode == CTRL_X_CMDLINE
zeertzjqdca29d92021-08-31 19:12:51 +0200329 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaarebfec1c2023-01-22 21:14:53 +0000330int ctrl_x_mode_function(void)
331 { return ctrl_x_mode == CTRL_X_FUNCTION; }
332int ctrl_x_mode_omni(void)
333 { return ctrl_x_mode == CTRL_X_OMNI; }
334int ctrl_x_mode_spell(void)
335 { return ctrl_x_mode == CTRL_X_SPELL; }
336static int ctrl_x_mode_eval(void)
337 { return ctrl_x_mode == CTRL_X_EVAL; }
338int ctrl_x_mode_line_or_eval(void)
339 { return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
glepnir05460682025-05-26 18:23:27 +0200340int ctrl_x_mode_register(void)
341 { return ctrl_x_mode == CTRL_X_REGISTER; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100342
343/*
344 * Whether other than default completion has been selected.
345 */
346 int
347ctrl_x_mode_not_default(void)
348{
349 return ctrl_x_mode != CTRL_X_NORMAL;
350}
351
352/*
zeertzjqdca29d92021-08-31 19:12:51 +0200353 * Whether CTRL-X was typed without a following character,
354 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100355 */
356 int
357ctrl_x_mode_not_defined_yet(void)
358{
359 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
360}
361
362/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000363 * Return TRUE if currently in "normal" or "adding" insert completion matches
364 * state
365 */
366 int
367compl_status_adding(void)
368{
369 return compl_cont_status & CONT_ADDING;
370}
371
372/*
373 * Return TRUE if the completion pattern includes start of line, just for
374 * word-wise expansion.
375 */
376 int
377compl_status_sol(void)
378{
379 return compl_cont_status & CONT_SOL;
380}
381
382/*
383 * Return TRUE if ^X^P/^X^N will do a local completion (i.e. use complete=.)
384 */
385 int
386compl_status_local(void)
387{
388 return compl_cont_status & CONT_LOCAL;
389}
390
391/*
392 * Clear the completion status flags
393 */
394 void
395compl_status_clear(void)
396{
397 compl_cont_status = 0;
398}
399
400/*
401 * Return TRUE if completion is using the forward direction matches
402 */
403 static int
404compl_dir_forward(void)
405{
406 return compl_direction == FORWARD;
407}
408
409/*
410 * Return TRUE if currently showing forward completion matches
411 */
412 static int
413compl_shows_dir_forward(void)
414{
415 return compl_shows_dir == FORWARD;
416}
417
418/*
419 * Return TRUE if currently showing backward completion matches
420 */
421 static int
422compl_shows_dir_backward(void)
423{
424 return compl_shows_dir == BACKWARD;
425}
426
427/*
428 * Return TRUE if the 'dictionary' or 'thesaurus' option can be used.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100429 */
430 int
431has_compl_option(int dict_opt)
432{
433 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200434#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100435 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200436#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100437 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100438 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
439#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100440 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100441#endif
442 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100443 {
444 ctrl_x_mode = CTRL_X_NORMAL;
445 edit_submode = NULL;
446 msg_attr(dict_opt ? _("'dictionary' option is empty")
447 : _("'thesaurus' option is empty"),
448 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100449 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100450 {
451 vim_beep(BO_COMPL);
452 setcursor();
453 out_flush();
454#ifdef FEAT_EVAL
455 if (!get_vim_var_nr(VV_TESTING))
456#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100457 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100458 }
459 return FALSE;
460 }
461 return TRUE;
462}
463
464/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000465 * Is the character "c" a valid key to go to or keep us in CTRL-X mode?
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100466 * This depends on the current mode.
467 */
468 int
469vim_is_ctrl_x_key(int c)
470{
471 // Always allow ^R - let its results then be checked
glepnir05460682025-05-26 18:23:27 +0200472 if (c == Ctrl_R && ctrl_x_mode != CTRL_X_REGISTER)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100473 return TRUE;
474
475 // Accept <PageUp> and <PageDown> if the popup menu is visible.
476 if (ins_compl_pum_key(c))
477 return TRUE;
478
479 switch (ctrl_x_mode)
480 {
481 case 0: // Not in any CTRL-X mode
482 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
483 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200484 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100485 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
486 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
487 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
488 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
489 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200490 || c == Ctrl_S || c == Ctrl_K || c == 's'
glepnir05460682025-05-26 18:23:27 +0200491 || c == Ctrl_Z || c == Ctrl_R);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100492 case CTRL_X_SCROLL:
493 return (c == Ctrl_Y || c == Ctrl_E);
494 case CTRL_X_WHOLE_LINE:
495 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
496 case CTRL_X_FILES:
497 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
498 case CTRL_X_DICTIONARY:
499 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
500 case CTRL_X_THESAURUS:
501 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
502 case CTRL_X_TAGS:
503 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
504#ifdef FEAT_FIND_ID
505 case CTRL_X_PATH_PATTERNS:
506 return (c == Ctrl_P || c == Ctrl_N);
507 case CTRL_X_PATH_DEFINES:
508 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
509#endif
510 case CTRL_X_CMDLINE:
511 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
512 || c == Ctrl_X);
513#ifdef FEAT_COMPL_FUNC
514 case CTRL_X_FUNCTION:
515 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
516 case CTRL_X_OMNI:
517 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
518#endif
519 case CTRL_X_SPELL:
520 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
521 case CTRL_X_EVAL:
522 return (c == Ctrl_P || c == Ctrl_N);
glepnir05460682025-05-26 18:23:27 +0200523 case CTRL_X_REGISTER:
524 return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100525 }
526 internal_error("vim_is_ctrl_x_key()");
527 return FALSE;
528}
529
530/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000531 * Return TRUE if "match" is the original text when the completion began.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000532 */
533 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000534match_at_original_text(compl_T *match)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000535{
536 return match->cp_flags & CP_ORIGINAL_TEXT;
537}
538
539/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000540 * Returns TRUE if "match" is the first match in the completion list.
541 */
542 static int
543is_first_match(compl_T *match)
544{
545 return match == compl_first_match;
546}
547
548/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100549 * Return TRUE when character "c" is part of the item currently being
550 * completed. Used to decide whether to abandon complete mode when the menu
551 * is visible.
552 */
553 int
554ins_compl_accept_char(int c)
555{
556 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
557 // When expanding an identifier only accept identifier chars.
558 return vim_isIDc(c);
559
560 switch (ctrl_x_mode)
561 {
562 case CTRL_X_FILES:
563 // When expanding file name only accept file name chars. But not
564 // path separators, so that "proto/<Tab>" expands files in
565 // "proto", not "proto/" as a whole
566 return vim_isfilec(c) && !vim_ispathsep(c);
567
568 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200569 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100570 case CTRL_X_OMNI:
571 // Command line and Omni completion can work with just about any
572 // printable character, but do stop at white space.
573 return vim_isprintc(c) && !VIM_ISWHITE(c);
574
575 case CTRL_X_WHOLE_LINE:
576 // For while line completion a space can be part of the line.
577 return vim_isprintc(c);
578 }
579 return vim_iswordc(c);
580}
581
582/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000583 * Get the completed text by inferring the case of the originally typed text.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100584 * If the result is in allocated memory "tofree" is set to it.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000585 */
586 static char_u *
587ins_compl_infercase_gettext(
glepnir19e1dd62025-05-08 22:50:38 +0200588 char_u *str,
589 int char_len,
590 int compl_char_len,
591 int min_len,
592 char_u **tofree)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000593{
594 int *wca; // Wide character array.
595 char_u *p;
596 int i, c;
597 int has_lower = FALSE;
598 int was_letter = FALSE;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100599 garray_T gap;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000600
601 IObuff[0] = NUL;
602
603 // Allocate wide character array for the completion and fill it.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100604 wca = ALLOC_MULT(int, char_len);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000605 if (wca == NULL)
606 return IObuff;
607
608 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100609 for (i = 0; i < char_len; ++i)
glepnir6e199932024-12-14 21:13:27 +0100610 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000611 if (has_mbyte)
612 wca[i] = mb_ptr2char_adv(&p);
613 else
614 wca[i] = *(p++);
glepnir6e199932024-12-14 21:13:27 +0100615 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000616
617 // Rule 1: Were any chars converted to lower?
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 (MB_ISLOWER(c))
623 {
624 has_lower = TRUE;
625 if (MB_ISUPPER(wca[i]))
626 {
627 // Rule 1 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100628 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000629 wca[i] = MB_TOLOWER(wca[i]);
630 break;
631 }
632 }
633 }
634
635 // Rule 2: No lower case, 2nd consecutive letter converted to
636 // upper case.
637 if (!has_lower)
638 {
John Marriott5e6ea922024-11-23 14:01:57 +0100639 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000640 for (i = 0; i < min_len; ++i)
641 {
glepnir6e199932024-12-14 21:13:27 +0100642 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000643 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
644 {
645 // Rule 2 is satisfied.
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100646 for (i = compl_char_len; i < char_len; ++i)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000647 wca[i] = MB_TOUPPER(wca[i]);
648 break;
649 }
650 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
651 }
652 }
653
654 // Copy the original case of the part we typed.
John Marriott5e6ea922024-11-23 14:01:57 +0100655 p = compl_orig_text.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000656 for (i = 0; i < min_len; ++i)
657 {
glepnir6e199932024-12-14 21:13:27 +0100658 c = has_mbyte ? mb_ptr2char_adv(&p) : *(p++);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000659 if (MB_ISLOWER(c))
660 wca[i] = MB_TOLOWER(wca[i]);
661 else if (MB_ISUPPER(c))
662 wca[i] = MB_TOUPPER(wca[i]);
663 }
664
665 // Generate encoding specific output from wide character array.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000666 p = IObuff;
667 i = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100668 ga_init2(&gap, 1, 500);
669 while (i < char_len)
670 {
671 if (gap.ga_data != NULL)
672 {
673 if (ga_grow(&gap, 10) == FAIL)
674 {
675 ga_clear(&gap);
676 return (char_u *)"[failed]";
677 }
678 p = (char_u *)gap.ga_data + gap.ga_len;
679 if (has_mbyte)
680 gap.ga_len += (*mb_char2bytes)(wca[i++], p);
681 else
682 {
683 *p = wca[i++];
684 ++gap.ga_len;
685 }
686 }
687 else if ((p - IObuff) + 6 >= IOSIZE)
688 {
689 // Multi-byte characters can occupy up to five bytes more than
690 // ASCII characters, and we also need one byte for NUL, so when
691 // getting to six bytes from the edge of IObuff switch to using a
692 // growarray. Add the character in the next round.
693 if (ga_grow(&gap, IOSIZE) == FAIL)
zeertzjq70e566b2024-03-21 07:11:58 +0100694 {
695 vim_free(wca);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100696 return (char_u *)"[failed]";
zeertzjq70e566b2024-03-21 07:11:58 +0100697 }
Bram Moolenaarb9e71732022-07-23 06:53:08 +0100698 *p = NUL;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100699 STRCPY(gap.ga_data, IObuff);
John Marriott5e6ea922024-11-23 14:01:57 +0100700 gap.ga_len = (int)(p - IObuff);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100701 }
702 else if (has_mbyte)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000703 p += (*mb_char2bytes)(wca[i++], p);
704 else
705 *(p++) = wca[i++];
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100706 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000707 vim_free(wca);
708
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100709 if (gap.ga_data != NULL)
710 {
711 *tofree = gap.ga_data;
712 return gap.ga_data;
713 }
714
715 *p = NUL;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +0000716 return IObuff;
717}
718
719/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100720 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
721 * case of the originally typed text is used, and the case of the completed
722 * text is inferred, ie this tries to work out what case you probably wanted
723 * the rest of the word to be in -- webb
724 */
725 int
726ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200727 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100728 int len,
729 int icase,
730 char_u *fname,
731 int dir,
glepnirf31cfa22025-03-06 21:59:13 +0100732 int cont_s_ipos, // next ^X<> will set initial_pos
733 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100734{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200735 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100736 char_u *p;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100737 int char_len; // count multi-byte characters
738 int compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100739 int min_len;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200740 int flags = 0;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100741 int res;
742 char_u *tofree = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100743
744 if (p_ic && curbuf->b_p_inf && len > 0)
745 {
746 // Infer case of completed part.
747
748 // Find actual length of completion.
749 if (has_mbyte)
750 {
751 p = str;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100752 char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100753 while (*p != NUL)
754 {
755 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100756 ++char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100757 }
758 }
759 else
glepnir6e199932024-12-14 21:13:27 +0100760 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100761 char_len = len;
glepnir6e199932024-12-14 21:13:27 +0100762 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100763
764 // Find actual length of original text.
765 if (has_mbyte)
766 {
John Marriott5e6ea922024-11-23 14:01:57 +0100767 p = compl_orig_text.string;
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100768 compl_char_len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100769 while (*p != NUL)
770 {
771 MB_PTR_ADV(p);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100772 ++compl_char_len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100773 }
774 }
775 else
glepnir6e199932024-12-14 21:13:27 +0100776 {
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100777 compl_char_len = compl_length;
glepnir6e199932024-12-14 21:13:27 +0100778 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100779
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100780 // "char_len" may be smaller than "compl_char_len" when using
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100781 // thesaurus, only use the minimum when comparing.
glepnir6e199932024-12-14 21:13:27 +0100782 min_len = MIN(char_len, compl_char_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100783
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100784 str = ins_compl_infercase_gettext(str, char_len,
785 compl_char_len, min_len, &tofree);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100786 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200787 if (cont_s_ipos)
788 flags |= CP_CONT_S_IPOS;
789 if (icase)
790 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200791
glepnirf31cfa22025-03-06 21:59:13 +0100792 res = ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE, NULL, score);
Bram Moolenaarcaea6642022-07-07 19:42:04 +0100793 vim_free(tofree);
794 return res;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100795}
796
797/*
glepnirf31cfa22025-03-06 21:59:13 +0100798 * Check if ctrl_x_mode has been configured in 'completefuzzycollect'
799 */
800 static int
801cfc_has_mode(void)
802{
glepnir58760162025-03-13 21:39:51 +0100803 if (ctrl_x_mode_normal() || ctrl_x_mode_dictionary())
804 return (cfc_flags & CFC_KEYWORD) != 0;
805 else if (ctrl_x_mode_files())
806 return (cfc_flags & CFC_FILES) != 0;
807 else if (ctrl_x_mode_whole_line())
808 return (cfc_flags & CFC_WHOLELINE) != 0;
809 else
810 return FALSE;
glepnirf31cfa22025-03-06 21:59:13 +0100811}
812
813/*
Girish Palyab1565882025-04-15 20:16:00 +0200814 * Returns TRUE if matches should be sorted based on proximity to the cursor.
815 */
816 static int
817is_nearest_active(void)
818{
glepnirc3fbaa02025-05-08 23:05:10 +0200819 return (get_cot_flags() & (COT_NEAREST | COT_FUZZY)) == COT_NEAREST;
Girish Palyab1565882025-04-15 20:16:00 +0200820}
821
822/*
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000823 * Add a match to the list of matches. The arguments are:
824 * str - text of the match to add
825 * len - length of "str". If -1, then the length of "str" is
826 * computed.
827 * fname - file name to associate with this match.
828 * cptext - list of strings to use with this match (for abbr, menu, info
829 * and kind)
830 * user_data - user supplied data (any vim type) for this match
831 * cdir - match direction. If 0, use "compl_direction".
832 * flags_arg - match flags (cp_flags)
833 * adup - accept this match even if it is already present.
glepnir80b66202024-11-27 21:53:53 +0100834 * *user_hl - list of extra highlight attributes for abbr kind.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000835 * If "cdir" is FORWARD, then the match is added after the current match.
836 * Otherwise, it is added before the current match.
837 *
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100838 * If the given string is already in the list of completions, then return
839 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
840 * maybe because alloc() returns NULL, then FAIL is returned.
841 */
842 static int
843ins_compl_add(
844 char_u *str,
845 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100846 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100847 char_u **cptext, // extra text for popup menu or NULL
848 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100849 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200850 int flags_arg,
glepnir508e7852024-07-25 21:39:08 +0200851 int adup, // accept duplicate match
glepnirf31cfa22025-03-06 21:59:13 +0100852 int *user_hl, // user abbr/kind hlattr
853 int score)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100854{
glepnirf31cfa22025-03-06 21:59:13 +0100855 compl_T *match, *current, *prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100856 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200857 int flags = flags_arg;
glepnirf31cfa22025-03-06 21:59:13 +0100858 int inserted = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100859
Bram Moolenaarceb06192021-04-04 15:05:22 +0200860 if (flags & CP_FAST)
861 fast_breakcheck();
862 else
863 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100864 if (got_int)
865 return FAIL;
866 if (len < 0)
867 len = (int)STRLEN(str);
868
869 // If the same match is already present, don't add it.
870 if (compl_first_match != NULL && !adup)
871 {
872 match = compl_first_match;
873 do
874 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000875 if (!match_at_original_text(match)
John Marriott5e6ea922024-11-23 14:01:57 +0100876 && STRNCMP(match->cp_str.string, str, len) == 0
877 && ((int)match->cp_str.length <= len
878 || match->cp_str.string[len] == NUL))
Girish Palyab1565882025-04-15 20:16:00 +0200879 {
880 if (is_nearest_active() && score > 0 && score < match->cp_score)
Girish Palyab1565882025-04-15 20:16:00 +0200881 match->cp_score = score;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100882 return NOTDONE;
Girish Palyab1565882025-04-15 20:16:00 +0200883 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100884 match = match->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +0000885 } while (match != NULL && !is_first_match(match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100886 }
887
888 // Remove any popup menu before changing the list of matches.
889 ins_compl_del_pum();
890
891 // Allocate a new match structure.
892 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200893 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100894 if (match == NULL)
895 return FAIL;
glepnir40891ba2025-02-10 22:18:00 +0100896 match->cp_number = flags & CP_ORIGINAL_TEXT ? 0 : -1;
John Marriott5e6ea922024-11-23 14:01:57 +0100897 if ((match->cp_str.string = vim_strnsave(str, len)) == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100898 {
899 vim_free(match);
900 return FAIL;
901 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100902
John Marriott5e6ea922024-11-23 14:01:57 +0100903 match->cp_str.length = len;
904
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100905 // match-fname is:
906 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200907 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100908 // - NULL otherwise. --Acevedo
909 if (fname != NULL
910 && compl_curr_match != NULL
911 && compl_curr_match->cp_fname != NULL
912 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
913 match->cp_fname = compl_curr_match->cp_fname;
914 else if (fname != NULL)
915 {
916 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200917 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100918 }
919 else
920 match->cp_fname = NULL;
921 match->cp_flags = flags;
glepnir80b66202024-11-27 21:53:53 +0100922 match->cp_user_abbr_hlattr = user_hl ? user_hl[0] : -1;
923 match->cp_user_kind_hlattr = user_hl ? user_hl[1] : -1;
glepnirf31cfa22025-03-06 21:59:13 +0100924 match->cp_score = score;
Girish Palya0ac1eb32025-04-16 20:18:33 +0200925 match->cp_cpt_source_idx = cpt_sources_index;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100926
927 if (cptext != NULL)
928 {
glepnir19e1dd62025-05-08 22:50:38 +0200929 for (int i = 0; i < CPT_COUNT; ++i)
glepnir6e199932024-12-14 21:13:27 +0100930 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100931 if (cptext[i] != NULL && *cptext[i] != NUL)
932 match->cp_text[i] = vim_strsave(cptext[i]);
glepnir6e199932024-12-14 21:13:27 +0100933 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100934 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100935#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100936 if (user_data != NULL)
937 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100938#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100939
Yegappan Lakshmanan37079142022-01-08 10:38:48 +0000940 // Link the new match structure after (FORWARD) or before (BACKWARD) the
941 // current match in the list of matches .
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100942 if (compl_first_match == NULL)
943 match->cp_next = match->cp_prev = NULL;
glepnirf31cfa22025-03-06 21:59:13 +0100944 else if (cfc_has_mode() && score > 0 && compl_get_longest)
945 {
946 current = compl_first_match->cp_next;
947 prev = compl_first_match;
948 inserted = FALSE;
949 // The direction is ignored when using longest and
950 // completefuzzycollect, because matches are inserted
951 // and sorted by score.
952 while (current != NULL && current != compl_first_match)
953 {
954 if (current->cp_score < score)
955 {
Hirohito Higashi355db992025-04-28 18:07:02 +0200956 match->cp_next = current;
957 match->cp_prev = current->cp_prev;
958 if (current->cp_prev)
glepnirf31cfa22025-03-06 21:59:13 +0100959 current->cp_prev->cp_next = match;
Hirohito Higashi355db992025-04-28 18:07:02 +0200960 current->cp_prev = match;
961 inserted = TRUE;
962 break;
glepnirf31cfa22025-03-06 21:59:13 +0100963 }
964 prev = current;
965 current = current->cp_next;
966 }
967 if (!inserted)
968 {
969 prev->cp_next = match;
970 match->cp_prev = prev;
971 match->cp_next = compl_first_match;
972 compl_first_match->cp_prev = match;
973 }
974 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100975 else if (dir == FORWARD)
976 {
977 match->cp_next = compl_curr_match->cp_next;
978 match->cp_prev = compl_curr_match;
979 }
980 else // BACKWARD
981 {
982 match->cp_next = compl_curr_match;
983 match->cp_prev = compl_curr_match->cp_prev;
984 }
985 if (match->cp_next)
986 match->cp_next->cp_prev = match;
987 if (match->cp_prev)
988 match->cp_prev->cp_next = match;
989 else // if there's nothing before, it is the first match
990 compl_first_match = match;
991 compl_curr_match = match;
992
993 // Find the longest common string if still doing that.
glepnirf31cfa22025-03-06 21:59:13 +0100994 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0 && !cfc_has_mode())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100995 ins_compl_longest_match(match);
996
997 return OK;
998}
999
1000/*
1001 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001002 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001003 */
1004 static int
1005ins_compl_equal(compl_T *match, char_u *str, int len)
1006{
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001007 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +02001008 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001009 if (match->cp_flags & CP_ICASE)
John Marriott5e6ea922024-11-23 14:01:57 +01001010 return STRNICMP(match->cp_str.string, str, (size_t)len) == 0;
1011 return STRNCMP(match->cp_str.string, str, (size_t)len) == 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001012}
1013
1014/*
glepnir6a38aff2024-12-16 21:56:16 +01001015 * when len is -1 mean use whole length of p otherwise part of p
1016 */
1017 static void
1018ins_compl_insert_bytes(char_u *p, int len)
1019{
1020 if (len == -1)
1021 len = (int)STRLEN(p);
1022 ins_bytes_len(p, len);
zeertzjqf25d8f92024-12-18 21:12:25 +01001023 compl_ins_end_col = curwin->w_cursor.col;
glepnir6a38aff2024-12-16 21:56:16 +01001024}
1025
1026/*
zeertzjqd32bf0a2024-12-17 20:55:13 +01001027 * Checks if the column is within the currently inserted completion text
1028 * column range. If it is, it returns a special highlight attribute.
glepnir76bdb822025-02-08 19:04:51 +01001029 * -1 means normal item.
glepnir6a38aff2024-12-16 21:56:16 +01001030 */
1031 int
glepnir76bdb822025-02-08 19:04:51 +01001032ins_compl_col_range_attr(linenr_T lnum, int col)
glepnir6a38aff2024-12-16 21:56:16 +01001033{
glepnir76bdb822025-02-08 19:04:51 +01001034 int start_col;
1035 int attr;
1036
1037 if ((get_cot_flags() & COT_FUZZY)
1038 || (attr = syn_name2attr((char_u *)"ComplMatchIns")) == 0)
glepnire8908872025-01-08 18:30:45 +01001039 return -1;
1040
glepnir76bdb822025-02-08 19:04:51 +01001041 start_col = compl_col + (int)ins_compl_leader_len();
1042 if (!ins_compl_has_multiple())
1043 return (col >= start_col && col < compl_ins_end_col) ? attr : -1;
1044
1045 // Multiple lines
1046 if ((lnum == compl_lnum && col >= start_col && col < MAXCOL) ||
1047 (lnum > compl_lnum && lnum < curwin->w_cursor.lnum) ||
1048 (lnum == curwin->w_cursor.lnum && col <= compl_ins_end_col))
1049 return attr;
glepnir6a38aff2024-12-16 21:56:16 +01001050
1051 return -1;
1052}
1053
1054/*
glepnir76bdb822025-02-08 19:04:51 +01001055 * Returns TRUE if the current completion string contains newline characters,
1056 * indicating it's a multi-line completion.
1057 */
1058 static int
1059ins_compl_has_multiple(void)
1060{
1061 return vim_strchr(compl_shown_match->cp_str.string, '\n') != NULL;
1062}
1063
1064/*
1065 * Returns TRUE if the given line number falls within the range of a multi-line
1066 * completion, i.e. between the starting line (compl_lnum) and current cursor
1067 * line. Always returns FALSE for single-line completions.
1068 */
1069 int
1070ins_compl_lnum_in_range(linenr_T lnum)
1071{
1072 if (!ins_compl_has_multiple())
1073 return FALSE;
1074 return lnum >= compl_lnum && lnum <= curwin->w_cursor.lnum;
1075}
1076
1077/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001078 * Reduce the longest common string for match "match".
1079 */
1080 static void
1081ins_compl_longest_match(compl_T *match)
1082{
1083 char_u *p, *s;
1084 int c1, c2;
1085 int had_match;
1086
John Marriott5e6ea922024-11-23 14:01:57 +01001087 if (compl_leader.string == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001088 {
1089 // First match, use it as a whole.
John Marriott5e6ea922024-11-23 14:01:57 +01001090 compl_leader.string = vim_strnsave(match->cp_str.string, match->cp_str.length);
1091 if (compl_leader.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001092 return;
1093
John Marriott5e6ea922024-11-23 14:01:57 +01001094 compl_leader.length = match->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001095 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001096 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001097
1098 // When the match isn't there (to avoid matching itself) remove it
1099 // again after redrawing.
1100 if (!had_match)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001101 ins_compl_delete();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001102 compl_used_match = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001103
1104 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001105 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001106
1107 // Reduce the text if this match differs from compl_leader.
John Marriott5e6ea922024-11-23 14:01:57 +01001108 p = compl_leader.string;
1109 s = match->cp_str.string;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001110 while (*p != NUL)
1111 {
1112 if (has_mbyte)
1113 {
1114 c1 = mb_ptr2char(p);
1115 c2 = mb_ptr2char(s);
1116 }
1117 else
1118 {
1119 c1 = *p;
1120 c2 = *s;
1121 }
1122 if ((match->cp_flags & CP_ICASE)
1123 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
1124 break;
1125 if (has_mbyte)
1126 {
1127 MB_PTR_ADV(p);
1128 MB_PTR_ADV(s);
1129 }
1130 else
1131 {
1132 ++p;
1133 ++s;
1134 }
1135 }
1136
1137 if (*p != NUL)
1138 {
1139 // Leader was shortened, need to change the inserted text.
1140 *p = NUL;
John Marriott5e6ea922024-11-23 14:01:57 +01001141 compl_leader.length = (size_t)(p - compl_leader.string);
1142
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001143 had_match = (curwin->w_cursor.col > compl_col);
glepnirf31cfa22025-03-06 21:59:13 +01001144 ins_compl_longest_insert(compl_leader.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001145
1146 // When the match isn't there (to avoid matching itself) remove it
1147 // again after redrawing.
1148 if (!had_match)
1149 ins_compl_delete();
1150 }
1151
1152 compl_used_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001153}
1154
1155/*
1156 * Add an array of matches to the list of matches.
1157 * Frees matches[].
1158 */
1159 static void
1160ins_compl_add_matches(
1161 int num_matches,
1162 char_u **matches,
1163 int icase)
1164{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001165 int add_r = OK;
1166 int dir = compl_direction;
1167
glepnir19e1dd62025-05-08 22:50:38 +02001168 for (int i = 0; i < num_matches && add_r != FAIL; i++)
glepnir6e199932024-12-14 21:13:27 +01001169 {
1170 add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
glepnirf31cfa22025-03-06 21:59:13 +01001171 CP_FAST | (icase ? CP_ICASE : 0), FALSE, NULL, 0);
glepnir6e199932024-12-14 21:13:27 +01001172 if (add_r == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001173 // if dir was BACKWARD then honor it just once
1174 dir = FORWARD;
glepnir6e199932024-12-14 21:13:27 +01001175 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001176 FreeWild(num_matches, matches);
1177}
1178
1179/*
1180 * Make the completion list cyclic.
1181 * Return the number of matches (excluding the original).
1182 */
1183 static int
1184ins_compl_make_cyclic(void)
1185{
1186 compl_T *match;
1187 int count = 0;
1188
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001189 if (compl_first_match == NULL)
1190 return 0;
1191
1192 // Find the end of the list.
1193 match = compl_first_match;
1194 // there's always an entry for the compl_orig_text, it doesn't count.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001195 while (match->cp_next != NULL && !is_first_match(match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001196 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001197 match = match->cp_next;
1198 ++count;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001199 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001200 match->cp_next = compl_first_match;
1201 compl_first_match->cp_prev = match;
1202
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001203 return count;
1204}
1205
1206/*
1207 * Return whether there currently is a shown match.
1208 */
1209 int
1210ins_compl_has_shown_match(void)
1211{
1212 return compl_shown_match == NULL
1213 || compl_shown_match != compl_shown_match->cp_next;
1214}
1215
1216/*
1217 * Return whether the shown match is long enough.
1218 */
1219 int
1220ins_compl_long_shown_match(void)
1221{
John Marriott5e6ea922024-11-23 14:01:57 +01001222 return (int)compl_shown_match->cp_str.length
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001223 > curwin->w_cursor.col - compl_col;
1224}
1225
1226/*
zeertzjq529b9ad2024-06-05 20:27:06 +02001227 * Get the local or global value of 'completeopt' flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001228 */
zeertzjq529b9ad2024-06-05 20:27:06 +02001229 unsigned int
1230get_cot_flags(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001231{
zeertzjq529b9ad2024-06-05 20:27:06 +02001232 return curbuf->b_cot_flags != 0 ? curbuf->b_cot_flags : cot_flags;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001233}
1234
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001235/*
1236 * Update the screen and when there is any scrolling remove the popup menu.
1237 */
1238 static void
1239ins_compl_upd_pum(void)
1240{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001241 if (compl_match_array == NULL)
1242 return;
1243
glepnir19e1dd62025-05-08 22:50:38 +02001244 int h = curwin->w_cline_height;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001245 // Update the screen later, before drawing the popup menu over it.
1246 pum_call_update_screen();
1247 if (h != curwin->w_cline_height)
1248 ins_compl_del_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001249}
1250
1251/*
1252 * Remove any popup menu.
1253 */
1254 static void
1255ins_compl_del_pum(void)
1256{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001257 if (compl_match_array == NULL)
1258 return;
1259
1260 pum_undisplay();
1261 VIM_CLEAR(compl_match_array);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001262}
1263
1264/*
1265 * Return TRUE if the popup menu should be displayed.
1266 */
1267 int
1268pum_wanted(void)
1269{
1270 // 'completeopt' must contain "menu" or "menuone"
zeertzjq529b9ad2024-06-05 20:27:06 +02001271 if ((get_cot_flags() & COT_ANY_MENU) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001272 return FALSE;
1273
1274 // The display looks bad on a B&W display.
1275 if (t_colors < 8
1276#ifdef FEAT_GUI
1277 && !gui.in_use
1278#endif
1279 )
1280 return FALSE;
1281 return TRUE;
1282}
1283
1284/*
1285 * Return TRUE if there are two or more matches to be shown in the popup menu.
1286 * One if 'completopt' contains "menuone".
1287 */
1288 static int
1289pum_enough_matches(void)
1290{
1291 compl_T *compl;
glepnir6e199932024-12-14 21:13:27 +01001292 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001293
1294 // Don't display the popup menu if there are no matches or there is only
1295 // one (ignoring the original text).
1296 compl = compl_first_match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001297 do
1298 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001299 if (compl == NULL || (!match_at_original_text(compl) && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001300 break;
1301 compl = compl->cp_next;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001302 } while (!is_first_match(compl));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001303
zeertzjq529b9ad2024-06-05 20:27:06 +02001304 if (get_cot_flags() & COT_MENUONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001305 return (i >= 1);
1306 return (i >= 2);
1307}
1308
Bram Moolenaar3075a452021-11-17 15:51:52 +00001309#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001310/*
1311 * Allocate Dict for the completed item.
1312 * { word, abbr, menu, kind, info }
1313 */
1314 static dict_T *
1315ins_compl_dict_alloc(compl_T *match)
1316{
1317 dict_T *dict = dict_alloc_lock(VAR_FIXED);
1318
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001319 if (dict == NULL)
1320 return NULL;
1321
John Marriott5e6ea922024-11-23 14:01:57 +01001322 dict_add_string(dict, "word", match->cp_str.string);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001323 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
1324 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
1325 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
1326 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
1327 if (match->cp_user_data.v_type == VAR_UNKNOWN)
1328 dict_add_string(dict, "user_data", (char_u *)"");
1329 else
1330 dict_add_tv(dict, "user_data", &match->cp_user_data);
1331
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001332 return dict;
1333}
1334
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001335/*
1336 * Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode
1337 * completion menu is changed.
1338 */
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001339 static void
1340trigger_complete_changed_event(int cur)
1341{
1342 dict_T *v_event;
1343 dict_T *item;
1344 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001345 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001346
1347 if (recursive)
1348 return;
1349
glepnir40891ba2025-02-10 22:18:00 +01001350 item = cur < 0 ? dict_alloc() : ins_compl_dict_alloc(compl_curr_match);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001351 if (item == NULL)
1352 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001353 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001354 dict_add_dict(v_event, "completed_item", item);
1355 pum_set_event_info(v_event);
1356 dict_set_items_ro(v_event);
1357
1358 recursive = TRUE;
zeertzjqcfe45652022-05-27 17:26:55 +01001359 textlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001360 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
zeertzjqcfe45652022-05-27 17:26:55 +01001361 textlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001362 recursive = FALSE;
1363
Bram Moolenaar3075a452021-11-17 15:51:52 +00001364 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001365}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001366#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001367
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001368/*
Girish Palya8cd42a52025-06-05 21:04:29 +02001369 * Helper functions for mergesort_list().
Girish Palya19ef6b02025-05-28 20:28:21 +02001370 */
Girish Palya8cd42a52025-06-05 21:04:29 +02001371 static void*
1372cp_get_next(void *node)
Girish Palya19ef6b02025-05-28 20:28:21 +02001373{
Girish Palya8cd42a52025-06-05 21:04:29 +02001374 return ((compl_T*)node)->cp_next;
Girish Palya19ef6b02025-05-28 20:28:21 +02001375}
1376
Girish Palya8cd42a52025-06-05 21:04:29 +02001377 static void
1378cp_set_next(void *node, void *next)
glepnira218cc62024-06-03 19:32:39 +02001379{
Girish Palya8cd42a52025-06-05 21:04:29 +02001380 ((compl_T*)node)->cp_next = (compl_T*)next;
1381}
1382
1383 static void*
1384cp_get_prev(void* node)
1385{
1386 return ((compl_T*)node)->cp_prev;
1387}
1388
1389 static void
1390cp_set_prev(void* node, void* prev)
1391{
1392 ((compl_T*)node)->cp_prev = (compl_T*)prev;
1393}
1394
1395 static int
1396cp_compare_fuzzy(const void* a, const void* b)
1397{
1398 int score_a = ((compl_T*)a)->cp_score;
1399 int score_b = ((compl_T*)b)->cp_score;
1400 return (score_b > score_a) ? 1 : (score_b < score_a) ? -1 : 0;
glepnira218cc62024-06-03 19:32:39 +02001401}
1402
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001403 static int
1404cp_compare_nearest(const void* a, const void* b)
1405{
1406 int score_a = ((compl_T*)a)->cp_score;
1407 int score_b = ((compl_T*)b)->cp_score;
Girish Palyacd68f212025-06-22 20:23:54 +02001408 if (score_a == 0 || score_b == 0)
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001409 return 0;
1410 return (score_a > score_b) ? 1 : (score_a < score_b) ? -1 : 0;
1411}
1412
1413/*
Girish Palyaba11e782025-07-05 16:11:44 +02001414 * Constructs a new string by prepending text from the current line (from
1415 * startcol to compl_col) to the given source string. Stores the result in
1416 * dest. Returns OK or FAIL.
1417 */
1418 static int
1419prepend_startcol_text(string_T *dest, string_T *src, int startcol)
1420{
1421 int prepend_len = compl_col - startcol;
1422 int new_length = prepend_len + (int)src->length;
1423
1424 dest->length = (size_t)new_length;
1425 dest->string = alloc(new_length + 1); // +1 for NUL
1426 if (dest->string == NULL)
1427 {
1428 dest->length = 0;
1429 return FAIL;
1430 }
1431
1432 char_u *line = ml_get(curwin->w_cursor.lnum);
1433
1434 mch_memmove(dest->string, line + startcol, prepend_len);
1435 mch_memmove(dest->string + prepend_len, src->string, src->length);
1436 dest->string[new_length] = NUL;
1437 return OK;
1438}
1439
1440/*
1441 * Returns the completion leader string adjusted for a specific source's
1442 * startcol. If the source's startcol is before compl_col, prepends text from
1443 * the buffer line to the original compl_leader.
1444 */
1445 static string_T *
1446get_leader_for_startcol(compl_T *match, int cached)
1447{
1448 static string_T adjusted_leader = {NULL, 0};
1449
1450 if (match == NULL)
1451 {
1452 VIM_CLEAR_STRING(adjusted_leader);
1453 return NULL;
1454 }
1455
1456 if (cpt_sources_array == NULL || compl_leader.string == NULL)
1457 goto theend;
1458
1459 int cpt_idx = match->cp_cpt_source_idx;
1460 if (cpt_idx < 0 || compl_col <= 0)
1461 goto theend;
1462 int startcol = cpt_sources_array[cpt_idx].cs_startcol;
1463
1464 if (startcol >= 0 && startcol < compl_col)
1465 {
1466 int prepend_len = compl_col - startcol;
1467 int new_length = prepend_len + (int)compl_leader.length;
1468 if (cached && (size_t)new_length == adjusted_leader.length
1469 && adjusted_leader.string != NULL)
1470 return &adjusted_leader;
1471
1472 VIM_CLEAR_STRING(adjusted_leader);
1473 if (prepend_startcol_text(&adjusted_leader, &compl_leader,
1474 startcol) != OK)
1475 goto theend;
1476
1477 return &adjusted_leader;
1478 }
1479theend:
1480 return &compl_leader;
1481}
1482
1483/*
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001484 * Set fuzzy score.
1485 */
1486 static void
1487set_fuzzy_score(void)
1488{
zeertzjq91782b42025-06-10 20:06:53 +02001489 compl_T *compl;
zeertzjqde1c7ac2025-06-09 20:34:57 +02001490
zeertzjq91782b42025-06-10 20:06:53 +02001491 if (!compl_first_match
1492 || compl_leader.string == NULL || compl_leader.length == 0)
1493 return;
1494
Girish Palyaba11e782025-07-05 16:11:44 +02001495 (void)get_leader_for_startcol(NULL, TRUE); // Clear the cache
1496
zeertzjq91782b42025-06-10 20:06:53 +02001497 compl = compl_first_match;
1498 do
1499 {
1500 compl->cp_score = fuzzy_match_str(compl->cp_str.string,
Girish Palyaba11e782025-07-05 16:11:44 +02001501 get_leader_for_startcol(compl, TRUE)->string);
zeertzjq91782b42025-06-10 20:06:53 +02001502 compl = compl->cp_next;
1503 } while (compl != NULL && !is_first_match(compl));
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001504}
1505
1506/*
1507 * Sort completion matches, excluding the node that contains the leader.
1508 */
1509 static void
1510sort_compl_match_list(int (*compare)(const void *, const void *))
1511{
zeertzjq91782b42025-06-10 20:06:53 +02001512 compl_T *compl;
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001513
1514 if (!compl_first_match || is_first_match(compl_first_match->cp_next))
1515 return;
1516
zeertzjq91782b42025-06-10 20:06:53 +02001517 compl = compl_first_match->cp_prev;
Girish Palyab8ee1cf2025-06-08 16:20:06 +02001518 ins_compl_make_linear();
1519 if (compl_shows_dir_forward())
1520 {
1521 compl_first_match->cp_next->cp_prev = NULL;
1522 compl_first_match->cp_next = mergesort_list(compl_first_match->cp_next,
1523 cp_get_next, cp_set_next, cp_get_prev, cp_set_prev, compare);
1524 compl_first_match->cp_next->cp_prev = compl_first_match;
1525 }
1526 else
1527 {
1528 compl->cp_prev->cp_next = NULL;
1529 compl_first_match = mergesort_list(compl_first_match, cp_get_next,
1530 cp_set_next, cp_get_prev, cp_set_prev, compare);
1531 compl_T *tail = compl_first_match;
1532 while (tail->cp_next != NULL)
1533 tail = tail->cp_next;
1534 tail->cp_next = compl;
1535 compl->cp_prev = tail;
1536 }
1537 (void)ins_compl_make_cyclic();
1538}
1539
glepnira218cc62024-06-03 19:32:39 +02001540/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001541 * Build a popup menu to show the completion matches.
1542 * Returns the popup menu entry that should be selected. Returns -1 if nothing
1543 * should be selected.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001544 */
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001545 static int
1546ins_compl_build_pum(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001547{
1548 compl_T *compl;
1549 compl_T *shown_compl = NULL;
1550 int did_find_shown_match = FALSE;
1551 int shown_match_ok = FALSE;
glepnira49c0772024-11-30 10:56:30 +01001552 int i = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001553 int cur = -1;
zeertzjqaa925ee2024-06-09 18:24:05 +02001554 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02001555 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
zeertzjqd65aa1b2025-01-25 15:29:03 +01001556 int fuzzy_filter = (cur_cot_flags & COT_FUZZY) != 0;
glepnir80b66202024-11-27 21:53:53 +01001557 compl_T *match_head = NULL;
1558 compl_T *match_tail = NULL;
1559 compl_T *match_next = NULL;
Girish Palya8cd42a52025-06-05 21:04:29 +02001560 int *match_count = NULL;
Girish Palya19ef6b02025-05-28 20:28:21 +02001561 int is_forward = compl_shows_dir_forward();
Girish Palya8cd42a52025-06-05 21:04:29 +02001562 int is_cpt_completion = (cpt_sources_array != NULL);
Girish Palyaba11e782025-07-05 16:11:44 +02001563 string_T *leader;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001564
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001565 // Need to build the popup menu list.
1566 compl_match_arraysize = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001567
glepnira49c0772024-11-30 10:56:30 +01001568 // If the current match is the original text don't find the first
1569 // match after it, don't highlight anything.
1570 if (match_at_original_text(compl_shown_match))
1571 shown_match_ok = TRUE;
1572
1573 if (compl_leader.string != NULL
1574 && STRCMP(compl_leader.string, compl_orig_text.string) == 0
1575 && shown_match_ok == FALSE)
1576 compl_shown_match = compl_no_select ? compl_first_match
1577 : compl_first_match->cp_next;
1578
Girish Palya8cd42a52025-06-05 21:04:29 +02001579 if (is_cpt_completion)
1580 {
1581 match_count = ALLOC_CLEAR_MULT(int, cpt_sources_count);
1582 if (match_count == NULL)
1583 return -1;
1584 }
1585
Girish Palyaba11e782025-07-05 16:11:44 +02001586 (void)get_leader_for_startcol(NULL, TRUE); // Clear the cache
1587
Girish Palya8cd42a52025-06-05 21:04:29 +02001588 compl = compl_first_match;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001589 do
1590 {
glepnird4088ed2024-12-31 10:55:22 +01001591 compl->cp_in_match_array = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02001592
Girish Palyadc314052025-05-08 23:28:52 +02001593 // Apply 'smartcase' behavior during normal mode
1594 if (ctrl_x_mode_normal() && !p_inf && compl_leader.string
1595 && !ignorecase(compl_leader.string) && !fuzzy_filter)
1596 compl->cp_flags &= ~CP_ICASE;
1597
Girish Palyaba11e782025-07-05 16:11:44 +02001598 leader = get_leader_for_startcol(compl, TRUE);
1599
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001600 if (!match_at_original_text(compl)
Girish Palyaba11e782025-07-05 16:11:44 +02001601 && (leader->string == NULL
1602 || ins_compl_equal(compl, leader->string,
1603 (int)leader->length)
glepnirf400a0c2025-01-23 19:55:14 +01001604 || (fuzzy_filter && compl->cp_score > 0)))
glepnir80b66202024-11-27 21:53:53 +01001605 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001606 // Limit number of items from each source if max_items is set.
1607 int match_limit_exceeded = FALSE;
1608 int cur_source = compl->cp_cpt_source_idx;
1609 if (is_forward && cur_source != -1 && is_cpt_completion)
glepnira49c0772024-11-30 10:56:30 +01001610 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001611 match_count[cur_source]++;
1612 int max_matches = cpt_sources_array[cur_source].cs_max_matches;
1613 if (max_matches > 0 && match_count[cur_source] > max_matches)
1614 match_limit_exceeded = TRUE;
1615 }
1616
1617 if (!match_limit_exceeded)
1618 {
1619 ++compl_match_arraysize;
1620 compl->cp_in_match_array = TRUE;
1621 if (match_head == NULL)
1622 match_head = compl;
glepnira49c0772024-11-30 10:56:30 +01001623 else
Girish Palya8cd42a52025-06-05 21:04:29 +02001624 match_tail->cp_match_next = compl;
1625 match_tail = compl;
glepnira49c0772024-11-30 10:56:30 +01001626
Girish Palya8cd42a52025-06-05 21:04:29 +02001627 if (!shown_match_ok && !fuzzy_filter)
glepnira49c0772024-11-30 10:56:30 +01001628 {
Girish Palya8cd42a52025-06-05 21:04:29 +02001629 if (compl == compl_shown_match || did_find_shown_match)
1630 {
1631 // This item is the shown match or this is the
1632 // first displayed item after the shown match.
1633 compl_shown_match = compl;
1634 did_find_shown_match = TRUE;
1635 shown_match_ok = TRUE;
1636 }
1637 else
1638 // Remember this displayed match for when the
1639 // shown match is just below it.
1640 shown_compl = compl;
glepnira49c0772024-11-30 10:56:30 +01001641 cur = i;
glepnira49c0772024-11-30 10:56:30 +01001642 }
Girish Palya8cd42a52025-06-05 21:04:29 +02001643 else if (fuzzy_filter)
1644 {
1645 if (i == 0)
1646 shown_compl = compl;
1647
1648 if (!shown_match_ok && compl == compl_shown_match)
1649 {
1650 cur = i;
1651 shown_match_ok = TRUE;
1652 }
1653 }
1654 i++;
glepnira49c0772024-11-30 10:56:30 +01001655 }
glepnir80b66202024-11-27 21:53:53 +01001656 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001657
glepnirf400a0c2025-01-23 19:55:14 +01001658 if (compl == compl_shown_match && !fuzzy_filter)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001659 {
1660 did_find_shown_match = TRUE;
1661
1662 // When the original text is the shown match don't set
1663 // compl_shown_match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00001664 if (match_at_original_text(compl))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001665 shown_match_ok = TRUE;
1666
1667 if (!shown_match_ok && shown_compl != NULL)
1668 {
1669 // The shown match isn't displayed, set it to the
1670 // previously displayed match.
1671 compl_shown_match = shown_compl;
1672 shown_match_ok = TRUE;
1673 }
1674 }
glepnira49c0772024-11-30 10:56:30 +01001675 compl = compl->cp_next;
1676 } while (compl != NULL && !is_first_match(compl));
1677
Girish Palya8cd42a52025-06-05 21:04:29 +02001678 vim_free(match_count);
1679
glepnira49c0772024-11-30 10:56:30 +01001680 if (compl_match_arraysize == 0)
1681 return -1;
1682
Girish Palya8cd42a52025-06-05 21:04:29 +02001683 if (fuzzy_filter && !compl_no_select && !shown_match_ok)
glepnirc0b7ca42025-02-13 20:27:44 +01001684 {
1685 compl_shown_match = shown_compl;
1686 shown_match_ok = TRUE;
1687 cur = 0;
1688 }
1689
glepnira49c0772024-11-30 10:56:30 +01001690 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
1691 if (compl_match_array == NULL)
1692 return -1;
1693
1694 compl = match_head;
1695 i = 0;
1696 while (compl != NULL)
1697 {
glepnir6e199932024-12-14 21:13:27 +01001698 compl_match_array[i].pum_text = compl->cp_text[CPT_ABBR] != NULL
1699 ? compl->cp_text[CPT_ABBR] : compl->cp_str.string;
glepnira49c0772024-11-30 10:56:30 +01001700 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1701 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
Girish Palya19ef6b02025-05-28 20:28:21 +02001702 compl_match_array[i].pum_cpt_source_idx = compl->cp_cpt_source_idx;
glepnira49c0772024-11-30 10:56:30 +01001703 compl_match_array[i].pum_user_abbr_hlattr = compl->cp_user_abbr_hlattr;
1704 compl_match_array[i].pum_user_kind_hlattr = compl->cp_user_kind_hlattr;
glepnir6e199932024-12-14 21:13:27 +01001705 compl_match_array[i++].pum_extra = compl->cp_text[CPT_MENU] != NULL
1706 ? compl->cp_text[CPT_MENU] : compl->cp_fname;
glepnir80b66202024-11-27 21:53:53 +01001707 match_next = compl->cp_match_next;
1708 compl->cp_match_next = NULL;
1709 compl = match_next;
1710 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001711
1712 if (!shown_match_ok) // no displayed match at all
1713 cur = -1;
1714
1715 return cur;
1716}
1717
1718/*
1719 * Show the popup menu for the list of matches.
1720 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1721 */
1722 void
1723ins_compl_show_pum(void)
1724{
1725 int i;
1726 int cur = -1;
1727 colnr_T col;
1728
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001729 if (!pum_wanted() || !pum_enough_matches())
1730 return;
1731
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001732 // Update the screen later, before drawing the popup menu over it.
1733 pum_call_update_screen();
1734
1735 if (compl_match_array == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001736 // Need to build the popup menu list.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001737 cur = ins_compl_build_pum();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001738 else
1739 {
1740 // popup menu already exists, only need to find the current item.
1741 for (i = 0; i < compl_match_arraysize; ++i)
glepnir19e1dd62025-05-08 22:50:38 +02001742 {
John Marriott5e6ea922024-11-23 14:01:57 +01001743 if (compl_match_array[i].pum_text == compl_shown_match->cp_str.string
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001744 || compl_match_array[i].pum_text
1745 == compl_shown_match->cp_text[CPT_ABBR])
1746 {
1747 cur = i;
1748 break;
1749 }
glepnir19e1dd62025-05-08 22:50:38 +02001750 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001751 }
1752
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001753 if (compl_match_array == NULL)
glepnir0d3c0a62024-02-11 17:52:40 +01001754 {
1755#ifdef FEAT_EVAL
1756 if (compl_started && has_completechanged())
1757 trigger_complete_changed_event(cur);
1758#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001759 return;
glepnir0d3c0a62024-02-11 17:52:40 +01001760 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001761
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001762 // In Replace mode when a $ is displayed at the end of the line only
1763 // part of the screen would be updated. We do need to redraw here.
1764 dollar_vcol = -1;
1765
1766 // Compute the screen column of the start of the completed text.
1767 // Use the cursor to get all wrapping and other settings right.
1768 col = curwin->w_cursor.col;
1769 curwin->w_cursor.col = compl_col;
glepnira218cc62024-06-03 19:32:39 +02001770 compl_selected_item = cur;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001771 pum_display(compl_match_array, compl_match_arraysize, cur);
1772 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001773
glepnircbb46b42024-02-03 18:11:13 +01001774 // After adding leader, set the current match to shown match.
1775 if (compl_started && compl_curr_match != compl_shown_match)
1776 compl_curr_match = compl_shown_match;
1777
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001778#ifdef FEAT_EVAL
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00001779 if (has_completechanged())
1780 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001781#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001782}
1783
1784#define DICT_FIRST (1) // use just first element in "dict"
1785#define DICT_EXACT (2) // "dict" is the exact name of a file
1786
1787/*
glepnir40c1c332024-06-11 19:37:04 +02001788 * Get current completion leader
1789 */
1790 char_u *
1791ins_compl_leader(void)
1792{
John Marriott5e6ea922024-11-23 14:01:57 +01001793 return compl_leader.string != NULL ? compl_leader.string : compl_orig_text.string;
1794}
1795
1796/*
1797 * Get current completion leader length
1798 */
1799 size_t
1800ins_compl_leader_len(void)
1801{
1802 return compl_leader.string != NULL ? compl_leader.length : compl_orig_text.length;
glepnir40c1c332024-06-11 19:37:04 +02001803}
1804
1805/*
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001806 * Add any identifiers that match the given pattern "pat" in the list of
1807 * dictionary files "dict_start" to the list of completions.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001808 */
1809 static void
1810ins_compl_dictionaries(
1811 char_u *dict_start,
1812 char_u *pat,
1813 int flags, // DICT_FIRST and/or DICT_EXACT
1814 int thesaurus) // Thesaurus completion
1815{
1816 char_u *dict = dict_start;
1817 char_u *ptr;
1818 char_u *buf;
1819 regmatch_T regmatch;
1820 char_u **files;
1821 int count;
1822 int save_p_scs;
1823 int dir = compl_direction;
1824
1825 if (*dict == NUL)
1826 {
1827#ifdef FEAT_SPELL
1828 // When 'dictionary' is empty and spell checking is enabled use
1829 // "spell".
1830 if (!thesaurus && curwin->w_p_spell)
1831 dict = (char_u *)"spell";
1832 else
1833#endif
1834 return;
1835 }
1836
1837 buf = alloc(LSIZE);
1838 if (buf == NULL)
1839 return;
1840 regmatch.regprog = NULL; // so that we can goto theend
1841
1842 // If 'infercase' is set, don't use 'smartcase' here
1843 save_p_scs = p_scs;
1844 if (curbuf->b_p_inf)
1845 p_scs = FALSE;
1846
1847 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1848 // to only match at the start of a line. Otherwise just match the
1849 // pattern. Also need to double backslashes.
1850 if (ctrl_x_mode_line_or_eval())
1851 {
1852 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001853
1854 if (pat_esc == NULL)
1855 goto theend;
glepnir19e1dd62025-05-08 22:50:38 +02001856 size_t len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001857 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001858 if (ptr == NULL)
1859 {
1860 vim_free(pat_esc);
1861 goto theend;
1862 }
1863 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1864 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1865 vim_free(pat_esc);
1866 vim_free(ptr);
1867 }
1868 else
1869 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001870 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001871 if (regmatch.regprog == NULL)
1872 goto theend;
1873 }
1874
1875 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1876 regmatch.rm_ic = ignorecase(pat);
1877 while (*dict != NUL && !got_int && !compl_interrupted)
1878 {
1879 // copy one dictionary file name into buf
1880 if (flags == DICT_EXACT)
1881 {
1882 count = 1;
1883 files = &dict;
1884 }
1885 else
1886 {
1887 // Expand wildcards in the dictionary name, but do not allow
1888 // backticks (for security, the 'dict' option may have been set in
1889 // a modeline).
1890 copy_option_part(&dict, buf, LSIZE, ",");
1891# ifdef FEAT_SPELL
1892 if (!thesaurus && STRCMP(buf, "spell") == 0)
1893 count = -1;
1894 else
1895# endif
1896 if (vim_strchr(buf, '`') != NULL
1897 || expand_wildcards(1, &buf, &count, &files,
1898 EW_FILE|EW_SILENT) != OK)
1899 count = 0;
1900 }
1901
1902# ifdef FEAT_SPELL
1903 if (count == -1)
1904 {
1905 // Complete from active spelling. Skip "\<" in the pattern, we
1906 // don't use it as a RE.
1907 if (pat[0] == '\\' && pat[1] == '<')
1908 ptr = pat + 2;
1909 else
1910 ptr = pat;
1911 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1912 }
1913 else
1914# endif
1915 if (count > 0) // avoid warning for using "files" uninit
1916 {
1917 ins_compl_files(count, files, thesaurus, flags,
glepnirf31cfa22025-03-06 21:59:13 +01001918 (cfc_has_mode() ? NULL : &regmatch), buf, &dir);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001919 if (flags != DICT_EXACT)
1920 FreeWild(count, files);
1921 }
1922 if (flags != 0)
1923 break;
1924 }
1925
1926theend:
1927 p_scs = save_p_scs;
1928 vim_regfree(regmatch.regprog);
1929 vim_free(buf);
1930}
1931
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001932/*
1933 * Add all the words in the line "*buf_arg" from the thesaurus file "fname"
1934 * skipping the word at 'skip_word'. Returns OK on success.
1935 */
1936 static int
zeertzjq5fb3aab2022-08-24 16:48:23 +01001937thesaurus_add_words_in_line(
glepnir19e1dd62025-05-08 22:50:38 +02001938 char_u *fname,
1939 char_u **buf_arg,
1940 int dir,
1941 char_u *skip_word)
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001942{
1943 int status = OK;
1944 char_u *ptr;
1945 char_u *wstart;
1946
1947 // Add the other matches on the line
1948 ptr = *buf_arg;
1949 while (!got_int)
1950 {
1951 // Find start of the next word. Skip white
1952 // space and punctuation.
1953 ptr = find_word_start(ptr);
1954 if (*ptr == NUL || *ptr == NL)
1955 break;
1956 wstart = ptr;
1957
1958 // Find end of the word.
1959 if (has_mbyte)
1960 // Japanese words may have characters in
1961 // different classes, only separate words
1962 // with single-byte non-word characters.
1963 while (*ptr != NUL)
1964 {
1965 int l = (*mb_ptr2len)(ptr);
1966
1967 if (l < 2 && !vim_iswordc(*ptr))
1968 break;
1969 ptr += l;
1970 }
1971 else
1972 ptr = find_word_end(ptr);
1973
1974 // Add the word. Skip the regexp match.
1975 if (wstart != skip_word)
1976 {
1977 status = ins_compl_add_infercase(wstart, (int)(ptr - wstart), p_ic,
glepnirf31cfa22025-03-06 21:59:13 +01001978 fname, dir, FALSE, 0);
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00001979 if (status == FAIL)
1980 break;
1981 }
1982 }
1983
1984 *buf_arg = ptr;
1985 return status;
1986}
1987
1988/*
1989 * Process "count" dictionary/thesaurus "files" and add the text matching
1990 * "regmatch".
1991 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001992 static void
1993ins_compl_files(
1994 int count,
1995 char_u **files,
1996 int thesaurus,
1997 int flags,
1998 regmatch_T *regmatch,
1999 char_u *buf,
2000 int *dir)
2001{
2002 char_u *ptr;
2003 int i;
2004 FILE *fp;
2005 int add_r;
glepnirf31cfa22025-03-06 21:59:13 +01002006 char_u *leader = NULL;
2007 int leader_len = 0;
glepnir58760162025-03-13 21:39:51 +01002008 int in_fuzzy_collect = cfc_has_mode();
glepnirf31cfa22025-03-06 21:59:13 +01002009 int score = 0;
2010 int len = 0;
2011 char_u *line_end = NULL;
2012
2013 if (in_fuzzy_collect)
2014 {
2015 leader = ins_compl_leader();
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02002016 leader_len = (int)ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01002017 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002018
2019 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
2020 {
2021 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01002022 if (flags != DICT_EXACT && !shortmess(SHM_COMPLETIONSCAN))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002023 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01002024 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002025 vim_snprintf((char *)IObuff, IOSIZE,
2026 _("Scanning dictionary: %s"), (char *)files[i]);
2027 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2028 }
2029
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002030 if (fp == NULL)
2031 continue;
2032
2033 // Read dictionary file line by line.
2034 // Check each line for a match.
2035 while (!got_int && !compl_interrupted && !vim_fgets(buf, LSIZE, fp))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002036 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002037 ptr = buf;
glepnirf31cfa22025-03-06 21:59:13 +01002038 if (regmatch != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002039 {
glepnirf31cfa22025-03-06 21:59:13 +01002040 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002041 {
glepnirf31cfa22025-03-06 21:59:13 +01002042 ptr = regmatch->startp[0];
2043 ptr = ctrl_x_mode_line_or_eval() ? find_line_end(ptr)
2044 : find_word_end(ptr);
2045 add_r = ins_compl_add_infercase(regmatch->startp[0],
2046 (int)(ptr - regmatch->startp[0]),
2047 p_ic, files[i], *dir, FALSE, 0);
2048 if (thesaurus)
2049 {
2050 // For a thesaurus, add all the words in the line
2051 ptr = buf;
2052 add_r = thesaurus_add_words_in_line(files[i], &ptr, *dir,
2053 regmatch->startp[0]);
2054 }
2055 if (add_r == OK)
2056 // if dir was BACKWARD then honor it just once
2057 *dir = FORWARD;
2058 else if (add_r == FAIL)
2059 break;
2060 // avoid expensive call to vim_regexec() when at end
2061 // of line
2062 if (*ptr == '\n' || got_int)
2063 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002064 }
glepnirf31cfa22025-03-06 21:59:13 +01002065 }
2066 else if (in_fuzzy_collect && leader_len > 0)
2067 {
2068 line_end = find_line_end(ptr);
2069 while (ptr < line_end)
2070 {
2071 if (fuzzy_match_str_in_line(&ptr, leader, &len, NULL, &score))
2072 {
2073 char_u *end_ptr = ctrl_x_mode_line_or_eval()
2074 ? find_line_end(ptr) : find_word_end(ptr);
2075 add_r = ins_compl_add_infercase(ptr, (int)(end_ptr - ptr),
2076 p_ic, files[i], *dir, FALSE, score);
2077 if (add_r == FAIL)
2078 break;
2079 ptr = end_ptr; // start from next word
2080 if (compl_get_longest && ctrl_x_mode_normal()
2081 && compl_first_match->cp_next
2082 && score == compl_first_match->cp_next->cp_score)
2083 compl_num_bests++;
2084 }
glepnirf31cfa22025-03-06 21:59:13 +01002085 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002086 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002087 line_breakcheck();
2088 ins_compl_check_keys(50, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002089 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002090 fclose(fp);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002091 }
2092}
2093
2094/*
2095 * Find the start of the next word.
2096 * Returns a pointer to the first char of the word. Also stops at a NUL.
2097 */
2098 char_u *
2099find_word_start(char_u *ptr)
2100{
2101 if (has_mbyte)
glepnir19e1dd62025-05-08 22:50:38 +02002102 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002103 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
2104 ptr += (*mb_ptr2len)(ptr);
glepnir19e1dd62025-05-08 22:50:38 +02002105 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002106 else
glepnir19e1dd62025-05-08 22:50:38 +02002107 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002108 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
2109 ++ptr;
glepnir19e1dd62025-05-08 22:50:38 +02002110 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002111 return ptr;
2112}
2113
2114/*
2115 * Find the end of the word. Assumes it starts inside a word.
2116 * Returns a pointer to just after the word.
2117 */
2118 char_u *
2119find_word_end(char_u *ptr)
2120{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002121 if (has_mbyte)
2122 {
glepnir19e1dd62025-05-08 22:50:38 +02002123 int start_class = mb_get_class(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002124 if (start_class > 1)
2125 while (*ptr != NUL)
2126 {
2127 ptr += (*mb_ptr2len)(ptr);
2128 if (mb_get_class(ptr) != start_class)
2129 break;
2130 }
2131 }
2132 else
2133 while (vim_iswordc(*ptr))
2134 ++ptr;
2135 return ptr;
2136}
2137
2138/*
2139 * Find the end of the line, omitting CR and NL at the end.
2140 * Returns a pointer to just after the line.
2141 */
glepnirdd42b052025-03-08 16:52:55 +01002142 char_u *
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002143find_line_end(char_u *ptr)
2144{
glepnir19e1dd62025-05-08 22:50:38 +02002145 char_u *s = ptr + STRLEN(ptr);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002146 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
2147 --s;
2148 return s;
2149}
2150
2151/*
Girish Palyacbe53192025-04-14 22:13:15 +02002152 * Free a completion item in the list
2153 */
2154 static void
2155ins_compl_item_free(compl_T *match)
2156{
Girish Palyacbe53192025-04-14 22:13:15 +02002157 VIM_CLEAR_STRING(match->cp_str);
2158 // several entries may use the same fname, free it just once.
2159 if (match->cp_flags & CP_FREE_FNAME)
2160 vim_free(match->cp_fname);
glepnir19e1dd62025-05-08 22:50:38 +02002161 for (int i = 0; i < CPT_COUNT; ++i)
Girish Palyacbe53192025-04-14 22:13:15 +02002162 vim_free(match->cp_text[i]);
2163#ifdef FEAT_EVAL
2164 clear_tv(&match->cp_user_data);
2165#endif
2166 vim_free(match);
2167}
2168
2169/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002170 * Free the list of completions
2171 */
2172 static void
2173ins_compl_free(void)
2174{
2175 compl_T *match;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002176
John Marriott5e6ea922024-11-23 14:01:57 +01002177 VIM_CLEAR_STRING(compl_pattern);
2178 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002179
2180 if (compl_first_match == NULL)
2181 return;
2182
2183 ins_compl_del_pum();
2184 pum_clear();
2185
2186 compl_curr_match = compl_first_match;
2187 do
2188 {
2189 match = compl_curr_match;
2190 compl_curr_match = compl_curr_match->cp_next;
Girish Palyacbe53192025-04-14 22:13:15 +02002191 ins_compl_item_free(match);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002192 } while (compl_curr_match != NULL && !is_first_match(compl_curr_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002193 compl_first_match = compl_curr_match = NULL;
2194 compl_shown_match = NULL;
2195 compl_old_match = NULL;
2196}
2197
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002198/*
2199 * Reset/clear the completion state.
2200 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002201 void
2202ins_compl_clear(void)
2203{
2204 compl_cont_status = 0;
2205 compl_started = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01002206 compl_cfc_longest_ins = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002207 compl_matches = 0;
glepnir07f0dbe2025-02-18 20:27:30 +01002208 compl_selected_item = -1;
glepnir6a38aff2024-12-16 21:56:16 +01002209 compl_ins_end_col = 0;
glepnircf7f0122025-04-15 19:02:00 +02002210 compl_curr_win = NULL;
2211 compl_curr_buf = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002212 VIM_CLEAR_STRING(compl_pattern);
2213 VIM_CLEAR_STRING(compl_leader);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002214 edit_submode_extra = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002215 VIM_CLEAR_STRING(compl_orig_text);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002216 compl_enter_selects = FALSE;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002217 cpt_sources_clear();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002218#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002219 // clear v:completed_item
2220 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002221#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002222}
2223
2224/*
2225 * Return TRUE when Insert completion is active.
2226 */
2227 int
2228ins_compl_active(void)
2229{
2230 return compl_started;
2231}
2232
2233/*
glepnir8d0bb6d2024-12-24 09:44:35 +01002234 * Return True when wp is the actual completion window
2235 */
2236 int
glepnircf7f0122025-04-15 19:02:00 +02002237ins_compl_win_active(win_T *wp)
glepnir8d0bb6d2024-12-24 09:44:35 +01002238{
glepnircf7f0122025-04-15 19:02:00 +02002239 return ins_compl_active() && wp == compl_curr_win
2240 && wp->w_buffer == compl_curr_buf;
glepnir8d0bb6d2024-12-24 09:44:35 +01002241}
2242
2243/*
Girish Palyacbe53192025-04-14 22:13:15 +02002244 * Selected one of the matches. When FALSE, the match was either edited or
2245 * using the longest common string.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002246 */
2247 int
2248ins_compl_used_match(void)
2249{
2250 return compl_used_match;
2251}
2252
2253/*
2254 * Initialize get longest common string.
2255 */
2256 void
2257ins_compl_init_get_longest(void)
2258{
2259 compl_get_longest = FALSE;
2260}
2261
2262/*
2263 * Returns TRUE when insert completion is interrupted.
2264 */
2265 int
2266ins_compl_interrupted(void)
2267{
2268 return compl_interrupted;
2269}
2270
2271/*
2272 * Returns TRUE if the <Enter> key selects a match in the completion popup
2273 * menu.
2274 */
2275 int
2276ins_compl_enter_selects(void)
2277{
2278 return compl_enter_selects;
2279}
2280
2281/*
2282 * Return the column where the text starts that is being completed
2283 */
2284 colnr_T
2285ins_compl_col(void)
2286{
2287 return compl_col;
2288}
2289
2290/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002291 * Return the length in bytes of the text being completed
2292 */
2293 int
2294ins_compl_len(void)
2295{
2296 return compl_length;
2297}
2298
2299/*
glepnir94a045e2025-03-01 16:12:23 +01002300 * Return TRUE when the 'completeopt' "preinsert" flag is in effect,
2301 * otherwise return FALSE.
glepniredd4ac32025-01-29 18:53:51 +01002302 */
2303 static int
2304ins_compl_has_preinsert(void)
2305{
glepnira2c55592025-02-28 17:43:42 +01002306 int cur_cot_flags = get_cot_flags();
glepnir94a045e2025-03-01 16:12:23 +01002307 return (cur_cot_flags & (COT_PREINSERT | COT_FUZZY | COT_MENUONE))
2308 == (COT_PREINSERT | COT_MENUONE);
glepniredd4ac32025-01-29 18:53:51 +01002309}
2310
2311/*
2312 * Returns TRUE if the pre-insert effect is valid and the cursor is within
2313 * the `compl_ins_end_col` range.
2314 */
2315 int
2316ins_compl_preinsert_effect(void)
2317{
2318 if (!ins_compl_has_preinsert())
2319 return FALSE;
2320
2321 return curwin->w_cursor.col < compl_ins_end_col;
2322}
2323
2324/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002325 * Delete one character before the cursor and show the subset of the matches
2326 * that match the word that is now before the cursor.
2327 * Returns the character to be used, NUL if the work is done and another char
2328 * to be got from the user.
2329 */
2330 int
2331ins_compl_bs(void)
2332{
2333 char_u *line;
2334 char_u *p;
2335
glepniredd4ac32025-01-29 18:53:51 +01002336 if (ins_compl_preinsert_effect())
2337 ins_compl_delete();
2338
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002339 line = ml_get_curline();
2340 p = line + curwin->w_cursor.col;
2341 MB_PTR_BACK(line, p);
2342
2343 // Stop completion when the whole word was deleted. For Omni completion
2344 // allow the word to be deleted, we won't match everything.
2345 // Respect the 'backspace' option.
2346 if ((int)(p - line) - (int)compl_col < 0
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002347 || ((int)(p - line) - (int)compl_col == 0 && !ctrl_x_mode_omni())
2348 || ctrl_x_mode_eval()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002349 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
2350 - compl_length < 0))
2351 return K_BS;
2352
2353 // Deleted more than what was used to find matches or didn't finish
2354 // finding all matches: need to look for matches all over again.
2355 if (curwin->w_cursor.col <= compl_col + compl_length
2356 || ins_compl_need_restart())
2357 ins_compl_restart();
2358
John Marriott5e6ea922024-11-23 14:01:57 +01002359 VIM_CLEAR_STRING(compl_leader);
2360 compl_leader.length = (size_t)((p - line) - compl_col);
2361 compl_leader.string = vim_strnsave(line + compl_col, compl_leader.length);
2362 if (compl_leader.string == NULL)
2363 {
2364 compl_leader.length = 0;
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002365 return K_BS;
John Marriott5e6ea922024-11-23 14:01:57 +01002366 }
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00002367
2368 ins_compl_new_leader();
2369 if (compl_shown_match != NULL)
2370 // Make sure current match is not a hidden item.
2371 compl_curr_match = compl_shown_match;
2372 return NUL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002373}
2374
2375/*
2376 * Return TRUE when we need to find matches again, ins_compl_restart() is to
2377 * be called.
2378 */
2379 static int
2380ins_compl_need_restart(void)
2381{
2382 // Return TRUE if we didn't complete finding matches or when the
2383 // 'completefunc' returned "always" in the "refresh" dictionary item.
2384 return compl_was_interrupted
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002385 || ((ctrl_x_mode_function() || ctrl_x_mode_omni())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002386 && compl_opt_refresh_always);
2387}
2388
2389/*
2390 * Called after changing "compl_leader".
2391 * Show the popup menu with a different set of matches.
2392 * May also search for matches again if the previous search was interrupted.
2393 */
2394 static void
2395ins_compl_new_leader(void)
2396{
glepnirecf8f152025-06-10 20:52:41 +02002397 int cur_cot_flags = get_cot_flags();
Girish Palyaba11e782025-07-05 16:11:44 +02002398
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002399 ins_compl_del_pum();
2400 ins_compl_delete();
glepnir6a38aff2024-12-16 21:56:16 +01002401 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002402 compl_used_match = FALSE;
2403
2404 if (compl_started)
Girish Palyacbe53192025-04-14 22:13:15 +02002405 {
John Marriott5e6ea922024-11-23 14:01:57 +01002406 ins_compl_set_original_text(compl_leader.string, compl_leader.length);
Girish Palyacbe53192025-04-14 22:13:15 +02002407 if (is_cpt_func_refresh_always())
2408 cpt_compl_refresh();
2409 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002410 else
2411 {
2412#ifdef FEAT_SPELL
2413 spell_bad_len = 0; // need to redetect bad word
2414#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002415 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002416 // the popup menu display the changed text before the cursor. Set
2417 // "compl_restarting" to avoid that the first match is inserted.
2418 pum_call_update_screen();
2419#ifdef FEAT_GUI
2420 if (gui.in_use)
2421 {
2422 // Show the cursor after the match, not after the redrawn text.
2423 setcursor();
2424 out_flush_cursor(FALSE, FALSE);
2425 }
2426#endif
2427 compl_restarting = TRUE;
2428 if (ins_complete(Ctrl_N, TRUE) == FAIL)
2429 compl_cont_status = 0;
2430 compl_restarting = FALSE;
2431 }
2432
glepnirecf8f152025-06-10 20:52:41 +02002433 // When 'cot' contains "fuzzy" set the cp_score and maybe sort
2434 if (cur_cot_flags & COT_FUZZY)
Girish Palyab8ee1cf2025-06-08 16:20:06 +02002435 {
glepnirecf8f152025-06-10 20:52:41 +02002436 set_fuzzy_score();
2437 // Sort the matches linked list based on fuzzy score
2438 if (!(cur_cot_flags & COT_NOSORT))
Girish Palyab8ee1cf2025-06-08 16:20:06 +02002439 {
glepnirecf8f152025-06-10 20:52:41 +02002440 sort_compl_match_list(cp_compare_fuzzy);
2441 if ((cur_cot_flags & (COT_NOINSERT | COT_NOSELECT)) == COT_NOINSERT
2442 && compl_first_match)
2443 {
2444 compl_shown_match = compl_first_match;
2445 if (compl_shows_dir_forward())
2446 compl_shown_match = compl_first_match->cp_next;
2447 }
Girish Palyab8ee1cf2025-06-08 16:20:06 +02002448 }
2449 }
2450
glepnir44180412025-02-20 22:09:48 +01002451 compl_enter_selects = !compl_used_match && compl_selected_item != -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002452
2453 // Show the popup menu with a different set of matches.
2454 ins_compl_show_pum();
2455
2456 // Don't let Enter select the original text when there is no popup menu.
2457 if (compl_match_array == NULL)
2458 compl_enter_selects = FALSE;
glepniredd4ac32025-01-29 18:53:51 +01002459 else if (ins_compl_has_preinsert() && compl_leader.length > 0)
Girish Palya5fbe72e2025-06-18 19:15:45 +02002460 ins_compl_insert(TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002461}
2462
2463/*
2464 * Return the length of the completion, from the completion start column to
2465 * the cursor column. Making sure it never goes below zero.
2466 */
2467 static int
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002468get_compl_len(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002469{
2470 int off = (int)curwin->w_cursor.col - (int)compl_col;
glepnir40891ba2025-02-10 22:18:00 +01002471 return MAX(0, off);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002472}
2473
2474/*
2475 * Append one character to the match leader. May reduce the number of
2476 * matches.
2477 */
2478 void
2479ins_compl_addleader(int c)
2480{
glepnir19e1dd62025-05-08 22:50:38 +02002481 int cc;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002482
glepniredd4ac32025-01-29 18:53:51 +01002483 if (ins_compl_preinsert_effect())
2484 ins_compl_delete();
2485
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002486 if (stop_arrow() == FAIL)
2487 return;
2488 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
2489 {
2490 char_u buf[MB_MAXBYTES + 1];
2491
2492 (*mb_char2bytes)(c, buf);
2493 buf[cc] = NUL;
2494 ins_char_bytes(buf, cc);
2495 if (compl_opt_refresh_always)
2496 AppendToRedobuff(buf);
2497 }
2498 else
2499 {
2500 ins_char(c);
2501 if (compl_opt_refresh_always)
2502 AppendCharToRedobuff(c);
2503 }
2504
2505 // If we didn't complete finding matches we must search again.
2506 if (ins_compl_need_restart())
2507 ins_compl_restart();
2508
2509 // When 'always' is set, don't reset compl_leader. While completing,
2510 // cursor doesn't point original position, changing compl_leader would
2511 // break redo.
2512 if (!compl_opt_refresh_always)
2513 {
John Marriott5e6ea922024-11-23 14:01:57 +01002514 VIM_CLEAR_STRING(compl_leader);
2515 compl_leader.length = (size_t)(curwin->w_cursor.col - compl_col);
2516 compl_leader.string = vim_strnsave(ml_get_curline() + compl_col,
2517 compl_leader.length);
2518 if (compl_leader.string == NULL)
2519 {
2520 compl_leader.length = 0;
2521 return;
2522 }
2523
2524 ins_compl_new_leader();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002525 }
2526}
2527
2528/*
2529 * Setup for finding completions again without leaving CTRL-X mode. Used when
2530 * BS or a key was typed while still searching for matches.
2531 */
2532 static void
2533ins_compl_restart(void)
2534{
2535 ins_compl_free();
2536 compl_started = FALSE;
2537 compl_matches = 0;
2538 compl_cont_status = 0;
2539 compl_cont_mode = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02002540 cpt_sources_clear();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002541}
2542
2543/*
2544 * Set the first match, the original text.
2545 */
2546 static void
John Marriott5e6ea922024-11-23 14:01:57 +01002547ins_compl_set_original_text(char_u *str, size_t len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002548{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002549 // Replace the original text entry.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002550 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly
2551 // be at the last item for backward completion
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002552 if (match_at_original_text(compl_first_match)) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002553 {
John Marriott5e6ea922024-11-23 14:01:57 +01002554 char_u *p = vim_strnsave(str, len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002555 if (p != NULL)
2556 {
John Marriott5e6ea922024-11-23 14:01:57 +01002557 VIM_CLEAR_STRING(compl_first_match->cp_str);
2558 compl_first_match->cp_str.string = p;
2559 compl_first_match->cp_str.length = len;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002560 }
2561 }
2562 else if (compl_first_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002563 && match_at_original_text(compl_first_match->cp_prev))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002564 {
John Marriott5e6ea922024-11-23 14:01:57 +01002565 char_u *p = vim_strnsave(str, len);
2566 if (p != NULL)
2567 {
2568 VIM_CLEAR_STRING(compl_first_match->cp_prev->cp_str);
2569 compl_first_match->cp_prev->cp_str.string = p;
2570 compl_first_match->cp_prev->cp_str.length = len;
2571 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002572 }
2573}
2574
2575/*
2576 * Append one character to the match leader. May reduce the number of
2577 * matches.
2578 */
2579 void
2580ins_compl_addfrommatch(void)
2581{
2582 char_u *p;
2583 int len = (int)curwin->w_cursor.col - (int)compl_col;
2584 int c;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002585
John Marriott5e6ea922024-11-23 14:01:57 +01002586 p = compl_shown_match->cp_str.string;
2587 if ((int)compl_shown_match->cp_str.length <= len) // the match is too short
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002588 {
John Marriott5e6ea922024-11-23 14:01:57 +01002589 size_t plen;
2590 compl_T *cp;
2591
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002592 // When still at the original match use the first entry that matches
2593 // the leader.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002594 if (!match_at_original_text(compl_shown_match))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002595 return;
2596
2597 p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002598 plen = 0;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002599 for (cp = compl_shown_match->cp_next; cp != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002600 && !is_first_match(cp); cp = cp->cp_next)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002601 {
John Marriott5e6ea922024-11-23 14:01:57 +01002602 if (compl_leader.string == NULL
2603 || ins_compl_equal(cp, compl_leader.string,
2604 (int)compl_leader.length))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002605 {
John Marriott5e6ea922024-11-23 14:01:57 +01002606 p = cp->cp_str.string;
2607 plen = cp->cp_str.length;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00002608 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002609 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002610 }
John Marriott5e6ea922024-11-23 14:01:57 +01002611 if (p == NULL || (int)plen <= len)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002612 return;
2613 }
2614 p += len;
2615 c = PTR2CHAR(p);
2616 ins_compl_addleader(c);
2617}
2618
2619/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00002620 * Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002621 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
2622 * compl_cont_mode and compl_cont_status.
2623 * Returns TRUE when the character is not to be inserted.
2624 */
2625 static int
2626set_ctrl_x_mode(int c)
2627{
glepnir05460682025-05-26 18:23:27 +02002628 int retval = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002629
2630 switch (c)
2631 {
2632 case Ctrl_E:
2633 case Ctrl_Y:
2634 // scroll the window one line up or down
2635 ctrl_x_mode = CTRL_X_SCROLL;
2636 if (!(State & REPLACE_FLAG))
2637 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
2638 else
2639 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
2640 edit_submode_pre = NULL;
2641 showmode();
2642 break;
2643 case Ctrl_L:
2644 // complete whole line
2645 ctrl_x_mode = CTRL_X_WHOLE_LINE;
2646 break;
2647 case Ctrl_F:
2648 // complete filenames
2649 ctrl_x_mode = CTRL_X_FILES;
2650 break;
2651 case Ctrl_K:
zeertzjq5fb3aab2022-08-24 16:48:23 +01002652 // complete words from a dictionary
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002653 ctrl_x_mode = CTRL_X_DICTIONARY;
2654 break;
2655 case Ctrl_R:
glepnir05460682025-05-26 18:23:27 +02002656 // When CTRL-R is followed by '=', don't trigger register completion
2657 // This allows expressions like <C-R>=func()<CR> to work normally
2658 if (vpeekc() == '=')
2659 break;
2660 ctrl_x_mode = CTRL_X_REGISTER;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002661 break;
2662 case Ctrl_T:
2663 // complete words from a thesaurus
2664 ctrl_x_mode = CTRL_X_THESAURUS;
2665 break;
2666#ifdef FEAT_COMPL_FUNC
2667 case Ctrl_U:
2668 // user defined completion
2669 ctrl_x_mode = CTRL_X_FUNCTION;
2670 break;
2671 case Ctrl_O:
2672 // omni completion
2673 ctrl_x_mode = CTRL_X_OMNI;
2674 break;
2675#endif
2676 case 's':
2677 case Ctrl_S:
2678 // complete spelling suggestions
2679 ctrl_x_mode = CTRL_X_SPELL;
2680#ifdef FEAT_SPELL
2681 ++emsg_off; // Avoid getting the E756 error twice.
2682 spell_back_to_badword();
2683 --emsg_off;
2684#endif
2685 break;
2686 case Ctrl_RSB:
2687 // complete tag names
2688 ctrl_x_mode = CTRL_X_TAGS;
2689 break;
2690#ifdef FEAT_FIND_ID
2691 case Ctrl_I:
2692 case K_S_TAB:
2693 // complete keywords from included files
2694 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
2695 break;
2696 case Ctrl_D:
2697 // complete definitions from included files
2698 ctrl_x_mode = CTRL_X_PATH_DEFINES;
2699 break;
2700#endif
2701 case Ctrl_V:
2702 case Ctrl_Q:
2703 // complete vim commands
2704 ctrl_x_mode = CTRL_X_CMDLINE;
2705 break;
2706 case Ctrl_Z:
2707 // stop completion
2708 ctrl_x_mode = CTRL_X_NORMAL;
2709 edit_submode = NULL;
2710 showmode();
2711 retval = TRUE;
2712 break;
2713 case Ctrl_P:
2714 case Ctrl_N:
2715 // ^X^P means LOCAL expansion if nothing interrupted (eg we
2716 // just started ^X mode, or there were enough ^X's to cancel
2717 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
2718 // do normal expansion when interrupting a different mode (say
2719 // ^X^F^X^P or ^P^X^X^P, see below)
2720 // nothing changes if interrupting mode 0, (eg, the flag
2721 // doesn't change when going to ADDING mode -- Acevedo
2722 if (!(compl_cont_status & CONT_INTRPT))
2723 compl_cont_status |= CONT_LOCAL;
2724 else if (compl_cont_mode != 0)
2725 compl_cont_status &= ~CONT_LOCAL;
2726 // FALLTHROUGH
2727 default:
2728 // If we have typed at least 2 ^X's... for modes != 0, we set
2729 // compl_cont_status = 0 (eg, as if we had just started ^X
2730 // mode).
2731 // For mode 0, we set "compl_cont_mode" to an impossible
2732 // value, in both cases ^X^X can be used to restart the same
2733 // mode (avoiding ADDING mode).
2734 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
2735 // 'complete' and local ^P expansions respectively.
2736 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
2737 // mode -- Acevedo
2738 if (c == Ctrl_X)
2739 {
2740 if (compl_cont_mode != 0)
2741 compl_cont_status = 0;
2742 else
2743 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
2744 }
2745 ctrl_x_mode = CTRL_X_NORMAL;
2746 edit_submode = NULL;
2747 showmode();
2748 break;
2749 }
2750
2751 return retval;
2752}
2753
2754/*
glepnir1c5a1202024-12-04 20:27:34 +01002755 * Trigger CompleteDone event and adds relevant information to v:event
2756 */
2757 static void
2758trigger_complete_done_event(int mode UNUSED, char_u *word UNUSED)
2759{
2760#if defined(FEAT_EVAL)
2761 save_v_event_T save_v_event;
2762 dict_T *v_event = get_v_event(&save_v_event);
2763 char_u *mode_str = NULL;
2764
2765 mode = mode & ~CTRL_X_WANT_IDENT;
2766 if (ctrl_x_mode_names[mode])
2767 mode_str = (char_u *)ctrl_x_mode_names[mode];
2768
2769 (void)dict_add_string(v_event, "complete_word",
2770 word == NULL ? (char_u *)"" : word);
2771 (void)dict_add_string(v_event, "complete_type",
2772 mode_str != NULL ? mode_str : (char_u *)"");
2773
2774 dict_set_items_ro(v_event);
2775#endif
2776 ins_apply_autocmds(EVENT_COMPLETEDONE);
2777
2778#if defined(FEAT_EVAL)
2779 restore_v_event(v_event, &save_v_event);
2780#endif
2781}
2782
2783/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002784 * Stop insert completion mode
2785 */
2786 static int
2787ins_compl_stop(int c, int prev_mode, int retval)
2788{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002789 int want_cindent;
glepnir1c5a1202024-12-04 20:27:34 +01002790 char_u *word = NULL;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002791
glepnir84a75032025-03-15 09:59:22 +01002792 // Remove pre-inserted text when present.
zeertzjq13436812025-04-23 20:46:35 +02002793 if (ins_compl_preinsert_effect() && ins_compl_win_active(curwin))
glepnir84a75032025-03-15 09:59:22 +01002794 ins_compl_delete();
2795
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002796 // Get here when we have finished typing a sequence of ^N and
2797 // ^P or other completion characters in CTRL-X mode. Free up
2798 // memory that was used, and make sure we can redo the insert.
John Marriott5e6ea922024-11-23 14:01:57 +01002799 if (compl_curr_match != NULL || compl_leader.string != NULL || c == Ctrl_E)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002800 {
glepnir40891ba2025-02-10 22:18:00 +01002801 char_u *ptr = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002802
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002803 // If any of the original typed text has been changed, eg when
2804 // ignorecase is set, we must add back-spaces to the redo
2805 // buffer. We add as few as necessary to delete just the part
2806 // of the original text that has changed.
2807 // When using the longest match, edited the match or used
2808 // CTRL-E then don't use the current match.
2809 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
John Marriott5e6ea922024-11-23 14:01:57 +01002810 ptr = compl_curr_match->cp_str.string;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002811 ins_compl_fixRedoBufForLeader(ptr);
2812 }
2813
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002814 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar8e145b82022-05-21 20:17:31 +01002815
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002816 // When completing whole lines: fix indent for 'cindent'.
2817 // Otherwise, break line if it's too long.
2818 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2819 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002820 // re-indent the current line
2821 if (want_cindent)
2822 {
2823 do_c_expr_indent();
2824 want_cindent = FALSE; // don't do it again
2825 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002826 }
2827 else
2828 {
2829 int prev_col = curwin->w_cursor.col;
2830
2831 // put the cursor on the last char, for 'tw' formatting
2832 if (prev_col > 0)
2833 dec_cursor();
2834 // only format when something was inserted
2835 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2836 insertchar(NUL, 0, -1);
2837 if (prev_col > 0
2838 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2839 inc_cursor();
2840 }
2841
2842 // If the popup menu is displayed pressing CTRL-Y means accepting
2843 // the selection without inserting anything. When
2844 // compl_enter_selects is set the Enter key does the same.
2845 if ((c == Ctrl_Y || (compl_enter_selects
2846 && (c == CAR || c == K_KENTER || c == NL)))
2847 && pum_visible())
glepnir1c5a1202024-12-04 20:27:34 +01002848 {
2849 word = vim_strsave(compl_shown_match->cp_str.string);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002850 retval = TRUE;
glepnir1c5a1202024-12-04 20:27:34 +01002851 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002852
2853 // CTRL-E means completion is Ended, go back to the typed text.
2854 // but only do this, if the Popup is still visible
2855 if (c == Ctrl_E)
2856 {
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002857 char_u *p = NULL;
John Marriott5e6ea922024-11-23 14:01:57 +01002858 size_t plen = 0;
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002859
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002860 ins_compl_delete();
John Marriott5e6ea922024-11-23 14:01:57 +01002861 if (compl_leader.string != NULL)
2862 {
2863 p = compl_leader.string;
2864 plen = compl_leader.length;
2865 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002866 else if (compl_first_match != NULL)
John Marriott5e6ea922024-11-23 14:01:57 +01002867 {
2868 p = compl_orig_text.string;
2869 plen = compl_orig_text.length;
2870 }
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002871 if (p != NULL)
2872 {
2873 int compl_len = get_compl_len();
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002874
John Marriott5e6ea922024-11-23 14:01:57 +01002875 if ((int)plen > compl_len)
zeertzjqf25d8f92024-12-18 21:12:25 +01002876 ins_compl_insert_bytes(p + compl_len, (int)plen - compl_len);
Bram Moolenaarf12129f2022-07-01 19:58:30 +01002877 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002878 retval = TRUE;
2879 }
2880
2881 auto_format(FALSE, TRUE);
2882
2883 // Trigger the CompleteDonePre event to give scripts a chance to
2884 // act upon the completion before clearing the info, and restore
2885 // ctrl_x_mode, so that complete_info() can be used.
2886 ctrl_x_mode = prev_mode;
2887 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2888
2889 ins_compl_free();
2890 compl_started = FALSE;
2891 compl_matches = 0;
2892 if (!shortmess(SHM_COMPLETIONMENU))
2893 msg_clr_cmdline(); // necessary for "noshowmode"
2894 ctrl_x_mode = CTRL_X_NORMAL;
2895 compl_enter_selects = FALSE;
2896 if (edit_submode != NULL)
2897 {
2898 edit_submode = NULL;
2899 showmode();
2900 }
2901
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002902 if (c == Ctrl_C && cmdwin_type != 0)
2903 // Avoid the popup menu remains displayed when leaving the
2904 // command line window.
2905 update_screen(0);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002906 // Indent now if a key was typed that is in 'cinkeys'.
2907 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2908 do_c_expr_indent();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002909 // Trigger the CompleteDone event to give scripts a chance to act
2910 // upon the end of completion.
glepnir1c5a1202024-12-04 20:27:34 +01002911 trigger_complete_done_event(prev_mode, word);
2912 vim_free(word);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002913
2914 return retval;
2915}
2916
2917/*
glepnircf7f0122025-04-15 19:02:00 +02002918 * Cancel completion.
2919 */
2920 int
2921ins_compl_cancel(void)
2922{
2923 return ins_compl_stop(' ', ctrl_x_mode, TRUE);
2924}
2925
2926/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002927 * Prepare for Insert mode completion, or stop it.
2928 * Called just after typing a character in Insert mode.
2929 * Returns TRUE when the character is not to be inserted;
2930 */
2931 int
2932ins_compl_prep(int c)
2933{
glepnir19e1dd62025-05-08 22:50:38 +02002934 int retval = FALSE;
2935 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002936
2937 // Forget any previous 'special' messages if this is actually
2938 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2939 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2940 edit_submode_extra = NULL;
2941
zeertzjq440d4cb2023-03-02 17:51:32 +00002942 // Ignore end of Select mode mapping and mouse scroll/movement.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002943 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
zeertzjq440d4cb2023-03-02 17:51:32 +00002944 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE
Bram Moolenaare32c3c42022-01-15 18:26:04 +00002945 || c == K_COMMAND || c == K_SCRIPT_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002946 return retval;
2947
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002948#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002949 // Ignore mouse events in a popup window
2950 if (is_mouse_key(c))
2951 {
2952 // Ignore drag and release events, the position does not need to be in
2953 // the popup and it may have just closed.
2954 if (c == K_LEFTRELEASE
2955 || c == K_LEFTRELEASE_NM
2956 || c == K_MIDDLERELEASE
2957 || c == K_RIGHTRELEASE
2958 || c == K_X1RELEASE
2959 || c == K_X2RELEASE
2960 || c == K_LEFTDRAG
2961 || c == K_MIDDLEDRAG
2962 || c == K_RIGHTDRAG
2963 || c == K_X1DRAG
2964 || c == K_X2DRAG)
2965 return retval;
2966 if (popup_visible)
2967 {
2968 int row = mouse_row;
2969 int col = mouse_col;
2970 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2971
2972 if (wp != NULL && WIN_IS_POPUP(wp))
2973 return retval;
2974 }
2975 }
2976#endif
2977
zeertzjqdca29d92021-08-31 19:12:51 +02002978 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2979 {
2980 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2981 || !vim_is_ctrl_x_key(c))
2982 {
2983 // Not starting another completion mode.
2984 ctrl_x_mode = CTRL_X_CMDLINE;
2985
2986 // CTRL-X CTRL-Z should stop completion without inserting anything
2987 if (c == Ctrl_Z)
2988 retval = TRUE;
2989 }
2990 else
2991 {
2992 ctrl_x_mode = CTRL_X_CMDLINE;
2993
2994 // Other CTRL-X keys first stop completion, then start another
2995 // completion mode.
2996 ins_compl_prep(' ');
2997 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2998 }
2999 }
3000
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003001 // Set "compl_get_longest" when finding the first matches.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003002 if (ctrl_x_mode_not_defined_yet()
3003 || (ctrl_x_mode_normal() && !compl_started))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003004 {
zeertzjq529b9ad2024-06-05 20:27:06 +02003005 compl_get_longest = (get_cot_flags() & COT_LONGEST) != 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003006 compl_used_match = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003007 }
3008
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003009 if (ctrl_x_mode_not_defined_yet())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003010 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
3011 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003012 retval = set_ctrl_x_mode(c);
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003013 else if (ctrl_x_mode_not_default())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003014 {
3015 // We're already in CTRL-X mode, do we stay in it?
3016 if (!vim_is_ctrl_x_key(c))
3017 {
glepnir40891ba2025-02-10 22:18:00 +01003018 ctrl_x_mode = ctrl_x_mode_scroll() ? CTRL_X_NORMAL : CTRL_X_FINISHED;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003019 edit_submode = NULL;
3020 }
3021 showmode();
3022 }
3023
3024 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
3025 {
3026 // Show error message from attempted keyword completion (probably
3027 // 'Pattern not found') until another key is hit, then go back to
3028 // showing what mode we are in.
3029 showmode();
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003030 if ((ctrl_x_mode_normal() && c != Ctrl_N && c != Ctrl_P
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003031 && c != Ctrl_R && !ins_compl_pum_key(c))
3032 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003033 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003034 }
3035 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
3036 // Trigger the CompleteDone event to give scripts a chance to act
3037 // upon the (possibly failed) completion.
glepnir1c5a1202024-12-04 20:27:34 +01003038 trigger_complete_done_event(ctrl_x_mode, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003039
LemonBoy2bf52dd2022-04-09 18:17:34 +01003040 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003041
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003042 // reset continue_* if we left expansion-mode, if we stay they'll be
3043 // (re)set properly in ins_complete()
3044 if (!vim_is_ctrl_x_key(c))
3045 {
3046 compl_cont_status = 0;
3047 compl_cont_mode = 0;
3048 }
3049
3050 return retval;
3051}
3052
3053/*
3054 * Fix the redo buffer for the completion leader replacing some of the typed
3055 * text. This inserts backspaces and appends the changed text.
3056 * "ptr" is the known leader text or NUL.
3057 */
3058 static void
3059ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
3060{
John Marriott5e6ea922024-11-23 14:01:57 +01003061 int len = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003062 char_u *p;
3063 char_u *ptr = ptr_arg;
3064
3065 if (ptr == NULL)
3066 {
John Marriott5e6ea922024-11-23 14:01:57 +01003067 if (compl_leader.string != NULL)
3068 ptr = compl_leader.string;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003069 else
3070 return; // nothing to do
3071 }
John Marriott5e6ea922024-11-23 14:01:57 +01003072 if (compl_orig_text.string != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003073 {
John Marriott5e6ea922024-11-23 14:01:57 +01003074 p = compl_orig_text.string;
glepnir40891ba2025-02-10 22:18:00 +01003075 // Find length of common prefix between original text and new completion
3076 while (p[len] != NUL && p[len] == ptr[len])
3077 len++;
3078 // Adjust length to not break inside a multi-byte character
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003079 if (len > 0)
3080 len -= (*mb_head_off)(p, p + len);
glepnir40891ba2025-02-10 22:18:00 +01003081 // Add backspace characters for each remaining character in
3082 // original text
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003083 for (p += len; *p != NUL; MB_PTR_ADV(p))
3084 AppendCharToRedobuff(K_BS);
3085 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003086 if (ptr != NULL)
3087 AppendToRedobuffLit(ptr + len, -1);
3088}
3089
3090/*
3091 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
3092 * (depending on flag) starting from buf and looking for a non-scanned
3093 * buffer (other than curbuf). curbuf is special, if it is called with
3094 * buf=curbuf then it has to be the first call for a given flag/expansion.
3095 *
3096 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
3097 */
3098 static buf_T *
3099ins_compl_next_buf(buf_T *buf, int flag)
3100{
glepnir19e1dd62025-05-08 22:50:38 +02003101 static win_T *wp = NULL;
3102 int skip_buffer;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003103
3104 if (flag == 'w') // just windows
3105 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01003106 if (buf == curbuf || !win_valid(wp))
3107 // first call for this flag/expansion or window was closed
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003108 wp = curwin;
glepnir40891ba2025-02-10 22:18:00 +01003109
3110 while (TRUE)
3111 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003112 // Move to next window (wrap to first window if at the end)
3113 wp = (wp->w_next != NULL) ? wp->w_next : firstwin;
3114 // Break if we're back at start or found an unscanned buffer
3115 if (wp == curwin || !wp->w_buffer->b_scanned)
3116 break;
glepnir40891ba2025-02-10 22:18:00 +01003117 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003118 buf = wp->w_buffer;
3119 }
3120 else
glepnir40891ba2025-02-10 22:18:00 +01003121 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003122 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
3123 // (unlisted buffers)
3124 // When completing whole lines skip unloaded buffers.
glepnir40891ba2025-02-10 22:18:00 +01003125 while (TRUE)
3126 {
3127 // Move to next buffer (wrap to first buffer if at the end)
3128 buf = (buf->b_next != NULL) ? buf->b_next : firstbuf;
3129 // Break if we're back at start buffer
3130 if (buf == curbuf)
3131 break;
3132
3133 // Check buffer conditions based on flag
3134 if (flag == 'U')
3135 skip_buffer = buf->b_p_bl;
3136 else
3137 skip_buffer = !buf->b_p_bl ||
3138 (buf->b_ml.ml_mfp == NULL) != (flag == 'u');
3139
3140 // Break if we found a buffer that matches our criteria
3141 if (!skip_buffer && !buf->b_scanned)
3142 break;
3143 }
3144 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003145 return buf;
3146}
3147
3148#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003149
3150# ifdef FEAT_EVAL
3151static callback_T cfu_cb; // 'completefunc' callback function
3152static callback_T ofu_cb; // 'omnifunc' callback function
3153static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
3154# endif
3155
3156/*
3157 * Copy a global callback function to a buffer local callback.
3158 */
3159 static void
3160copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
3161{
3162 free_callback(bufcb);
3163 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
3164 copy_callback(bufcb, globcb);
3165}
3166
3167/*
3168 * Parse the 'completefunc' option value and set the callback function.
3169 * Invoked when the 'completefunc' option is set. The option value can be a
3170 * name of a function (string), or function(<name>) or funcref(<name>) or a
3171 * lambda expression.
3172 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003173 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003174did_set_completefunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003175{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003176 if (option_set_callback_func(curbuf->b_p_cfu, &cfu_cb) == FAIL)
3177 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003178
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003179 set_buflocal_cfu_callback(curbuf);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003180
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003181 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003182}
3183
3184/*
3185 * Copy the global 'completefunc' callback function to the buffer-local
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003186 * 'completefunc' callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003187 */
3188 void
3189set_buflocal_cfu_callback(buf_T *buf UNUSED)
3190{
3191# ifdef FEAT_EVAL
3192 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
3193# endif
3194}
3195
3196/*
3197 * Parse the 'omnifunc' option value and set the callback function.
3198 * Invoked when the 'omnifunc' option is set. The option value can be a
3199 * name of a function (string), or function(<name>) or funcref(<name>) or a
3200 * lambda expression.
3201 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003202 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003203did_set_omnifunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003204{
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003205 if (option_set_callback_func(curbuf->b_p_ofu, &ofu_cb) == FAIL)
3206 return e_invalid_argument;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003207
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003208 set_buflocal_ofu_callback(curbuf);
3209 return NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003210}
3211
3212/*
3213 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003214 * callback for "buf".
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003215 */
3216 void
3217set_buflocal_ofu_callback(buf_T *buf UNUSED)
3218{
3219# ifdef FEAT_EVAL
3220 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
3221# endif
3222}
3223
3224/*
3225 * Parse the 'thesaurusfunc' option value and set the callback function.
3226 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
3227 * name of a function (string), or function(<name>) or funcref(<name>) or a
3228 * lambda expression.
3229 */
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003230 char *
Yegappan Lakshmananaf936912023-02-20 12:16:39 +00003231did_set_thesaurusfunc(optset_T *args UNUSED)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003232{
3233 int retval;
3234
zeertzjq6eda2692024-11-03 09:23:33 +01003235 if (args->os_flags & OPT_LOCAL)
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003236 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003237 retval = option_set_callback_func(curbuf->b_p_tsrfu,
3238 &curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003239 else
3240 {
3241 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003242 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
zeertzjq6eda2692024-11-03 09:23:33 +01003243 // when using :set, free the local callback
3244 if (!(args->os_flags & OPT_GLOBAL))
3245 free_callback(&curbuf->b_tsrfu_cb);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003246 }
3247
Yegappan Lakshmananf2e30d02023-01-30 13:04:42 +00003248 return retval == FAIL ? e_invalid_argument : NULL;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003249}
3250
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003251/*
3252 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003253 * "copyID" so that they are not garbage collected.
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003254 */
3255 int
3256set_ref_in_insexpand_funcs(int copyID)
3257{
glepnir19e1dd62025-05-08 22:50:38 +02003258 int abort = set_ref_in_callback(&cfu_cb, copyID);
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00003259 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
3260 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
3261
3262 return abort;
3263}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003264
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003265/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003266 * Get the user-defined completion function name for completion "type"
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003267 */
3268 static char_u *
3269get_complete_funcname(int type)
3270{
3271 switch (type)
3272 {
3273 case CTRL_X_FUNCTION:
3274 return curbuf->b_p_cfu;
3275 case CTRL_X_OMNI:
3276 return curbuf->b_p_ofu;
3277 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01003278 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01003279 default:
3280 return (char_u *)"";
3281 }
3282}
3283
3284/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003285 * Get the callback to use for insert mode completion.
3286 */
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003287 static callback_T *
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003288get_insert_callback(int type)
3289{
3290 if (type == CTRL_X_FUNCTION)
3291 return &curbuf->b_cfu_cb;
3292 if (type == CTRL_X_OMNI)
3293 return &curbuf->b_ofu_cb;
3294 // CTRL_X_THESAURUS
3295 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
3296}
3297
3298/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00003299 * Execute user defined complete function 'completefunc', 'omnifunc' or
3300 * 'thesaurusfunc', and get matches in "matches".
Girish Palyacbe53192025-04-14 22:13:15 +02003301 * "type" can be one of CTRL_X_OMNI, CTRL_X_FUNCTION, or CTRL_X_THESAURUS.
3302 * Callback function "cb" is set if triggered by a function in the 'cpt'
3303 * option; otherwise, it is NULL.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003304 */
3305 static void
Girish Palyacbe53192025-04-14 22:13:15 +02003306expand_by_function(int type, char_u *base, callback_T *cb)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003307{
3308 list_T *matchlist = NULL;
3309 dict_T *matchdict = NULL;
3310 typval_T args[3];
3311 char_u *funcname;
3312 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003313 typval_T rettv;
3314 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003315 int retval;
Girish Palyacbe53192025-04-14 22:13:15 +02003316 int is_cpt_function = (cb != NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003317
Girish Palyacbe53192025-04-14 22:13:15 +02003318 if (!is_cpt_function)
3319 {
3320 funcname = get_complete_funcname(type);
3321 if (*funcname == NUL)
3322 return;
3323 cb = get_insert_callback(type);
3324 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003325
3326 // Call 'completefunc' to obtain the list of matches.
3327 args[0].v_type = VAR_NUMBER;
3328 args[0].vval.v_number = 0;
3329 args[1].v_type = VAR_STRING;
3330 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
3331 args[2].v_type = VAR_UNKNOWN;
3332
3333 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01003334 // Lock the text to avoid weird things from happening. Also disallow
3335 // switching to another window, it should not be needed and may end up in
3336 // Insert mode in another buffer.
zeertzjqcfe45652022-05-27 17:26:55 +01003337 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003338
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003339 retval = call_callback(cb, 0, &rettv, 2, args);
3340
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003341 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00003342 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003343 {
3344 switch (rettv.v_type)
3345 {
3346 case VAR_LIST:
3347 matchlist = rettv.vval.v_list;
3348 break;
3349 case VAR_DICT:
3350 matchdict = rettv.vval.v_dict;
3351 break;
3352 case VAR_SPECIAL:
3353 if (rettv.vval.v_number == VVAL_NONE)
3354 compl_opt_suppress_empty = TRUE;
3355 // FALLTHROUGH
3356 default:
3357 // TODO: Give error message?
3358 clear_tv(&rettv);
3359 break;
3360 }
3361 }
zeertzjqcfe45652022-05-27 17:26:55 +01003362 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003363
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003364 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02003365 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003366 validate_cursor();
3367 if (!EQUAL_POS(curwin->w_cursor, pos))
3368 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00003369 emsg(_(e_complete_function_deleted_text));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003370 goto theend;
3371 }
3372
3373 if (matchlist != NULL)
3374 ins_compl_add_list(matchlist);
3375 else if (matchdict != NULL)
3376 ins_compl_add_dict(matchdict);
3377
3378theend:
3379 // Restore State, it might have been changed.
3380 State = save_State;
3381
3382 if (matchdict != NULL)
3383 dict_unref(matchdict);
3384 if (matchlist != NULL)
3385 list_unref(matchlist);
3386}
3387#endif // FEAT_COMPL_FUNC
3388
3389#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
glepnir38f99a12024-08-23 18:31:06 +02003390
3391 static inline int
3392get_user_highlight_attr(char_u *hlname)
3393{
3394 if (hlname != NULL && *hlname != NUL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003395 return syn_name2attr(hlname);
glepnir38f99a12024-08-23 18:31:06 +02003396 return -1;
3397}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003398/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003399 * Add a match to the list of matches from a typeval_T.
3400 * If the given string is already in the list of completions, then return
3401 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
3402 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02003403 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003404 */
3405 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02003406ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003407{
3408 char_u *word;
3409 int dup = FALSE;
3410 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02003411 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003412 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01003413 typval_T user_data;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003414 int status;
glepnir0fe17f82024-10-08 22:26:44 +02003415 char_u *user_abbr_hlname;
glepnir38f99a12024-08-23 18:31:06 +02003416 char_u *user_kind_hlname;
glepnir80b66202024-11-27 21:53:53 +01003417 int user_hl[2] = { -1, -1 };
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003418
Bram Moolenaar08928322020-01-04 14:32:48 +01003419 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003420 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
3421 {
Bram Moolenaard61efa52022-07-23 09:52:04 +01003422 word = dict_get_string(tv->vval.v_dict, "word", FALSE);
3423 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict, "abbr", FALSE);
3424 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict, "menu", FALSE);
3425 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict, "kind", FALSE);
3426 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict, "info", FALSE);
glepnir38f99a12024-08-23 18:31:06 +02003427
glepnir0fe17f82024-10-08 22:26:44 +02003428 user_abbr_hlname = dict_get_string(tv->vval.v_dict, "abbr_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003429 user_hl[0] = get_user_highlight_attr(user_abbr_hlname);
glepnir38f99a12024-08-23 18:31:06 +02003430
3431 user_kind_hlname = dict_get_string(tv->vval.v_dict, "kind_hlgroup", FALSE);
glepnir80b66202024-11-27 21:53:53 +01003432 user_hl[1] = get_user_highlight_attr(user_kind_hlname);
glepnir508e7852024-07-25 21:39:08 +02003433
Bram Moolenaard61efa52022-07-23 09:52:04 +01003434 dict_get_tv(tv->vval.v_dict, "user_data", &user_data);
3435 if (dict_get_string(tv->vval.v_dict, "icase", FALSE) != NULL
3436 && dict_get_number(tv->vval.v_dict, "icase"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003437 flags |= CP_ICASE;
Bram Moolenaard61efa52022-07-23 09:52:04 +01003438 if (dict_get_string(tv->vval.v_dict, "dup", FALSE) != NULL)
3439 dup = dict_get_number(tv->vval.v_dict, "dup");
3440 if (dict_get_string(tv->vval.v_dict, "empty", FALSE) != NULL)
3441 empty = dict_get_number(tv->vval.v_dict, "empty");
3442 if (dict_get_string(tv->vval.v_dict, "equal", FALSE) != NULL
3443 && dict_get_number(tv->vval.v_dict, "equal"))
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003444 flags |= CP_EQUAL;
3445 }
3446 else
3447 {
3448 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02003449 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003450 }
3451 if (word == NULL || (!empty && *word == NUL))
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003452 {
3453 clear_tv(&user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003454 return FAIL;
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003455 }
glepnir508e7852024-07-25 21:39:08 +02003456 status = ins_compl_add(word, -1, NULL, cptext,
glepnirf31cfa22025-03-06 21:59:13 +01003457 &user_data, dir, flags, dup, user_hl, 0);
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00003458 if (status != OK)
3459 clear_tv(&user_data);
3460 return status;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003461}
3462
3463/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003464 * Add completions from a list.
3465 */
3466 static void
3467ins_compl_add_list(list_T *list)
3468{
3469 listitem_T *li;
3470 int dir = compl_direction;
3471
3472 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003473 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003474 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003475 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02003476 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003477 // if dir was BACKWARD then honor it just once
3478 dir = FORWARD;
3479 else if (did_emsg)
3480 break;
3481 }
3482}
3483
3484/*
3485 * Add completions from a dict.
3486 */
3487 static void
3488ins_compl_add_dict(dict_T *dict)
3489{
3490 dictitem_T *di_refresh;
3491 dictitem_T *di_words;
3492
3493 // Check for optional "refresh" item.
3494 compl_opt_refresh_always = FALSE;
3495 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
3496 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
3497 {
3498 char_u *v = di_refresh->di_tv.vval.v_string;
3499
3500 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
3501 compl_opt_refresh_always = TRUE;
3502 }
3503
3504 // Add completions from a "words" list.
3505 di_words = dict_find(dict, (char_u *)"words", 5);
3506 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
3507 ins_compl_add_list(di_words->di_tv.vval.v_list);
3508}
3509
3510/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003511 * Start completion for the complete() function.
3512 * "startcol" is where the matched text starts (1 is first column).
3513 * "list" is the list of matches.
3514 */
3515 static void
3516set_completion(colnr_T startcol, list_T *list)
3517{
3518 int save_w_wrow = curwin->w_wrow;
3519 int save_w_leftcol = curwin->w_leftcol;
3520 int flags = CP_ORIGINAL_TEXT;
zeertzjqaa925ee2024-06-09 18:24:05 +02003521 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02003522 int compl_longest = (cur_cot_flags & COT_LONGEST) != 0;
3523 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
3524 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003525
3526 // If already doing completions stop it.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003527 if (ctrl_x_mode_not_default())
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003528 ins_compl_prep(' ');
3529 ins_compl_clear();
3530 ins_compl_free();
bfredl87af60c2022-09-24 11:17:51 +01003531 compl_get_longest = compl_longest;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003532
3533 compl_direction = FORWARD;
3534 if (startcol > curwin->w_cursor.col)
3535 startcol = curwin->w_cursor.col;
3536 compl_col = startcol;
glepnir76bdb822025-02-08 19:04:51 +01003537 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003538 compl_length = (int)curwin->w_cursor.col - (int)startcol;
3539 // compl_pattern doesn't need to be set
glepniredd4ac32025-01-29 18:53:51 +01003540 compl_orig_text.string = vim_strnsave(ml_get_curline() + compl_col,
3541 (size_t)compl_length);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003542 if (p_ic)
3543 flags |= CP_ICASE;
John Marriott5e6ea922024-11-23 14:01:57 +01003544 if (compl_orig_text.string == NULL)
3545 {
3546 compl_orig_text.length = 0;
3547 return;
3548 }
3549 compl_orig_text.length = (size_t)compl_length;
3550 if (ins_compl_add(compl_orig_text.string,
Hirohito Higashi355db992025-04-28 18:07:02 +02003551 (int)compl_orig_text.length, NULL, NULL, NULL, 0,
3552 flags | CP_FAST, FALSE, NULL, 0) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003553 return;
3554
3555 ctrl_x_mode = CTRL_X_EVAL;
3556
3557 ins_compl_add_list(list);
3558 compl_matches = ins_compl_make_cyclic();
3559 compl_started = TRUE;
3560 compl_used_match = TRUE;
3561 compl_cont_status = 0;
3562
3563 compl_curr_match = compl_first_match;
bfredl87af60c2022-09-24 11:17:51 +01003564 int no_select = compl_no_select || compl_longest;
3565 if (compl_no_insert || no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003566 {
3567 ins_complete(K_DOWN, FALSE);
bfredl87af60c2022-09-24 11:17:51 +01003568 if (no_select)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003569 // Down/Up has no real effect.
3570 ins_complete(K_UP, FALSE);
3571 }
3572 else
3573 ins_complete(Ctrl_N, FALSE);
3574 compl_enter_selects = compl_no_insert;
3575
3576 // Lazily show the popup menu, unless we got interrupted.
3577 if (!compl_interrupted)
3578 show_pum(save_w_wrow, save_w_leftcol);
LemonBoy2bf52dd2022-04-09 18:17:34 +01003579 may_trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003580 out_flush();
3581}
3582
3583/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003584 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003585 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003586 void
3587f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003588{
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003589 if (in_vim9script()
3590 && (check_for_number_arg(argvars, 0) == FAIL
3591 || check_for_list_arg(argvars, 1) == FAIL))
3592 return;
3593
Bram Moolenaar24959102022-05-07 20:01:16 +01003594 if ((State & MODE_INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003595 {
Bram Moolenaar677658a2022-01-05 16:09:06 +00003596 emsg(_(e_complete_can_only_be_used_in_insert_mode));
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003597 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003598 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003599
3600 // Check for undo allowed here, because if something was already inserted
3601 // the line was already saved for undo and this check isn't done.
3602 if (!undo_allowed())
3603 return;
3604
Bram Moolenaard83392a2022-09-01 12:22:46 +01003605 if (check_for_nonnull_list_arg(argvars, 1) != FAIL)
Bram Moolenaarff06f282020-04-21 22:01:14 +02003606 {
glepnir19e1dd62025-05-08 22:50:38 +02003607 int startcol = (int)tv_get_number_chk(&argvars[0], NULL);
Bram Moolenaarff06f282020-04-21 22:01:14 +02003608 if (startcol > 0)
3609 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003610 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003611}
3612
3613/*
3614 * "complete_add()" function
3615 */
3616 void
3617f_complete_add(typval_T *argvars, typval_T *rettv)
3618{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02003619 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02003620 return;
3621
Bram Moolenaar440cf092021-04-03 20:13:30 +02003622 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003623}
3624
3625/*
3626 * "complete_check()" function
3627 */
3628 void
3629f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
3630{
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003631 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003632 RedrawingDisabled = 0;
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003633
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003634 ins_compl_check_keys(0, TRUE);
3635 rettv->vval.v_number = ins_compl_interrupted();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01003636
3637 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003638}
3639
3640/*
glepnirbcd59952025-04-24 21:48:35 +02003641 * Add match item to the return list.
3642 * Returns FAIL if out of memory, OK otherwise.
3643 */
3644 static int
3645add_match_to_list(
3646 typval_T *rettv,
3647 char_u *str,
3648 int len,
3649 int pos)
3650{
3651 list_T *match;
3652 int ret;
3653
3654 match = list_alloc();
3655 if (match == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02003656 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003657
3658 if ((ret = list_append_number(match, pos + 1)) == FAIL
3659 || (ret = list_append_string(match, str, len)) == FAIL
3660 || (ret = list_append_list(rettv->vval.v_list, match)) == FAIL)
3661 {
Hirohito Higashi355db992025-04-28 18:07:02 +02003662 vim_free(match);
3663 return FAIL;
glepnirbcd59952025-04-24 21:48:35 +02003664 }
3665
3666 return OK;
3667}
3668
3669/*
3670 * "complete_match()" function
3671 */
3672 void
3673f_complete_match(typval_T *argvars, typval_T *rettv)
3674{
3675 linenr_T lnum;
3676 colnr_T col;
3677 char_u *line = NULL;
3678 char_u *ise = NULL;
3679 regmatch_T regmatch;
3680 char_u *before_cursor = NULL;
3681 char_u *cur_end = NULL;
glepnirbcd59952025-04-24 21:48:35 +02003682 int bytepos = 0;
3683 char_u part[MAXPATHL];
3684 int ret;
3685
3686 if (rettv_list_alloc(rettv) == FAIL)
3687 return;
3688
3689 ise = curbuf->b_p_ise[0] != NUL ? curbuf->b_p_ise : p_ise;
3690
3691 if (argvars[0].v_type == VAR_UNKNOWN)
3692 {
3693 lnum = curwin->w_cursor.lnum;
3694 col = curwin->w_cursor.col;
3695 }
3696 else if (argvars[1].v_type == VAR_UNKNOWN)
3697 {
3698 emsg(_(e_invalid_argument));
3699 return;
3700 }
3701 else
3702 {
3703 lnum = (linenr_T)tv_get_number(&argvars[0]);
3704 col = (colnr_T)tv_get_number(&argvars[1]);
3705 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
3706 {
3707 semsg(_(e_invalid_line_number_nr), lnum);
3708 return;
3709 }
3710 if (col < 1 || col > ml_get_buf_len(curbuf, lnum))
3711 {
3712 semsg(_(e_invalid_column_number_nr), col + 1);
3713 return;
3714 }
3715 }
3716
3717 line = ml_get_buf(curbuf, lnum, FALSE);
3718 if (line == NULL)
3719 return;
3720
3721 before_cursor = vim_strnsave(line, col);
3722 if (before_cursor == NULL)
3723 return;
3724
3725 if (ise == NULL || *ise == NUL)
3726 {
3727 regmatch.regprog = vim_regcomp((char_u *)"\\k\\+$", RE_MAGIC);
3728 if (regmatch.regprog != NULL)
3729 {
3730 if (vim_regexec_nl(&regmatch, before_cursor, (colnr_T)0))
3731 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003732 char_u *trig = vim_strnsave(regmatch.startp[0],
glepnirbcd59952025-04-24 21:48:35 +02003733 regmatch.endp[0] - regmatch.startp[0]);
3734 if (trig == NULL)
3735 {
3736 vim_free(before_cursor);
Christian Brabandt3accf042025-04-25 19:01:06 +02003737 vim_regfree(regmatch.regprog);
glepnirbcd59952025-04-24 21:48:35 +02003738 return;
3739 }
3740
Christian Brabandt3accf042025-04-25 19:01:06 +02003741 bytepos = (int)(regmatch.startp[0] - before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003742 ret = add_match_to_list(rettv, trig, -1, bytepos);
3743 vim_free(trig);
3744 if (ret == FAIL)
3745 {
Christian Brabandt3accf042025-04-25 19:01:06 +02003746 vim_free(before_cursor);
glepnirbcd59952025-04-24 21:48:35 +02003747 vim_regfree(regmatch.regprog);
3748 return;
3749 }
3750 }
3751 vim_regfree(regmatch.regprog);
3752 }
3753 }
3754 else
3755 {
glepnir08db2f42025-05-14 20:26:19 +02003756 char_u *p = ise;
3757 char_u *p_space = NULL;
3758
glepnirbcd59952025-04-24 21:48:35 +02003759 cur_end = before_cursor + (int)STRLEN(before_cursor);
3760
3761 while (*p != NUL)
3762 {
glepnir8d0e42b2025-05-12 20:28:28 +02003763 int len = 0;
glepnir08db2f42025-05-14 20:26:19 +02003764 if (p_space)
glepnir8d0e42b2025-05-12 20:28:28 +02003765 {
glepnir08db2f42025-05-14 20:26:19 +02003766 len = p - p_space - 1;
3767 memcpy(part, p_space + 1, len);
3768 p_space = NULL;
glepnir8d0e42b2025-05-12 20:28:28 +02003769 }
3770 else
glepnir08db2f42025-05-14 20:26:19 +02003771 {
3772 char_u *next_comma = vim_strchr((*p == ',') ? p + 1 : p, ',');
3773 if (next_comma && *(next_comma + 1) == ' ')
3774 p_space = next_comma;
3775
glepnir8d0e42b2025-05-12 20:28:28 +02003776 len = copy_option_part(&p, part, MAXPATHL, ",");
glepnir08db2f42025-05-14 20:26:19 +02003777 }
glepnirbcd59952025-04-24 21:48:35 +02003778
3779 if (len > 0 && len <= col)
3780 {
3781 if (STRNCMP(cur_end - len, part, len) == 0)
3782 {
3783 bytepos = col - len;
3784 if (add_match_to_list(rettv, part, len, bytepos) == FAIL)
3785 {
3786 vim_free(before_cursor);
3787 return;
3788 }
3789 }
3790 }
3791 }
3792 }
3793
3794 vim_free(before_cursor);
3795}
3796
3797/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003798 * Return Insert completion mode name string
3799 */
3800 static char_u *
3801ins_compl_mode(void)
3802{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003803 if (ctrl_x_mode_not_defined_yet() || ctrl_x_mode_scroll() || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003804 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
3805
3806 return (char_u *)"";
3807}
3808
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00003809/*
3810 * Assign the sequence number to all the completion matches which don't have
3811 * one assigned yet.
3812 */
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003813 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00003814ins_compl_update_sequence_numbers(void)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003815{
3816 int number = 0;
3817 compl_T *match;
3818
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003819 if (compl_dir_forward())
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003820 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003821 // Search backwards for the first valid (!= -1) number.
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003822 // This should normally succeed already at the first loop
3823 // cycle, so it's fast!
3824 for (match = compl_curr_match->cp_prev; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003825 && !is_first_match(match); match = match->cp_prev)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003826 if (match->cp_number != -1)
3827 {
3828 number = match->cp_number;
3829 break;
3830 }
3831 if (match != NULL)
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003832 // go up and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003833 for (match = match->cp_next;
3834 match != NULL && match->cp_number == -1;
3835 match = match->cp_next)
3836 match->cp_number = ++number;
3837 }
3838 else // BACKWARD
3839 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003840 // Search forwards (upwards) for the first valid (!= -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003841 // number. This should normally succeed already at the
3842 // first loop cycle, so it's fast!
3843 for (match = compl_curr_match->cp_next; match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00003844 && !is_first_match(match); match = match->cp_next)
glepnir40891ba2025-02-10 22:18:00 +01003845 {
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003846 if (match->cp_number != -1)
3847 {
3848 number = match->cp_number;
3849 break;
3850 }
glepnir40891ba2025-02-10 22:18:00 +01003851 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003852 if (match != NULL)
glepnir40891ba2025-02-10 22:18:00 +01003853 {
Bram Moolenaarf39d9e92023-04-22 22:54:40 +01003854 // go down and assign all numbers which are not assigned yet
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003855 for (match = match->cp_prev; match
3856 && match->cp_number == -1;
3857 match = match->cp_prev)
3858 match->cp_number = ++number;
glepnir40891ba2025-02-10 22:18:00 +01003859 }
Bram Moolenaarf9d51352020-10-26 19:22:42 +01003860 }
3861}
3862
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003863/*
glepnir037b0282025-01-16 14:37:44 +01003864 * Fill the dict of complete_info
3865 */
3866 static void
3867fill_complete_info_dict(dict_T *di, compl_T *match, int add_match)
3868{
3869 dict_add_string(di, "word", match->cp_str.string);
3870 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
3871 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
3872 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
3873 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
3874 if (add_match)
Hirohito Higashi355db992025-04-28 18:07:02 +02003875 dict_add_bool(di, "match", match->cp_in_match_array);
glepnir037b0282025-01-16 14:37:44 +01003876 if (match->cp_user_data.v_type == VAR_UNKNOWN)
Hirohito Higashi355db992025-04-28 18:07:02 +02003877 // Add an empty string for backwards compatibility
3878 dict_add_string(di, "user_data", (char_u *)"");
glepnir037b0282025-01-16 14:37:44 +01003879 else
Hirohito Higashi355db992025-04-28 18:07:02 +02003880 dict_add_tv(di, "user_data", &match->cp_user_data);
glepnir037b0282025-01-16 14:37:44 +01003881}
3882
3883/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003884 * Get complete information
3885 */
3886 static void
3887get_complete_info(list_T *what_list, dict_T *retdict)
3888{
3889 int ret = OK;
3890 listitem_T *item;
3891#define CI_WHAT_MODE 0x01
3892#define CI_WHAT_PUM_VISIBLE 0x02
3893#define CI_WHAT_ITEMS 0x04
3894#define CI_WHAT_SELECTED 0x08
glepnir037b0282025-01-16 14:37:44 +01003895#define CI_WHAT_COMPLETED 0x10
glepnird4088ed2024-12-31 10:55:22 +01003896#define CI_WHAT_MATCHES 0x20
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003897#define CI_WHAT_ALL 0xff
3898 int what_flag;
3899
3900 if (what_list == NULL)
glepnir037b0282025-01-16 14:37:44 +01003901 what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES | CI_WHAT_COMPLETED);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003902 else
3903 {
3904 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02003905 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02003906 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003907 {
3908 char_u *what = tv_get_string(&item->li_tv);
3909
3910 if (STRCMP(what, "mode") == 0)
3911 what_flag |= CI_WHAT_MODE;
3912 else if (STRCMP(what, "pum_visible") == 0)
3913 what_flag |= CI_WHAT_PUM_VISIBLE;
3914 else if (STRCMP(what, "items") == 0)
3915 what_flag |= CI_WHAT_ITEMS;
3916 else if (STRCMP(what, "selected") == 0)
3917 what_flag |= CI_WHAT_SELECTED;
glepnir037b0282025-01-16 14:37:44 +01003918 else if (STRCMP(what, "completed") == 0)
3919 what_flag |= CI_WHAT_COMPLETED;
glepnird4088ed2024-12-31 10:55:22 +01003920 else if (STRCMP(what, "matches") == 0)
3921 what_flag |= CI_WHAT_MATCHES;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003922 }
3923 }
3924
3925 if (ret == OK && (what_flag & CI_WHAT_MODE))
3926 ret = dict_add_string(retdict, "mode", ins_compl_mode());
3927
3928 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
3929 ret = dict_add_number(retdict, "pum_visible", pum_visible());
3930
glepnir037b0282025-01-16 14:37:44 +01003931 if (ret == OK && (what_flag & (CI_WHAT_ITEMS | CI_WHAT_SELECTED
3932 | CI_WHAT_MATCHES | CI_WHAT_COMPLETED)))
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003933 {
Christian Brabandt9eb236f2024-03-21 20:12:59 +01003934 list_T *li = NULL;
Girish Palya8950bf72024-03-20 20:07:29 +01003935 dict_T *di;
3936 compl_T *match;
3937 int selected_idx = -1;
glepnird4088ed2024-12-31 10:55:22 +01003938 int has_items = what_flag & CI_WHAT_ITEMS;
3939 int has_matches = what_flag & CI_WHAT_MATCHES;
glepnir037b0282025-01-16 14:37:44 +01003940 int has_completed = what_flag & CI_WHAT_COMPLETED;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003941
glepnird4088ed2024-12-31 10:55:22 +01003942 if (has_items || has_matches)
Girish Palya8950bf72024-03-20 20:07:29 +01003943 {
3944 li = list_alloc();
3945 if (li == NULL)
3946 return;
glepnird4088ed2024-12-31 10:55:22 +01003947 ret = dict_add_list(retdict, (has_matches && !has_items)
3948 ? "matches" : "items", li);
Girish Palya8950bf72024-03-20 20:07:29 +01003949 }
3950 if (ret == OK && what_flag & CI_WHAT_SELECTED)
3951 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
3952 ins_compl_update_sequence_numbers();
3953 if (ret == OK && compl_first_match != NULL)
3954 {
3955 int list_idx = 0;
3956 match = compl_first_match;
3957 do
3958 {
3959 if (!match_at_original_text(match))
3960 {
glepnird4088ed2024-12-31 10:55:22 +01003961 if (has_items
3962 || (has_matches && match->cp_in_match_array))
Girish Palya8950bf72024-03-20 20:07:29 +01003963 {
3964 di = dict_alloc();
3965 if (di == NULL)
3966 return;
3967 ret = list_append_dict(li, di);
3968 if (ret != OK)
3969 return;
glepnir037b0282025-01-16 14:37:44 +01003970 fill_complete_info_dict(di, match, has_matches && has_items);
Girish Palya8950bf72024-03-20 20:07:29 +01003971 }
glepnird4088ed2024-12-31 10:55:22 +01003972 if (compl_curr_match != NULL
3973 && compl_curr_match->cp_number == match->cp_number)
Girish Palya8950bf72024-03-20 20:07:29 +01003974 selected_idx = list_idx;
Girish Palya8cd42a52025-06-05 21:04:29 +02003975 if (match->cp_in_match_array)
Girish Palya0ac1eb32025-04-16 20:18:33 +02003976 list_idx += 1;
Girish Palya8950bf72024-03-20 20:07:29 +01003977 }
3978 match = match->cp_next;
3979 }
3980 while (match != NULL && !is_first_match(match));
3981 }
3982 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
3983 ret = dict_add_number(retdict, "selected", selected_idx);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003984
glepnir037b0282025-01-16 14:37:44 +01003985 if (ret == OK && selected_idx != -1 && has_completed)
3986 {
3987 di = dict_alloc();
3988 if (di == NULL)
3989 return;
3990 fill_complete_info_dict(di, compl_curr_match, FALSE);
3991 ret = dict_add_dict(retdict, "completed", di);
3992 }
Yegappan Lakshmanan6b085b92022-09-04 12:47:21 +01003993 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003994}
3995
3996/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02003997 * "complete_info()" function
3998 */
3999 void
4000f_complete_info(typval_T *argvars, typval_T *rettv)
4001{
4002 list_T *what_list = NULL;
4003
Bram Moolenaar93a10962022-06-16 11:42:09 +01004004 if (rettv_dict_alloc(rettv) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004005 return;
4006
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02004007 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
4008 return;
4009
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004010 if (argvars[0].v_type != VAR_UNKNOWN)
4011 {
Bram Moolenaard83392a2022-09-01 12:22:46 +01004012 if (check_for_list_arg(argvars, 0) == FAIL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004013 return;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02004014 what_list = argvars[0].vval.v_list;
4015 }
4016 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004017}
4018#endif
4019
4020/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01004021 * Returns TRUE when using a user-defined function for thesaurus completion.
4022 */
4023 static int
4024thesaurus_func_complete(int type UNUSED)
4025{
4026#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01004027 return type == CTRL_X_THESAURUS
4028 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01004029#else
4030 return FALSE;
4031#endif
4032}
4033
4034/*
Girish Palya7c621052025-05-26 19:41:59 +02004035 * Check if 'cpt' list index can be advanced to the next completion source.
4036 */
4037 static int
4038may_advance_cpt_index(char_u *cpt)
4039{
4040 char_u *p = cpt;
4041
Girish Palya98c29db2025-06-01 19:40:00 +02004042 if (cpt_sources_index == -1)
4043 return FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004044 while (*p == ',' || *p == ' ') // Skip delimiters
4045 p++;
4046 return (*p != NUL);
4047}
4048
4049/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004050 * Return value of process_next_cpt_value()
4051 */
4052enum
4053{
4054 INS_COMPL_CPT_OK = 1,
4055 INS_COMPL_CPT_CONT,
4056 INS_COMPL_CPT_END
4057};
4058
4059/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004060 * state information used for getting the next set of insert completion
4061 * matches.
4062 */
4063typedef struct
4064{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004065 char_u *e_cpt_copy; // copy of 'complete'
4066 char_u *e_cpt; // current entry in "e_cpt_copy"
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004067 buf_T *ins_buf; // buffer being scanned
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004068 pos_T *cur_match_pos; // current match position
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004069 pos_T prev_match_pos; // previous match position
4070 int set_match_pos; // save first_match_pos/last_match_pos
4071 pos_T first_match_pos; // first match position
4072 pos_T last_match_pos; // last match position
4073 int found_all; // found all matches of a certain type.
4074 char_u *dict; // dictionary file to search
4075 int dict_f; // "dict" is an exact file name or not
Girish Palyacbe53192025-04-14 22:13:15 +02004076 callback_T *func_cb; // callback of function in 'cpt' option
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004077} ins_compl_next_state_T;
4078
4079/*
4080 * Process the next 'complete' option value in st->e_cpt.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004081 *
4082 * If successful, the arguments are set as below:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004083 * st->cpt - pointer to the next option value in "st->cpt"
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004084 * compl_type_arg - type of insert mode completion to use
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004085 * st->found_all - all matches of this type are found
4086 * st->ins_buf - search for completions in this buffer
4087 * st->first_match_pos - position of the first completion match
4088 * st->last_match_pos - position of the last completion match
4089 * st->set_match_pos - TRUE if the first match position should be saved to
Bram Moolenaar6ed545e2022-05-09 20:09:23 +01004090 * avoid loops after the search wraps around.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004091 * st->dict - name of the dictionary or thesaurus file to search
4092 * st->dict_f - flag specifying whether "dict" is an exact file name or not
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004093 *
4094 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00004095 * Returns INS_COMPL_CPT_CONT to skip the current completion source matching
4096 * the "st->e_cpt" option value and process the next matching source.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004097 * Returns INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed.
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004098 */
4099 static int
4100process_next_cpt_value(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004101 ins_compl_next_state_T *st,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004102 int *compl_type_arg,
glepnir8159fb12024-07-17 20:32:54 +02004103 pos_T *start_match_pos,
Girish Palya7c621052025-05-26 19:41:59 +02004104 int fuzzy_collect,
4105 int *advance_cpt_idx)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004106{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004107 int compl_type = -1;
4108 int status = INS_COMPL_CPT_OK;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004109
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004110 st->found_all = FALSE;
Girish Palya7c621052025-05-26 19:41:59 +02004111 *advance_cpt_idx = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004112
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004113 while (*st->e_cpt == ',' || *st->e_cpt == ' ')
4114 st->e_cpt++;
4115
4116 if (*st->e_cpt == '.' && !curbuf->b_scanned)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004117 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004118 st->ins_buf = curbuf;
4119 st->first_match_pos = *start_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004120 // Move the cursor back one character so that ^N can match the
4121 // word immediately after the cursor.
glepnir53b14572025-03-12 21:28:39 +01004122 if (ctrl_x_mode_normal() && (!fuzzy_collect && dec(&st->first_match_pos) < 0))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004123 {
4124 // Move the cursor to after the last character in the
4125 // buffer, so that word at start of buffer is found
4126 // correctly.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004127 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count;
zeertzjq94b7c322024-03-12 21:50:32 +01004128 st->first_match_pos.col = ml_get_len(st->first_match_pos.lnum);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004129 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004130 st->last_match_pos = st->first_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004131 compl_type = 0;
4132
4133 // Remember the first match so that the loop stops when we
4134 // wrap and come back there a second time.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004135 st->set_match_pos = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004136 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004137 else if (vim_strchr((char_u *)"buwU", *st->e_cpt) != NULL
Bram Moolenaar0ff01832022-09-24 19:20:30 +01004138 && (st->ins_buf = ins_compl_next_buf(
4139 st->ins_buf, *st->e_cpt)) != curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004140 {
4141 // Scan a buffer, but not the current one.
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004142 if (st->ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004143 {
4144 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004145 st->first_match_pos.col = st->last_match_pos.col = 0;
4146 st->first_match_pos.lnum = st->ins_buf->b_ml.ml_line_count + 1;
4147 st->last_match_pos.lnum = 0;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004148 compl_type = 0;
4149 }
4150 else // unloaded buffer, scan like dictionary
4151 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004152 st->found_all = TRUE;
4153 if (st->ins_buf->b_fname == NULL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004154 {
4155 status = INS_COMPL_CPT_CONT;
4156 goto done;
4157 }
4158 compl_type = CTRL_X_DICTIONARY;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004159 st->dict = st->ins_buf->b_fname;
4160 st->dict_f = DICT_EXACT;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004161 }
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004162 if (!shortmess(SHM_COMPLETIONSCAN))
4163 {
4164 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4165 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
4166 st->ins_buf->b_fname == NULL
4167 ? buf_spname(st->ins_buf)
4168 : st->ins_buf->b_sfname == NULL
4169 ? st->ins_buf->b_fname
4170 : st->ins_buf->b_sfname);
4171 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4172 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004173 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004174 else if (*st->e_cpt == NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004175 status = INS_COMPL_CPT_END;
4176 else
4177 {
4178 if (ctrl_x_mode_line_or_eval())
4179 compl_type = -1;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004180 else if (*st->e_cpt == 'k' || *st->e_cpt == 's')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004181 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004182 if (*st->e_cpt == 'k')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004183 compl_type = CTRL_X_DICTIONARY;
4184 else
4185 compl_type = CTRL_X_THESAURUS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004186 if (*++st->e_cpt != ',' && *st->e_cpt != NUL)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004187 {
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004188 st->dict = st->e_cpt;
4189 st->dict_f = DICT_FIRST;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004190 }
4191 }
Girish Palyacbe53192025-04-14 22:13:15 +02004192#ifdef FEAT_COMPL_FUNC
Girish Palya14f6da52025-05-26 19:04:25 +02004193 else if (*st->e_cpt == 'F' || *st->e_cpt == 'o')
Girish Palyacbe53192025-04-14 22:13:15 +02004194 {
4195 compl_type = CTRL_X_FUNCTION;
Girish Palya98c29db2025-06-01 19:40:00 +02004196 st->func_cb = get_callback_if_cpt_func(st->e_cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02004197 if (!st->func_cb)
4198 compl_type = -1;
4199 }
4200#endif
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004201#ifdef FEAT_FIND_ID
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004202 else if (*st->e_cpt == 'i')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004203 compl_type = CTRL_X_PATH_PATTERNS;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004204 else if (*st->e_cpt == 'd')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004205 compl_type = CTRL_X_PATH_DEFINES;
4206#endif
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004207 else if (*st->e_cpt == ']' || *st->e_cpt == 't')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004208 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004209 compl_type = CTRL_X_TAGS;
=?UTF-8?q?Bj=C3=B6rn=20Linse?=91ccbad2022-10-13 12:51:13 +01004210 if (!shortmess(SHM_COMPLETIONSCAN))
4211 {
4212 msg_hist_off = TRUE; // reset in msg_trunc_attr()
4213 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
4214 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
4215 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004216 }
4217 else
4218 compl_type = -1;
4219
4220 // in any case e_cpt is advanced to the next entry
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004221 (void)copy_option_part(&st->e_cpt, IObuff, IOSIZE, ",");
Girish Palya7c621052025-05-26 19:41:59 +02004222 *advance_cpt_idx = may_advance_cpt_index(st->e_cpt);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004223
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004224 st->found_all = TRUE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004225 if (compl_type == -1)
4226 status = INS_COMPL_CPT_CONT;
4227 }
4228
4229done:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004230 *compl_type_arg = compl_type;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004231 return status;
4232}
4233
4234#ifdef FEAT_FIND_ID
4235/*
4236 * Get the next set of identifiers or defines matching "compl_pattern" in
4237 * included files.
4238 */
4239 static void
4240get_next_include_file_completion(int compl_type)
4241{
John Marriott5e6ea922024-11-23 14:01:57 +01004242 find_pattern_in_path(compl_pattern.string, compl_direction,
4243 (int)compl_pattern.length, FALSE, FALSE,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004244 (compl_type == CTRL_X_PATH_DEFINES
4245 && !(compl_cont_status & CONT_SOL))
4246 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
Colin Kennedy21570352024-03-03 16:16:47 +01004247 (linenr_T)1, (linenr_T)MAXLNUM, FALSE);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004248}
4249#endif
4250
4251/*
4252 * Get the next set of words matching "compl_pattern" in dictionary or
4253 * thesaurus files.
4254 */
4255 static void
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004256get_next_dict_tsr_completion(int compl_type, char_u *dict, int dict_f)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004257{
4258#ifdef FEAT_COMPL_FUNC
4259 if (thesaurus_func_complete(compl_type))
Girish Palyacbe53192025-04-14 22:13:15 +02004260 expand_by_function(compl_type, compl_pattern.string, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004261 else
4262#endif
4263 ins_compl_dictionaries(
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004264 dict != NULL ? dict
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004265 : (compl_type == CTRL_X_THESAURUS
4266 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
4267 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
John Marriott5e6ea922024-11-23 14:01:57 +01004268 compl_pattern.string,
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004269 dict != NULL ? dict_f : 0,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004270 compl_type == CTRL_X_THESAURUS);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004271}
4272
4273/*
4274 * Get the next set of tag names matching "compl_pattern".
4275 */
4276 static void
4277get_next_tag_completion(void)
4278{
4279 int save_p_ic;
4280 char_u **matches;
4281 int num_matches;
4282
4283 // set p_ic according to p_ic, p_scs and pat for find_tags().
4284 save_p_ic = p_ic;
John Marriott5e6ea922024-11-23 14:01:57 +01004285 p_ic = ignorecase(compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004286
4287 // Find up to TAG_MANY matches. Avoids that an enormous number
4288 // of matches is found when compl_pattern is empty
4289 g_tag_at_cursor = TRUE;
John Marriott5e6ea922024-11-23 14:01:57 +01004290 if (find_tags(compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004291 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004292 | (ctrl_x_mode_not_default() ? TAG_VERBOSE : 0),
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004293 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
4294 ins_compl_add_matches(num_matches, matches, p_ic);
4295 g_tag_at_cursor = FALSE;
4296 p_ic = save_p_ic;
4297}
4298
4299/*
glepnir8159fb12024-07-17 20:32:54 +02004300 * Compare function for qsort
4301 */
glepnirf31cfa22025-03-06 21:59:13 +01004302 static int
4303compare_scores(const void *a, const void *b)
glepnir8159fb12024-07-17 20:32:54 +02004304{
4305 int idx_a = *(const int *)a;
4306 int idx_b = *(const int *)b;
4307 int score_a = compl_fuzzy_scores[idx_a];
4308 int score_b = compl_fuzzy_scores[idx_b];
zeertzjq58d70522024-08-31 17:05:39 +02004309 return score_a == score_b ? (idx_a == idx_b ? 0 : (idx_a < idx_b ? -1 : 1))
4310 : (score_a > score_b ? -1 : 1);
glepnir8159fb12024-07-17 20:32:54 +02004311}
4312
4313/*
glepnirf31cfa22025-03-06 21:59:13 +01004314 * insert prefix with redraw
4315 */
4316 static void
4317ins_compl_longest_insert(char_u *prefix)
4318{
4319 ins_compl_delete();
4320 ins_compl_insert_bytes(prefix + get_compl_len(), -1);
4321 ins_redraw(FALSE);
4322}
4323
4324/*
4325 * Calculate the longest common prefix among the best fuzzy matches
4326 * stored in compl_best_matches, and insert it as the longest.
4327 */
4328 static void
4329fuzzy_longest_match(void)
4330{
4331 char_u *prefix = NULL;
4332 int prefix_len = 0;
4333 int i = 0;
4334 int j = 0;
4335 char_u *match_str = NULL;
4336 char_u *prefix_ptr = NULL;
4337 char_u *match_ptr = NULL;
4338 char_u *leader = NULL;
4339 size_t leader_len = 0;
4340 compl_T *compl = NULL;
4341 int more_candidates = FALSE;
4342 compl_T *nn_compl = NULL;
4343
4344 if (compl_num_bests == 0)
Hirohito Higashi355db992025-04-28 18:07:02 +02004345 return;
glepnirf31cfa22025-03-06 21:59:13 +01004346
4347 nn_compl = compl_first_match->cp_next->cp_next;
4348 if (nn_compl && nn_compl != compl_first_match)
4349 more_candidates = TRUE;
4350
4351 compl = ctrl_x_mode_whole_line() ? compl_first_match
4352 : compl_first_match->cp_next;
4353 if (compl_num_bests == 1)
4354 {
4355 // no more candidates insert the match str
4356 if (!more_candidates)
4357 {
4358 ins_compl_longest_insert(compl->cp_str.string);
4359 compl_num_bests = 0;
4360 }
4361 compl_num_bests = 0;
4362 return;
4363 }
4364
4365 compl_best_matches = (compl_T **)alloc(compl_num_bests * sizeof(compl_T *));
4366 if (compl_best_matches == NULL)
Hirohito Higashi355db992025-04-28 18:07:02 +02004367 return;
glepnirf31cfa22025-03-06 21:59:13 +01004368 while (compl != NULL && i < compl_num_bests)
4369 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004370 compl_best_matches[i] = compl;
4371 compl = compl->cp_next;
4372 i++;
glepnirf31cfa22025-03-06 21:59:13 +01004373 }
4374
4375 prefix = compl_best_matches[0]->cp_str.string;
zeertzjq4422de62025-03-07 19:06:02 +01004376 prefix_len = (int)compl_best_matches[0]->cp_str.length;
glepnirf31cfa22025-03-06 21:59:13 +01004377
4378 for (i = 1; i < compl_num_bests; i++)
4379 {
4380 match_str = compl_best_matches[i]->cp_str.string;
Hirohito Higashi355db992025-04-28 18:07:02 +02004381 prefix_ptr = prefix;
4382 match_ptr = match_str;
4383 j = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004384
4385 while (j < prefix_len && *match_ptr != NUL && *prefix_ptr != NUL)
4386 {
4387 if (STRNCMP(prefix_ptr, match_ptr, mb_ptr2len(prefix_ptr)) != 0)
4388 break;
4389
4390 MB_PTR_ADV(prefix_ptr);
4391 MB_PTR_ADV(match_ptr);
4392 j++;
4393 }
4394
4395 if (j > 0)
4396 prefix_len = j;
4397 }
4398
4399 leader = ins_compl_leader();
zeertzjq4422de62025-03-07 19:06:02 +01004400 leader_len = ins_compl_leader_len();
glepnirf31cfa22025-03-06 21:59:13 +01004401
4402 // skip non-consecutive prefixes
zeertzjq4422de62025-03-07 19:06:02 +01004403 if (leader_len > 0 && STRNCMP(prefix, leader, leader_len) != 0)
glepnirf31cfa22025-03-06 21:59:13 +01004404 goto end;
4405
zeertzjq4422de62025-03-07 19:06:02 +01004406 prefix = vim_strnsave(prefix, prefix_len);
glepnirf31cfa22025-03-06 21:59:13 +01004407 if (prefix != NULL)
4408 {
4409 ins_compl_longest_insert(prefix);
4410 compl_cfc_longest_ins = TRUE;
4411 vim_free(prefix);
4412 }
4413
4414end:
4415 vim_free(compl_best_matches);
4416 compl_best_matches = NULL;
4417 compl_num_bests = 0;
4418}
4419
4420/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004421 * Get the next set of filename matching "compl_pattern".
4422 */
4423 static void
4424get_next_filename_completion(void)
4425{
4426 char_u **matches;
4427 int num_matches;
glepnir8159fb12024-07-17 20:32:54 +02004428 char_u *ptr;
4429 garray_T fuzzy_indices;
4430 int i;
4431 int score;
4432 char_u *leader = ins_compl_leader();
John Marriott5e6ea922024-11-23 14:01:57 +01004433 size_t leader_len = ins_compl_leader_len();;
glepnirf31cfa22025-03-06 21:59:13 +01004434 int in_fuzzy_collect = (cfc_has_mode() && leader_len > 0);
glepnir8159fb12024-07-17 20:32:54 +02004435 int *fuzzy_indices_data;
glepnir0be03e12024-07-19 16:45:05 +02004436 char_u *last_sep = NULL;
glepnirf31cfa22025-03-06 21:59:13 +01004437 int need_collect_bests = in_fuzzy_collect && compl_get_longest;
4438 int max_score = 0;
4439 int current_score = 0;
4440 int dir = compl_direction;
glepnir8159fb12024-07-17 20:32:54 +02004441
glepnirb9de1a02024-08-02 19:14:38 +02004442#ifdef BACKSLASH_IN_FILENAME
4443 char pathsep = (curbuf->b_p_csl[0] == 's') ?
4444 '/' : (curbuf->b_p_csl[0] == 'b') ? '\\' : PATHSEP;
4445#else
4446 char pathsep = PATHSEP;
4447#endif
4448
glepnirf31cfa22025-03-06 21:59:13 +01004449 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004450 {
glepnirb9de1a02024-08-02 19:14:38 +02004451#ifdef BACKSLASH_IN_FILENAME
4452 if (curbuf->b_p_csl[0] == 's')
4453 {
John Marriott5e6ea922024-11-23 14:01:57 +01004454 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004455 {
4456 if (leader[i] == '\\')
4457 leader[i] = '/';
4458 }
4459 }
4460 else if (curbuf->b_p_csl[0] == 'b')
4461 {
John Marriott5e6ea922024-11-23 14:01:57 +01004462 for (i = 0; i < (int)leader_len; i++)
glepnirb9de1a02024-08-02 19:14:38 +02004463 {
4464 if (leader[i] == '/')
4465 leader[i] = '\\';
4466 }
4467 }
4468#endif
4469 last_sep = vim_strrchr(leader, pathsep);
glepnir0be03e12024-07-19 16:45:05 +02004470 if (last_sep == NULL)
4471 {
4472 // No path separator or separator is the last character,
4473 // fuzzy match the whole leader
John Marriott5e6ea922024-11-23 14:01:57 +01004474 VIM_CLEAR_STRING(compl_pattern);
4475 compl_pattern.string = vim_strnsave((char_u *)"*", 1);
4476 if (compl_pattern.string == NULL)
4477 return;
4478 compl_pattern.length = 1;
glepnir0be03e12024-07-19 16:45:05 +02004479 }
4480 else if (*(last_sep + 1) == '\0')
glepnirf31cfa22025-03-06 21:59:13 +01004481 in_fuzzy_collect = FALSE;
glepnir0be03e12024-07-19 16:45:05 +02004482 else
4483 {
4484 // Split leader into path and file parts
4485 int path_len = last_sep - leader + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004486 char_u *path_with_wildcard;
4487
4488 path_with_wildcard = alloc(path_len + 2);
glepnir0be03e12024-07-19 16:45:05 +02004489 if (path_with_wildcard != NULL)
4490 {
John Marriott5e6ea922024-11-23 14:01:57 +01004491 vim_snprintf((char *)path_with_wildcard, path_len + 2, "%*.*s*", path_len, path_len, leader);
4492 VIM_CLEAR_STRING(compl_pattern);
4493 compl_pattern.string = path_with_wildcard;
4494 compl_pattern.length = path_len + 1;
glepnir0be03e12024-07-19 16:45:05 +02004495
4496 // Move leader to the file part
4497 leader = last_sep + 1;
John Marriott5e6ea922024-11-23 14:01:57 +01004498 leader_len -= path_len;
glepnir0be03e12024-07-19 16:45:05 +02004499 }
4500 }
glepnir8159fb12024-07-17 20:32:54 +02004501 }
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004502
John Marriott5e6ea922024-11-23 14:01:57 +01004503 if (expand_wildcards(1, &compl_pattern.string, &num_matches, &matches,
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004504 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
4505 return;
4506
4507 // May change home directory back to "~".
John Marriott5e6ea922024-11-23 14:01:57 +01004508 tilde_replace(compl_pattern.string, num_matches, matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004509#ifdef BACKSLASH_IN_FILENAME
4510 if (curbuf->b_p_csl[0] != NUL)
4511 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004512 for (i = 0; i < num_matches; ++i)
4513 {
glepnir8159fb12024-07-17 20:32:54 +02004514 ptr = matches[i];
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004515 while (*ptr != NUL)
4516 {
4517 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
4518 *ptr = '/';
4519 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
4520 *ptr = '\\';
4521 ptr += (*mb_ptr2len)(ptr);
4522 }
4523 }
4524 }
4525#endif
glepnir8159fb12024-07-17 20:32:54 +02004526
glepnirf31cfa22025-03-06 21:59:13 +01004527 if (in_fuzzy_collect)
glepnir8159fb12024-07-17 20:32:54 +02004528 {
4529 ga_init2(&fuzzy_indices, sizeof(int), 10);
4530 compl_fuzzy_scores = (int *)alloc(sizeof(int) * num_matches);
4531
4532 for (i = 0; i < num_matches; i++)
4533 {
4534 ptr = matches[i];
4535 score = fuzzy_match_str(ptr, leader);
4536 if (score > 0)
4537 {
4538 if (ga_grow(&fuzzy_indices, 1) == OK)
4539 {
4540 ((int *)fuzzy_indices.ga_data)[fuzzy_indices.ga_len] = i;
4541 compl_fuzzy_scores[i] = score;
4542 fuzzy_indices.ga_len++;
4543 }
4544 }
4545 }
4546
Christian Brabandt220474d2024-07-20 13:26:44 +02004547 // prevent qsort from deref NULL pointer
4548 if (fuzzy_indices.ga_len > 0)
4549 {
glepnirf31cfa22025-03-06 21:59:13 +01004550 char_u *match = NULL;
Christian Brabandt220474d2024-07-20 13:26:44 +02004551 fuzzy_indices_data = (int *)fuzzy_indices.ga_data;
4552 qsort(fuzzy_indices_data, fuzzy_indices.ga_len, sizeof(int), compare_scores);
glepnir8159fb12024-07-17 20:32:54 +02004553
Christian Brabandt220474d2024-07-20 13:26:44 +02004554 for (i = 0; i < fuzzy_indices.ga_len; ++i)
glepnirf31cfa22025-03-06 21:59:13 +01004555 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004556 match = matches[fuzzy_indices_data[i]];
glepnirf31cfa22025-03-06 21:59:13 +01004557 current_score = compl_fuzzy_scores[fuzzy_indices_data[i]];
4558 if (ins_compl_add(match, -1, NULL, NULL, NULL, dir,
Hirohito Higashi355db992025-04-28 18:07:02 +02004559 CP_FAST | ((p_fic || p_wic) ? CP_ICASE : 0),
4560 FALSE, NULL, current_score) == OK)
glepnirf31cfa22025-03-06 21:59:13 +01004561 dir = FORWARD;
4562
4563 if (need_collect_bests)
4564 {
4565 if (i == 0 || current_score == max_score)
4566 {
4567 compl_num_bests++;
4568 max_score = current_score;
4569 }
4570 }
4571 }
glepnir8159fb12024-07-17 20:32:54 +02004572
Christian Brabandt220474d2024-07-20 13:26:44 +02004573 FreeWild(num_matches, matches);
Christian Brabandt220474d2024-07-20 13:26:44 +02004574 }
glepnir6b6280c2024-07-27 16:25:45 +02004575 else if (leader_len > 0)
4576 {
4577 FreeWild(num_matches, matches);
4578 num_matches = 0;
4579 }
Christian Brabandt220474d2024-07-20 13:26:44 +02004580
glepnir8159fb12024-07-17 20:32:54 +02004581 vim_free(compl_fuzzy_scores);
4582 ga_clear(&fuzzy_indices);
glepnirf31cfa22025-03-06 21:59:13 +01004583
4584 if (compl_num_bests > 0 && compl_get_longest)
4585 fuzzy_longest_match();
4586 return;
glepnir8159fb12024-07-17 20:32:54 +02004587 }
4588
glepnir6b6280c2024-07-27 16:25:45 +02004589 if (num_matches > 0)
4590 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004591}
4592
4593/*
4594 * Get the next set of command-line completions matching "compl_pattern".
4595 */
4596 static void
Yegappan Lakshmanana23a11b2023-02-21 14:27:41 +00004597get_next_cmdline_completion(void)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004598{
4599 char_u **matches;
4600 int num_matches;
4601
John Marriott5e6ea922024-11-23 14:01:57 +01004602 if (expand_cmdline(&compl_xp, compl_pattern.string,
4603 (int)compl_pattern.length, &num_matches, &matches) == EXPAND_OK)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004604 ins_compl_add_matches(num_matches, matches, FALSE);
4605}
4606
4607/*
4608 * Get the next set of spell suggestions matching "compl_pattern".
4609 */
4610 static void
4611get_next_spell_completion(linenr_T lnum UNUSED)
4612{
4613#ifdef FEAT_SPELL
4614 char_u **matches;
4615 int num_matches;
4616
John Marriott5e6ea922024-11-23 14:01:57 +01004617 num_matches = expand_spelling(lnum, compl_pattern.string, &matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004618 if (num_matches > 0)
4619 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00004620 else
4621 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004622#endif
4623}
4624
4625/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004626 * Return the next word or line from buffer "ins_buf" at position
4627 * "cur_match_pos" for completion. The length of the match is set in "len".
4628 */
4629 static char_u *
zeertzjq440d4cb2023-03-02 17:51:32 +00004630ins_compl_get_next_word_or_line(
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004631 buf_T *ins_buf, // buffer being scanned
4632 pos_T *cur_match_pos, // current match position
4633 int *match_len,
4634 int *cont_s_ipos) // next ^X<> will set initial_pos
4635{
4636 char_u *ptr;
4637 int len;
4638
4639 *match_len = 0;
4640 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
4641 cur_match_pos->col;
John Marriott5e6ea922024-11-23 14:01:57 +01004642 len = (int)ml_get_buf_len(ins_buf, cur_match_pos->lnum) - cur_match_pos->col;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004643 if (ctrl_x_mode_line_or_eval())
4644 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004645 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004646 {
4647 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
4648 return NULL;
4649 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
John Marriott5e6ea922024-11-23 14:01:57 +01004650 len = ml_get_buf_len(ins_buf, cur_match_pos->lnum + 1);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004651 if (!p_paste)
John Marriott5e6ea922024-11-23 14:01:57 +01004652 {
4653 char_u *tmp_ptr = ptr;
4654
4655 ptr = skipwhite(tmp_ptr);
4656 len -= (int)(ptr - tmp_ptr);
4657 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004658 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004659 }
4660 else
4661 {
4662 char_u *tmp_ptr = ptr;
4663
John Marriott5e6ea922024-11-23 14:01:57 +01004664 if (compl_status_adding() && compl_length <= len)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004665 {
4666 tmp_ptr += compl_length;
4667 // Skip if already inside a word.
4668 if (vim_iswordp(tmp_ptr))
4669 return NULL;
4670 // Find start of next word.
4671 tmp_ptr = find_word_start(tmp_ptr);
4672 }
4673 // Find end of this word.
4674 tmp_ptr = find_word_end(tmp_ptr);
4675 len = (int)(tmp_ptr - ptr);
4676
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004677 if (compl_status_adding() && len == compl_length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004678 {
4679 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
4680 {
4681 // Try next line, if any. the new word will be
4682 // "join" as if the normal command "J" was used.
4683 // IOSIZE is always greater than
4684 // compl_length, so the next STRNCPY always
4685 // works -- Acevedo
4686 STRNCPY(IObuff, ptr, len);
4687 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
4688 tmp_ptr = ptr = skipwhite(ptr);
4689 // Find start of next word.
4690 tmp_ptr = find_word_start(tmp_ptr);
4691 // Find end of next word.
4692 tmp_ptr = find_word_end(tmp_ptr);
4693 if (tmp_ptr > ptr)
4694 {
4695 if (*ptr != ')' && IObuff[len - 1] != TAB)
4696 {
4697 if (IObuff[len - 1] != ' ')
4698 IObuff[len++] = ' ';
4699 // IObuf =~ "\k.* ", thus len >= 2
4700 if (p_js
4701 && (IObuff[len - 2] == '.'
4702 || (vim_strchr(p_cpo, CPO_JOINSP)
4703 == NULL
4704 && (IObuff[len - 2] == '?'
4705 || IObuff[len - 2] == '!'))))
4706 IObuff[len++] = ' ';
4707 }
4708 // copy as much as possible of the new word
4709 if (tmp_ptr - ptr >= IOSIZE - len)
4710 tmp_ptr = ptr + IOSIZE - len - 1;
4711 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
4712 len += (int)(tmp_ptr - ptr);
4713 *cont_s_ipos = TRUE;
4714 }
4715 IObuff[len] = NUL;
4716 ptr = IObuff;
4717 }
4718 if (len == compl_length)
4719 return NULL;
4720 }
4721 }
4722
4723 *match_len = len;
4724 return ptr;
4725}
4726
4727/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004728 * Get the next set of words matching "compl_pattern" for default completion(s)
4729 * (normal ^P/^N and ^X^L).
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004730 * Search for "compl_pattern" in the buffer "st->ins_buf" starting from the
4731 * position "st->start_pos" in the "compl_direction" direction. If
4732 * "st->set_match_pos" is TRUE, then set the "st->first_match_pos" and
4733 * "st->last_match_pos".
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004734 * Returns OK if a new next match is found, otherwise returns FAIL.
4735 */
4736 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004737get_next_default_completion(ins_compl_next_state_T *st, pos_T *start_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004738{
4739 int found_new_match = FAIL;
4740 int save_p_scs;
4741 int save_p_ws;
4742 int looped_around = FALSE;
glepnir8159fb12024-07-17 20:32:54 +02004743 char_u *ptr = NULL;
4744 int len = 0;
glepnirf31cfa22025-03-06 21:59:13 +01004745 int in_collect = (cfc_has_mode() && compl_length > 0);
glepnir8159fb12024-07-17 20:32:54 +02004746 char_u *leader = ins_compl_leader();
glepnirf31cfa22025-03-06 21:59:13 +01004747 int score = 0;
Girish Palyab1565882025-04-15 20:16:00 +02004748 int in_curbuf = st->ins_buf == curbuf;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004749
4750 // If 'infercase' is set, don't use 'smartcase' here
4751 save_p_scs = p_scs;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004752 if (st->ins_buf->b_p_inf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004753 p_scs = FALSE;
4754
4755 // Buffers other than curbuf are scanned from the beginning or the
4756 // end but never from the middle, thus setting nowrapscan in this
4757 // buffer is a good idea, on the other hand, we always set
4758 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
4759 save_p_ws = p_ws;
Girish Palyab1565882025-04-15 20:16:00 +02004760 if (!in_curbuf)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004761 p_ws = FALSE;
glepnirf31cfa22025-03-06 21:59:13 +01004762 else if (*st->e_cpt == '.')
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004763 p_ws = TRUE;
4764 looped_around = FALSE;
4765 for (;;)
4766 {
4767 int cont_s_ipos = FALSE;
4768
4769 ++msg_silent; // Don't want messages for wrapscan.
4770
glepnirf31cfa22025-03-06 21:59:13 +01004771 if (in_collect)
4772 {
Hirohito Higashi355db992025-04-28 18:07:02 +02004773 found_new_match = search_for_fuzzy_match(st->ins_buf,
glepnir8159fb12024-07-17 20:32:54 +02004774 st->cur_match_pos, leader, compl_direction,
glepnirf31cfa22025-03-06 21:59:13 +01004775 start_pos, &len, &ptr, &score);
4776 }
4777 // ctrl_x_mode_line_or_eval() || word-wise search that
4778 // has added a word that was at the beginning of the line
4779 else if (ctrl_x_mode_whole_line() || ctrl_x_mode_eval() || (compl_cont_status & CONT_SOL))
4780 found_new_match = search_for_exact_line(st->ins_buf,
4781 st->cur_match_pos, compl_direction, compl_pattern.string);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004782 else
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004783 found_new_match = searchit(NULL, st->ins_buf, st->cur_match_pos,
John Marriott5e6ea922024-11-23 14:01:57 +01004784 NULL, compl_direction, compl_pattern.string, (int)compl_pattern.length,
John Marriott8c85a2a2024-05-20 19:18:26 +02004785 1L, SEARCH_KEEP + SEARCH_NFMSG, RE_LAST, NULL);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004786 --msg_silent;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004787 if (!compl_started || st->set_match_pos)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004788 {
4789 // set "compl_started" even on fail
4790 compl_started = TRUE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004791 st->first_match_pos = *st->cur_match_pos;
4792 st->last_match_pos = *st->cur_match_pos;
4793 st->set_match_pos = FALSE;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004794 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004795 else if (st->first_match_pos.lnum == st->last_match_pos.lnum
4796 && st->first_match_pos.col == st->last_match_pos.col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004797 {
4798 found_new_match = FAIL;
4799 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004800 else if (compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004801 && (st->prev_match_pos.lnum > st->cur_match_pos->lnum
4802 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4803 && st->prev_match_pos.col >= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004804 {
4805 if (looped_around)
4806 found_new_match = FAIL;
4807 else
4808 looped_around = TRUE;
4809 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00004810 else if (!compl_dir_forward()
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004811 && (st->prev_match_pos.lnum < st->cur_match_pos->lnum
4812 || (st->prev_match_pos.lnum == st->cur_match_pos->lnum
4813 && st->prev_match_pos.col <= st->cur_match_pos->col)))
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004814 {
4815 if (looped_around)
4816 found_new_match = FAIL;
4817 else
4818 looped_around = TRUE;
4819 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004820 st->prev_match_pos = *st->cur_match_pos;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004821 if (found_new_match == FAIL)
4822 break;
4823
4824 // when ADDING, the text before the cursor matches, skip it
Girish Palyab1565882025-04-15 20:16:00 +02004825 if (compl_status_adding() && in_curbuf
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00004826 && start_pos->lnum == st->cur_match_pos->lnum
4827 && start_pos->col == st->cur_match_pos->col)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004828 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004829
glepnirf31cfa22025-03-06 21:59:13 +01004830 if (!in_collect)
glepnir8159fb12024-07-17 20:32:54 +02004831 ptr = ins_compl_get_next_word_or_line(st->ins_buf, st->cur_match_pos,
4832 &len, &cont_s_ipos);
glepnirbfb4eea2025-01-31 15:28:29 +01004833 if (ptr == NULL || (ins_compl_has_preinsert() && STRCMP(ptr, compl_pattern.string) == 0))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004834 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004835
Girish Palyab1565882025-04-15 20:16:00 +02004836 if (is_nearest_active() && in_curbuf)
4837 {
4838 score = st->cur_match_pos->lnum - curwin->w_cursor.lnum;
4839 if (score < 0)
4840 score = -score;
4841 score++;
4842 }
4843
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004844 if (ins_compl_add_infercase(ptr, len, p_ic,
Girish Palyab1565882025-04-15 20:16:00 +02004845 in_curbuf ? NULL : st->ins_buf->b_sfname,
glepnirf31cfa22025-03-06 21:59:13 +01004846 0, cont_s_ipos, score) != NOTDONE)
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004847 {
glepnirf31cfa22025-03-06 21:59:13 +01004848 if (in_collect && score == compl_first_match->cp_next->cp_score)
4849 compl_num_bests++;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004850 found_new_match = OK;
4851 break;
4852 }
4853 }
4854 p_scs = save_p_scs;
4855 p_ws = save_p_ws;
4856
4857 return found_new_match;
4858}
4859
Girish Palyacbe53192025-04-14 22:13:15 +02004860#ifdef FEAT_COMPL_FUNC
Girish Palya98c29db2025-06-01 19:40:00 +02004861/*
4862 * Return the callback function associated with "p" if it points to a
4863 * userfunc.
4864 */
Girish Palyacbe53192025-04-14 22:13:15 +02004865 static callback_T *
Girish Palya98c29db2025-06-01 19:40:00 +02004866get_callback_if_cpt_func(char_u *p)
Girish Palyacbe53192025-04-14 22:13:15 +02004867{
4868 static callback_T cb;
4869 char_u buf[LSIZE];
4870 int slen;
4871
Girish Palya98c29db2025-06-01 19:40:00 +02004872 if (*p == 'o')
4873 return &curbuf->b_ofu_cb;
4874 if (*p == 'F')
4875 {
4876 if (*++p != ',' && *p != NUL)
4877 {
4878 free_callback(&cb);
4879 slen = copy_option_part(&p, buf, LSIZE, ",");
4880 if (slen > 0 && option_set_callback_func(buf, &cb))
4881 return &cb;
4882 return NULL;
4883 }
4884 else
4885 return &curbuf->b_cfu_cb;
4886 }
Girish Palyacbe53192025-04-14 22:13:15 +02004887 return NULL;
4888}
Girish Palyacbe53192025-04-14 22:13:15 +02004889#endif
4890
4891/*
glepnir05460682025-05-26 18:23:27 +02004892 * Get completion matches from register contents.
4893 * Extracts words from all available registers and adds them to the completion list.
4894 */
4895 static void
4896get_register_completion(void)
4897{
4898 int dir = compl_direction;
4899 yankreg_T *reg = NULL;
4900 void *reg_ptr = NULL;
glepnir86d46a72025-06-03 21:04:44 +02004901 int adding_mode = compl_status_adding();
glepnir05460682025-05-26 18:23:27 +02004902
4903 for (int i = 0; i < NUM_REGISTERS; i++)
4904 {
4905 int regname = 0;
glepnir05460682025-05-26 18:23:27 +02004906 if (i == 0)
4907 regname = '"'; // unnamed register
4908 else if (i < 10)
4909 regname = '0' + i;
4910 else if (i == DELETION_REGISTER)
4911 regname = '-';
4912#ifdef FEAT_CLIPBOARD
4913 else if (i == STAR_REGISTER)
4914 regname = '*';
4915 else if (i == PLUS_REGISTER)
4916 regname = '+';
4917#endif
4918 else
4919 regname = 'a' + i - 10;
4920
4921 // Skip invalid or black hole register
4922 if (!valid_yank_reg(regname, FALSE) || regname == '_')
4923 continue;
4924
4925 reg_ptr = get_register(regname, FALSE);
4926 if (reg_ptr == NULL)
4927 continue;
4928
4929 reg = (yankreg_T *)reg_ptr;
4930
glepnir86d46a72025-06-03 21:04:44 +02004931 for (int j = 0; j < reg->y_size; j++)
glepnir05460682025-05-26 18:23:27 +02004932 {
glepnir86d46a72025-06-03 21:04:44 +02004933 char_u *str = reg->y_array[j].string;
4934 if (str == NULL)
4935 continue;
glepnir05460682025-05-26 18:23:27 +02004936
glepnir86d46a72025-06-03 21:04:44 +02004937 if (adding_mode)
4938 {
glepnird5fdfa52025-06-02 19:45:41 +02004939 int str_len = (int)STRLEN(str);
4940 if (str_len == 0)
4941 continue;
glepnir05460682025-05-26 18:23:27 +02004942
glepnird5fdfa52025-06-02 19:45:41 +02004943 if (!compl_orig_text.string
4944 || (p_ic ? STRNICMP(str, compl_orig_text.string,
4945 compl_orig_text.length) == 0
4946 : STRNCMP(str, compl_orig_text.string,
4947 compl_orig_text.length) == 0))
glepnir05460682025-05-26 18:23:27 +02004948 {
glepnir86d46a72025-06-03 21:04:44 +02004949 if (ins_compl_add_infercase(str, str_len, p_ic, NULL,
4950 dir, FALSE, 0) == OK)
glepnir05460682025-05-26 18:23:27 +02004951 dir = FORWARD;
4952 }
glepnird5fdfa52025-06-02 19:45:41 +02004953 }
glepnir86d46a72025-06-03 21:04:44 +02004954 else
glepnird5fdfa52025-06-02 19:45:41 +02004955 {
glepnird5fdfa52025-06-02 19:45:41 +02004956 // Calculate the safe end of string to avoid null byte issues
4957 char_u *str_end = str + STRLEN(str);
4958 char_u *p = str;
4959
4960 // Safely iterate through the string
4961 while (p < str_end && *p != NUL)
4962 {
4963 char_u *old_p = p;
4964 p = find_word_start(p);
4965 if (p >= str_end || *p == NUL)
4966 break;
4967
4968 char_u *word_end = find_word_end(p);
4969
4970 if (word_end <= p)
4971 {
4972 if (has_mbyte)
4973 word_end = p + (*mb_ptr2len)(p);
4974 else
4975 word_end = p + 1;
4976 }
4977
4978 if (word_end > str_end)
4979 word_end = str_end;
4980
4981 int len = (int)(word_end - p);
4982 if (len > 0 && (!compl_orig_text.string
4983 || (p_ic ? STRNICMP(p, compl_orig_text.string,
4984 compl_orig_text.length) == 0
4985 : STRNCMP(p, compl_orig_text.string,
4986 compl_orig_text.length) == 0)))
4987 {
4988 if (ins_compl_add_infercase(p, len, p_ic, NULL,
4989 dir, FALSE, 0) == OK)
4990 dir = FORWARD;
4991 }
4992
4993 p = word_end;
4994
4995 if (p <= old_p)
4996 {
4997 p = old_p + 1;
4998 if (has_mbyte && p < str_end)
4999 p = old_p + (*mb_ptr2len)(old_p);
5000 }
5001 }
glepnir05460682025-05-26 18:23:27 +02005002 }
5003 }
5004
5005 // Free the register copy
5006 put_register(regname, reg_ptr);
5007 }
5008}
5009
5010/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005011 * get the next set of completion matches for "type".
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005012 * Returns TRUE if a new match is found. Otherwise returns FALSE.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005013 */
5014 static int
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005015get_next_completion_match(int type, ins_compl_next_state_T *st, pos_T *ini)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005016{
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005017 int found_new_match = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005018
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005019 switch (type)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005020 {
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005021 case -1:
5022 break;
5023#ifdef FEAT_FIND_ID
5024 case CTRL_X_PATH_PATTERNS:
5025 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005026 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005027 break;
5028#endif
5029
5030 case CTRL_X_DICTIONARY:
5031 case CTRL_X_THESAURUS:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005032 get_next_dict_tsr_completion(type, st->dict, st->dict_f);
5033 st->dict = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005034 break;
5035
5036 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005037 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005038 break;
5039
5040 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005041 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005042 break;
5043
5044 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02005045 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00005046 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005047 break;
5048
5049#ifdef FEAT_COMPL_FUNC
5050 case CTRL_X_FUNCTION:
Girish Palyacbe53192025-04-14 22:13:15 +02005051 if (ctrl_x_mode_normal()) // Invoked by a func in 'cpt' option
Girish Palyaba11e782025-07-05 16:11:44 +02005052 get_cpt_func_completion_matches(st->func_cb);
Girish Palyacbe53192025-04-14 22:13:15 +02005053 else
5054 expand_by_function(type, compl_pattern.string, NULL);
5055 break;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005056 case CTRL_X_OMNI:
Girish Palyacbe53192025-04-14 22:13:15 +02005057 expand_by_function(type, compl_pattern.string, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005058 break;
5059#endif
5060
5061 case CTRL_X_SPELL:
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005062 get_next_spell_completion(st->first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005063 break;
5064
glepnir05460682025-05-26 18:23:27 +02005065 case CTRL_X_REGISTER:
5066 get_register_completion();
5067 break;
5068
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005069 default: // normal ^P/^N and ^X^L
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005070 found_new_match = get_next_default_completion(st, ini);
5071 if (found_new_match == FAIL && st->ins_buf == curbuf)
5072 st->found_all = TRUE;
5073 }
5074
5075 // check if compl_curr_match has changed, (e.g. other type of
5076 // expansion added something)
5077 if (type != 0 && compl_curr_match != compl_old_match)
5078 found_new_match = OK;
5079
5080 return found_new_match;
5081}
5082
5083/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005084 * Strips carets followed by numbers. This suffix typically represents the
5085 * max_matches setting.
5086 */
5087 static void
5088strip_caret_numbers_in_place(char_u *str)
5089{
5090 char_u *read = str, *write = str, *p;
5091
5092 if (str == NULL)
5093 return;
5094
5095 while (*read)
5096 {
5097 if (*read == '^')
5098 {
5099 p = read + 1;
5100 while (vim_isdigit(*p))
5101 p++;
5102 if ((*p == ',' || *p == '\0') && p != read + 1)
5103 {
5104 read = p;
5105 continue;
5106 }
5107 else
5108 *write++ = *read++;
5109 }
5110 else
5111 *write++ = *read++;
5112 }
5113 *write = '\0';
5114}
5115
5116/*
Girish Palya98c29db2025-06-01 19:40:00 +02005117 * Call functions specified in the 'cpt' option with findstart=1,
5118 * and retrieve the startcol.
5119 */
5120 static void
5121prepare_cpt_compl_funcs(void)
5122{
5123#ifdef FEAT_COMPL_FUNC
5124 char_u *cpt;
5125 char_u *p;
5126 callback_T *cb = NULL;
5127 int idx = 0;
5128 int startcol;
5129
5130 // Make a copy of 'cpt' in case the buffer gets wiped out
5131 cpt = vim_strsave(curbuf->b_p_cpt);
5132 strip_caret_numbers_in_place(cpt);
5133
5134 // Re-insert the text removed by ins_compl_delete().
5135 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
5136
5137 for (p = cpt; *p;)
5138 {
5139 while (*p == ',' || *p == ' ') // Skip delimiters
5140 p++;
Girish Palyaba11e782025-07-05 16:11:44 +02005141 if (*p == NUL)
5142 break;
5143
Girish Palya98c29db2025-06-01 19:40:00 +02005144 cb = get_callback_if_cpt_func(p);
5145 if (cb)
5146 {
5147 if (get_userdefined_compl_info(curwin->w_cursor.col, cb, &startcol)
5148 == FAIL)
5149 {
5150 if (startcol == -3)
5151 cpt_sources_array[idx].cs_refresh_always = FALSE;
5152 else
5153 startcol = -2;
5154 }
5155 cpt_sources_array[idx].cs_startcol = startcol;
5156 }
Girish Palyaba11e782025-07-05 16:11:44 +02005157 else
5158 cpt_sources_array[idx].cs_startcol = STARTCOL_NONE;
5159
Girish Palya98c29db2025-06-01 19:40:00 +02005160 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
5161 idx++;
5162 }
5163
5164 // Undo insertion
5165 ins_compl_delete();
5166
5167 vim_free(cpt);
5168#endif
5169}
5170
5171/*
Girish Palya7c621052025-05-26 19:41:59 +02005172 * Safely advance the cpt_sources_index by one.
5173 */
5174 static int
5175advance_cpt_sources_index_safe(void)
5176{
5177 if (cpt_sources_index < cpt_sources_count - 1)
5178 {
5179 cpt_sources_index++;
5180 return OK;
5181 }
5182#ifdef FEAT_EVAL
5183 semsg(_(e_list_index_out_of_range_nr), cpt_sources_index + 1);
5184#endif
5185 return FAIL;
5186}
5187
5188/*
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005189 * Get the next expansion(s), using "compl_pattern".
5190 * The search starts at position "ini" in curbuf and in the direction
5191 * compl_direction.
5192 * When "compl_started" is FALSE start at that position, otherwise continue
5193 * where we stopped searching before.
5194 * This may return before finding all the matches.
5195 * Return the total number of matches or -1 if still unknown -- Acevedo
5196 */
5197 static int
5198ins_compl_get_exp(pos_T *ini)
5199{
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005200 static ins_compl_next_state_T st;
5201 static int st_cleared = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005202 int i;
5203 int found_new_match;
5204 int type = ctrl_x_mode;
Girish Palya7c621052025-05-26 19:41:59 +02005205 int may_advance_cpt_idx = FALSE;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005206
5207 if (!compl_started)
5208 {
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005209 buf_T *buf;
5210
5211 FOR_ALL_BUFFERS(buf)
5212 buf->b_scanned = 0;
5213 if (!st_cleared)
5214 {
5215 CLEAR_FIELD(st);
5216 st_cleared = TRUE;
5217 }
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005218 st.found_all = FALSE;
5219 st.ins_buf = curbuf;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005220 vim_free(st.e_cpt_copy);
Christian Brabandtee17b6f2023-09-09 11:23:50 +02005221 // Make a copy of 'complete', in case the buffer is wiped out.
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005222 st.e_cpt_copy = vim_strsave((compl_cont_status & CONT_LOCAL)
5223 ? (char_u *)"." : curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02005224 strip_caret_numbers_in_place(st.e_cpt_copy);
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005225 st.e_cpt = st.e_cpt_copy == NULL ? (char_u *)"" : st.e_cpt_copy;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005226 st.last_match_pos = st.first_match_pos = *ini;
5227 }
5228 else if (st.ins_buf != curbuf && !buf_valid(st.ins_buf))
5229 st.ins_buf = curbuf; // In case the buffer was wiped out.
5230
5231 compl_old_match = compl_curr_match; // remember the last current match
Christian Brabandt13032a42024-07-28 21:16:48 +02005232 st.cur_match_pos = (compl_dir_forward())
glepnir8159fb12024-07-17 20:32:54 +02005233 ? &st.last_match_pos : &st.first_match_pos;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005234
Girish Palya98c29db2025-06-01 19:40:00 +02005235 if (ctrl_x_mode_normal() && !ctrl_x_mode_line_or_eval() &&
5236 !(compl_cont_status & CONT_LOCAL))
5237 {
5238 // ^N completion, not ^X^L or complete() or ^X^N
5239 if (!compl_started) // Before showing menu the first time
5240 {
5241 if (setup_cpt_sources() == FAIL)
5242 return FAIL;
5243 }
5244 prepare_cpt_compl_funcs();
5245 cpt_sources_index = 0;
5246 }
5247
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005248 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
Girish Palya7c621052025-05-26 19:41:59 +02005249 for (;;)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005250 {
5251 found_new_match = FAIL;
5252 st.set_match_pos = FALSE;
5253
5254 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
5255 // or if found_all says this entry is done. For ^X^L only use the
5256 // entries from 'complete' that look in loaded buffers.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005257 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005258 && (!compl_started || st.found_all))
5259 {
Girish Palya7c621052025-05-26 19:41:59 +02005260 int status = process_next_cpt_value(&st, &type, ini,
5261 cfc_has_mode(), &may_advance_cpt_idx);
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005262
5263 if (status == INS_COMPL_CPT_END)
5264 break;
5265 if (status == INS_COMPL_CPT_CONT)
Girish Palyacbe53192025-04-14 22:13:15 +02005266 {
Girish Palya7c621052025-05-26 19:41:59 +02005267 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5268 break;
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005269 continue;
Girish Palyacbe53192025-04-14 22:13:15 +02005270 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005271 }
5272
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005273 // If complete() was called then compl_pattern has been reset. The
5274 // following won't work then, bail out.
John Marriott5e6ea922024-11-23 14:01:57 +01005275 if (compl_pattern.string == NULL)
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005276 break;
5277
5278 // get the next set of completion matches
5279 found_new_match = get_next_completion_match(type, &st, ini);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005280
Girish Palya7c621052025-05-26 19:41:59 +02005281 if (may_advance_cpt_idx && !advance_cpt_sources_index_safe())
5282 break;
Girish Palyacbe53192025-04-14 22:13:15 +02005283
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005284 // break the loop for specialized modes (use 'complete' just for the
5285 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
5286 // match
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005287 if ((ctrl_x_mode_not_default() && !ctrl_x_mode_line_or_eval())
5288 || found_new_match != FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005289 {
5290 if (got_int)
5291 break;
5292 // Fill the popup menu as soon as possible.
5293 if (type != -1)
5294 ins_compl_check_keys(0, FALSE);
5295
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005296 if ((ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005297 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
5298 break;
5299 compl_started = TRUE;
5300 }
5301 else
5302 {
5303 // Mark a buffer scanned when it has been scanned completely
Christian Brabandtee9166e2023-09-03 21:24:33 +02005304 if (buf_valid(st.ins_buf) && (type == 0 || type == CTRL_X_PATH_PATTERNS))
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005305 st.ins_buf->b_scanned = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005306
5307 compl_started = FALSE;
5308 }
Girish Palya5fbe72e2025-06-18 19:15:45 +02005309
5310 // For `^P` completion, reset `compl_curr_match` to the head to avoid
5311 // mixing matches from different sources.
5312 if (!compl_dir_forward())
5313 while (compl_curr_match->cp_prev)
5314 compl_curr_match = compl_curr_match->cp_prev;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005315 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02005316 cpt_sources_index = -1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005317 compl_started = TRUE;
5318
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005319 if ((ctrl_x_mode_normal() || ctrl_x_mode_line_or_eval())
Yegappan Lakshmanan6ad84ab2021-12-31 12:59:53 +00005320 && *st.e_cpt == NUL) // Got to end of 'complete'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005321 found_new_match = FAIL;
5322
5323 i = -1; // total of matches, unknown
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005324 if (found_new_match == FAIL || (ctrl_x_mode_not_default()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005325 && !ctrl_x_mode_line_or_eval()))
5326 i = ins_compl_make_cyclic();
5327
glepnirf31cfa22025-03-06 21:59:13 +01005328 if (cfc_has_mode() && compl_get_longest && compl_num_bests > 0)
5329 fuzzy_longest_match();
5330
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005331 if (compl_old_match != NULL)
5332 {
5333 // If several matches were added (FORWARD) or the search failed and has
5334 // just been made cyclic then we have to move compl_curr_match to the
5335 // next or previous entry (if any) -- Acevedo
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005336 compl_curr_match = compl_dir_forward() ? compl_old_match->cp_next
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005337 : compl_old_match->cp_prev;
5338 if (compl_curr_match == NULL)
5339 compl_curr_match = compl_old_match;
5340 }
LemonBoy2bf52dd2022-04-09 18:17:34 +01005341 may_trigger_modechanged();
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01005342
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005343 if (is_nearest_active())
5344 sort_compl_match_list(cp_compare_nearest);
5345
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005346 return i;
5347}
5348
5349/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005350 * Update "compl_shown_match" to the actually shown match, it may differ when
5351 * "compl_leader" is used to omit some of the matches.
5352 */
5353 static void
5354ins_compl_update_shown_match(void)
5355{
Girish Palyaba11e782025-07-05 16:11:44 +02005356 string_T *leader;
5357
5358 (void)get_leader_for_startcol(NULL, TRUE); // Clear the cache
5359 leader = get_leader_for_startcol(compl_shown_match, TRUE);
5360
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005361 while (!ins_compl_equal(compl_shown_match,
Girish Palyaba11e782025-07-05 16:11:44 +02005362 leader->string, (int)leader->length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005363 && compl_shown_match->cp_next != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005364 && !is_first_match(compl_shown_match->cp_next))
Girish Palyaba11e782025-07-05 16:11:44 +02005365 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005366 compl_shown_match = compl_shown_match->cp_next;
Girish Palyaba11e782025-07-05 16:11:44 +02005367 leader = get_leader_for_startcol(compl_shown_match, TRUE);
5368 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005369
5370 // If we didn't find it searching forward, and compl_shows_dir is
5371 // backward, find the last match.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005372 if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005373 && !ins_compl_equal(compl_shown_match,
Girish Palyaba11e782025-07-05 16:11:44 +02005374 leader->string, (int)leader->length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005375 && (compl_shown_match->cp_next == NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005376 || is_first_match(compl_shown_match->cp_next)))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005377 {
5378 while (!ins_compl_equal(compl_shown_match,
Girish Palyaba11e782025-07-05 16:11:44 +02005379 leader->string, (int)leader->length)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005380 && compl_shown_match->cp_prev != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005381 && !is_first_match(compl_shown_match->cp_prev))
Girish Palyaba11e782025-07-05 16:11:44 +02005382 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005383 compl_shown_match = compl_shown_match->cp_prev;
Girish Palyaba11e782025-07-05 16:11:44 +02005384 leader = get_leader_for_startcol(compl_shown_match, TRUE);
5385 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005386 }
5387}
5388
5389/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005390 * Delete the old text being completed.
5391 */
5392 void
5393ins_compl_delete(void)
5394{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005395 // In insert mode: Delete the typed part.
5396 // In replace mode: Put the old characters back, if any.
glepniredd4ac32025-01-29 18:53:51 +01005397 int col = compl_col + (compl_status_adding() ? compl_length : 0);
John Marriottf4b36412025-02-23 09:09:59 +01005398 string_T remaining = {NULL, 0};
glepnir76bdb822025-02-08 19:04:51 +01005399 int orig_col;
glepniredd4ac32025-01-29 18:53:51 +01005400 int has_preinsert = ins_compl_preinsert_effect();
5401 if (has_preinsert)
5402 {
Yegappan Lakshmanan7b6add02025-04-01 20:38:37 +02005403 col += (int)ins_compl_leader_len();
glepniredd4ac32025-01-29 18:53:51 +01005404 curwin->w_cursor.col = compl_ins_end_col;
5405 }
5406
glepnir76bdb822025-02-08 19:04:51 +01005407 if (curwin->w_cursor.lnum > compl_lnum)
5408 {
5409 if (curwin->w_cursor.col < ml_get_curline_len())
5410 {
John Marriottf4b36412025-02-23 09:09:59 +01005411 char_u *line = ml_get_cursor();
5412 remaining.length = ml_get_cursor_len();
5413 remaining.string = vim_strnsave(line, remaining.length);
5414 if (remaining.string == NULL)
glepnir76bdb822025-02-08 19:04:51 +01005415 return;
5416 }
5417 while (curwin->w_cursor.lnum > compl_lnum)
5418 {
5419 if (ml_delete(curwin->w_cursor.lnum) == FAIL)
5420 {
John Marriottf4b36412025-02-23 09:09:59 +01005421 if (remaining.string)
5422 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005423 return;
5424 }
zeertzjq060e6552025-02-21 20:06:26 +01005425 deleted_lines_mark(curwin->w_cursor.lnum, 1L);
glepnir76bdb822025-02-08 19:04:51 +01005426 curwin->w_cursor.lnum--;
5427 }
5428 // move cursor to end of line
5429 curwin->w_cursor.col = ml_get_curline_len();
5430 }
5431
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005432 if ((int)curwin->w_cursor.col > col)
5433 {
5434 if (stop_arrow() == FAIL)
glepnire3647c82025-02-10 21:16:32 +01005435 {
John Marriottf4b36412025-02-23 09:09:59 +01005436 if (remaining.string)
5437 vim_free(remaining.string);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005438 return;
glepnire3647c82025-02-10 21:16:32 +01005439 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005440 backspace_until_column(col);
zeertzjqf25d8f92024-12-18 21:12:25 +01005441 compl_ins_end_col = curwin->w_cursor.col;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005442 }
5443
John Marriottf4b36412025-02-23 09:09:59 +01005444 if (remaining.string != NULL)
glepnir76bdb822025-02-08 19:04:51 +01005445 {
5446 orig_col = curwin->w_cursor.col;
John Marriottf4b36412025-02-23 09:09:59 +01005447 ins_str(remaining.string, remaining.length);
glepnir76bdb822025-02-08 19:04:51 +01005448 curwin->w_cursor.col = orig_col;
John Marriottf4b36412025-02-23 09:09:59 +01005449 vim_free(remaining.string);
glepnir76bdb822025-02-08 19:04:51 +01005450 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005451 // TODO: is this sufficient for redrawing? Redrawing everything causes
5452 // flicker, thus we can't do that.
5453 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005454#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005455 // clear v:completed_item
5456 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005457#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005458}
5459
5460/*
glepnir76bdb822025-02-08 19:04:51 +01005461 * Insert a completion string that contains newlines.
5462 * The string is split and inserted line by line.
5463 */
5464 static void
5465ins_compl_expand_multiple(char_u *str)
5466{
5467 char_u *start = str;
5468 char_u *curr = str;
glepnir5090a1f2025-02-24 19:10:37 +01005469 int base_indent = get_indent();
glepnir76bdb822025-02-08 19:04:51 +01005470
5471 while (*curr != NUL)
5472 {
5473 if (*curr == '\n')
5474 {
5475 // Insert the text chunk before newline
5476 if (curr > start)
5477 ins_char_bytes(start, (int)(curr - start));
5478
5479 // Handle newline
glepnir5090a1f2025-02-24 19:10:37 +01005480 open_line(FORWARD, OPENLINE_KEEPTRAIL | OPENLINE_FORCE_INDENT, base_indent, NULL);
glepnir76bdb822025-02-08 19:04:51 +01005481 start = curr + 1;
5482 }
5483 curr++;
5484 }
5485
5486 // Handle remaining text after last newline (if any)
5487 if (curr > start)
5488 ins_char_bytes(start, (int)(curr - start));
5489
5490 compl_ins_end_col = curwin->w_cursor.col;
5491}
5492
5493/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005494 * Insert the new text being completed.
glepniredd4ac32025-01-29 18:53:51 +01005495 * "move_cursor" is used when 'completeopt' includes "preinsert" and when TRUE
5496 * cursor needs to move back from the inserted text to the compl_leader.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005497 */
5498 void
Girish Palya5fbe72e2025-06-18 19:15:45 +02005499ins_compl_insert(int move_cursor)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005500{
glepnir76bdb822025-02-08 19:04:51 +01005501 int compl_len = get_compl_len();
5502 int preinsert = ins_compl_has_preinsert();
5503 char_u *cp_str = compl_shown_match->cp_str.string;
5504 size_t cp_str_len = compl_shown_match->cp_str.length;
5505 size_t leader_len = ins_compl_leader_len();
5506 char_u *has_multiple = vim_strchr(cp_str, '\n');
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005507
Girish Palyaba11e782025-07-05 16:11:44 +02005508 // Since completion sources may provide matches with varying start
5509 // positions, insert only the portion of the match that corresponds to the
5510 // intended replacement range.
5511 if (cpt_sources_array != NULL)
5512 {
5513 int cpt_idx = compl_shown_match->cp_cpt_source_idx;
5514 if (cpt_idx >= 0 && compl_col >= 0)
5515 {
5516 int startcol = cpt_sources_array[cpt_idx].cs_startcol;
5517 if (startcol >= 0 && startcol < (int)compl_col)
5518 {
5519 int skip = (int)compl_col - startcol;
5520 if ((size_t)skip <= cp_str_len)
5521 {
5522 cp_str_len -= skip;
5523 cp_str += skip;
5524 }
5525 }
5526 }
5527 }
5528
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00005529 // Make sure we don't go over the end of the string, this can happen with
5530 // illegal bytes.
zeertzjq8297e2c2025-01-30 11:04:47 +01005531 if (compl_len < (int)cp_str_len)
glepniredd4ac32025-01-29 18:53:51 +01005532 {
glepnir76bdb822025-02-08 19:04:51 +01005533 if (has_multiple)
5534 ins_compl_expand_multiple(cp_str + compl_len);
5535 else
5536 {
5537 ins_compl_insert_bytes(cp_str + compl_len, -1);
5538 if (preinsert && move_cursor)
5539 curwin->w_cursor.col -= (colnr_T)(cp_str_len - leader_len);
5540 }
glepniredd4ac32025-01-29 18:53:51 +01005541 }
5542 if (match_at_original_text(compl_shown_match) || preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005543 compl_used_match = FALSE;
5544 else
5545 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02005546#ifdef FEAT_EVAL
5547 {
5548 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
5549
5550 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
5551 }
5552#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005553}
5554
5555/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005556 * show the file name for the completion match (if any). Truncate the file
5557 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005558 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005559 static void
5560ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005561{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005562 char *lead = _("match in file");
5563 int space = sc_col - vim_strsize((char_u *)lead) - 2;
5564 char_u *s;
5565 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005566
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005567 if (space <= 0)
5568 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005569
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005570 // We need the tail that fits. With double-byte encoding going
5571 // back from the end is very slow, thus go from the start and keep
5572 // the text that fits in "space" between "s" and "e".
5573 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005574 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005575 space -= ptr2cells(e);
5576 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005577 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005578 space += ptr2cells(s);
5579 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005580 }
5581 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005582 msg_hist_off = TRUE;
5583 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
5584 s > compl_shown_match->cp_fname ? "<" : "", s);
5585 msg((char *)IObuff);
5586 msg_hist_off = FALSE;
5587 redraw_cmdline = FALSE; // don't overwrite!
5588}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005589
glepnirdca57fb2024-06-04 22:01:21 +02005590/*
Girish Palya0ac1eb32025-04-16 20:18:33 +02005591 * Find the appropriate completion item when 'complete' ('cpt') includes
5592 * a 'max_matches' postfix. In this case, we search for a match where
5593 * 'cp_in_match_array' is set, indicating that the match is also present
5594 * in 'compl_match_array'.
5595 */
5596 static compl_T *
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005597find_next_match_in_menu(void)
Girish Palya0ac1eb32025-04-16 20:18:33 +02005598{
5599 int is_forward = compl_shows_dir_forward();
5600 compl_T *match = compl_shown_match;
5601
5602 do
5603 match = is_forward ? match->cp_next : match->cp_prev;
5604 while (match->cp_next && !match->cp_in_match_array
5605 && !match_at_original_text(match));
5606 return match;
5607}
5608
5609/*
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005610 * Find the next set of matches for completion. Repeat the completion "todo"
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005611 * times. The number of matches found is returned in 'num_matches'.
5612 *
5613 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
5614 * get more completions. If it is FALSE, then do nothing when there are no more
5615 * completions in the given direction.
5616 *
5617 * If "advance" is TRUE, then completion will move to the first match.
5618 * Otherwise, the original text will be shown.
5619 *
5620 * Returns OK on success and -1 if the number of matches are unknown.
5621 */
5622 static int
5623find_next_completion_match(
5624 int allow_get_expansion,
5625 int todo, // repeat completion this many times
5626 int advance,
5627 int *num_matches)
5628{
Girish Palyaba11e782025-07-05 16:11:44 +02005629 int found_end = FALSE;
5630 compl_T *found_compl = NULL;
zeertzjqaa925ee2024-06-09 18:24:05 +02005631 unsigned int cur_cot_flags = get_cot_flags();
Girish Palyaba11e782025-07-05 16:11:44 +02005632 int compl_no_select = (cur_cot_flags & COT_NOSELECT) != 0;
5633 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
5634 string_T *leader;
5635
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005636
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005637 while (--todo >= 0)
5638 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005639 if (compl_shows_dir_forward() && compl_shown_match->cp_next != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005640 {
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005641 if (compl_match_array != NULL)
5642 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005643 else
5644 compl_shown_match = compl_shown_match->cp_next;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005645 found_end = (compl_first_match != NULL
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005646 && (is_first_match(compl_shown_match->cp_next)
5647 || is_first_match(compl_shown_match)));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005648 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005649 else if (compl_shows_dir_backward()
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005650 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005651 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005652 found_end = is_first_match(compl_shown_match);
Girish Palyab8ee1cf2025-06-08 16:20:06 +02005653 if (compl_match_array != NULL)
5654 compl_shown_match = find_next_match_in_menu();
Girish Palya0ac1eb32025-04-16 20:18:33 +02005655 else
5656 compl_shown_match = compl_shown_match->cp_prev;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005657 found_end |= is_first_match(compl_shown_match);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005658 }
5659 else
5660 {
5661 if (!allow_get_expansion)
5662 {
5663 if (advance)
5664 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005665 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005666 compl_pending -= todo + 1;
5667 else
5668 compl_pending += todo + 1;
5669 }
5670 return -1;
5671 }
5672
5673 if (!compl_no_select && advance)
5674 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005675 if (compl_shows_dir_backward())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005676 --compl_pending;
5677 else
5678 ++compl_pending;
5679 }
5680
5681 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005682 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005683
5684 // handle any pending completions
5685 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005686 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005687 {
5688 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
5689 {
5690 compl_shown_match = compl_shown_match->cp_next;
5691 --compl_pending;
5692 }
5693 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
5694 {
5695 compl_shown_match = compl_shown_match->cp_prev;
5696 ++compl_pending;
5697 }
5698 else
5699 break;
5700 }
5701 found_end = FALSE;
5702 }
Girish Palyaba11e782025-07-05 16:11:44 +02005703
5704 leader = get_leader_for_startcol(compl_shown_match, FALSE);
5705
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00005706 if (!match_at_original_text(compl_shown_match)
Girish Palyaba11e782025-07-05 16:11:44 +02005707 && leader->string != NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005708 && !ins_compl_equal(compl_shown_match,
Girish Palyaba11e782025-07-05 16:11:44 +02005709 leader->string, (int)leader->length)
glepnira218cc62024-06-03 19:32:39 +02005710 && !(compl_fuzzy_match && compl_shown_match->cp_score > 0))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005711 ++todo;
5712 else
5713 // Remember a matching item.
5714 found_compl = compl_shown_match;
5715
5716 // Stop at the end of the list when we found a usable match.
5717 if (found_end)
5718 {
5719 if (found_compl != NULL)
5720 {
5721 compl_shown_match = found_compl;
5722 break;
5723 }
5724 todo = 1; // use first usable match after wrapping around
5725 }
5726 }
5727
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005728 return OK;
5729}
5730
5731/*
5732 * Fill in the next completion in the current direction.
5733 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
5734 * get more completions. If it is FALSE, then we just do nothing when there
5735 * are no more completions in a given direction. The latter case is used when
5736 * we are still in the middle of finding completions, to allow browsing
5737 * through the ones found so far.
5738 * Return the total number of matches, or -1 if still unknown -- webb.
5739 *
5740 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
5741 * compl_shown_match here.
5742 *
5743 * Note that this function may be called recursively once only. First with
5744 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
5745 * calls this function with "allow_get_expansion" FALSE.
5746 */
5747 static int
5748ins_compl_next(
5749 int allow_get_expansion,
5750 int count, // repeat completion this many times; should
5751 // be at least 1
Girish Palya5fbe72e2025-06-18 19:15:45 +02005752 int insert_match) // Insert the newly selected match
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005753{
5754 int num_matches = -1;
5755 int todo = count;
5756 int advance;
5757 int started = compl_started;
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005758 buf_T *orig_curbuf = curbuf;
zeertzjqaa925ee2024-06-09 18:24:05 +02005759 unsigned int cur_cot_flags = get_cot_flags();
zeertzjq529b9ad2024-06-05 20:27:06 +02005760 int compl_no_insert = (cur_cot_flags & COT_NOINSERT) != 0;
5761 int compl_fuzzy_match = (cur_cot_flags & COT_FUZZY) != 0;
glepniredd4ac32025-01-29 18:53:51 +01005762 int compl_preinsert = ins_compl_has_preinsert();
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005763
5764 // When user complete function return -1 for findstart which is next
5765 // time of 'always', compl_shown_match become NULL.
5766 if (compl_shown_match == NULL)
5767 return -1;
5768
John Marriott5e6ea922024-11-23 14:01:57 +01005769 if (compl_leader.string != NULL
glepnira218cc62024-06-03 19:32:39 +02005770 && !match_at_original_text(compl_shown_match)
5771 && !compl_fuzzy_match)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005772 // Update "compl_shown_match" to the actually shown match
5773 ins_compl_update_shown_match();
5774
5775 if (allow_get_expansion && insert_match
nwounkn2e3cd522023-10-17 11:05:38 +02005776 && (!compl_get_longest || compl_used_match))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005777 // Delete old text to be replaced
5778 ins_compl_delete();
5779
5780 // When finding the longest common text we stick at the original text,
5781 // don't let CTRL-N or CTRL-P move to the first match.
5782 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
5783
5784 // When restarting the search don't insert the first match either.
5785 if (compl_restarting)
5786 {
5787 advance = FALSE;
5788 compl_restarting = FALSE;
5789 }
5790
5791 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
5792 // around.
5793 if (find_next_completion_match(allow_get_expansion, todo, advance,
5794 &num_matches) == -1)
5795 return -1;
5796
Bram Moolenaar0ff01832022-09-24 19:20:30 +01005797 if (curbuf != orig_curbuf)
5798 {
5799 // In case some completion function switched buffer, don't want to
5800 // insert the completion elsewhere.
5801 return -1;
5802 }
5803
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005804 // Insert the text of the new completion, or the compl_leader.
glepniredd4ac32025-01-29 18:53:51 +01005805 if (compl_no_insert && !started && !compl_preinsert)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005806 {
glepnir6a38aff2024-12-16 21:56:16 +01005807 ins_compl_insert_bytes(compl_orig_text.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005808 compl_used_match = FALSE;
5809 }
5810 else if (insert_match)
5811 {
5812 if (!compl_get_longest || compl_used_match)
Girish Palya5fbe72e2025-06-18 19:15:45 +02005813 ins_compl_insert(TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005814 else
glepnir6a38aff2024-12-16 21:56:16 +01005815 ins_compl_insert_bytes(compl_leader.string + get_compl_len(), -1);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005816 }
5817 else
5818 compl_used_match = FALSE;
5819
5820 if (!allow_get_expansion)
5821 {
5822 // may undisplay the popup menu first
5823 ins_compl_upd_pum();
5824
5825 if (pum_enough_matches())
5826 // Will display the popup menu, don't redraw yet to avoid flicker.
5827 pum_call_update_screen();
5828 else
5829 // Not showing the popup menu yet, redraw to show the user what was
5830 // inserted.
5831 update_screen(0);
5832
5833 // display the updated popup menu
5834 ins_compl_show_pum();
5835#ifdef FEAT_GUI
5836 if (gui.in_use)
5837 {
5838 // Show the cursor after the match, not after the redrawn text.
5839 setcursor();
5840 out_flush_cursor(FALSE, FALSE);
5841 }
5842#endif
5843
5844 // Delete old text to be replaced, since we're still searching and
5845 // don't want to match ourselves!
5846 ins_compl_delete();
5847 }
5848
5849 // Enter will select a match when the match wasn't inserted and the popup
5850 // menu is visible.
5851 if (compl_no_insert && !started)
5852 compl_enter_selects = TRUE;
5853 else
5854 compl_enter_selects = !insert_match && compl_match_array != NULL;
5855
5856 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005857 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00005858 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005859
5860 return num_matches;
5861}
5862
5863/*
5864 * Call this while finding completions, to check whether the user has hit a key
5865 * that should change the currently displayed completion, or exit completion
5866 * mode. Also, when compl_pending is not zero, show a completion as soon as
5867 * possible. -- webb
5868 * "frequency" specifies out of how many calls we actually check.
5869 * "in_compl_func" is TRUE when called from complete_check(), don't set
5870 * compl_curr_match.
5871 */
5872 void
5873ins_compl_check_keys(int frequency, int in_compl_func)
5874{
5875 static int count = 0;
5876 int c;
5877
5878 // Don't check when reading keys from a script, :normal or feedkeys().
5879 // That would break the test scripts. But do check for keys when called
5880 // from complete_check().
5881 if (!in_compl_func && (using_script() || ex_normal_busy))
5882 return;
5883
5884 // Only do this at regular intervals
5885 if (++count < frequency)
5886 return;
5887 count = 0;
5888
5889 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
5890 // can't do its work correctly.
5891 c = vpeekc_any();
Girish Palyaba11e782025-07-05 16:11:44 +02005892 if (c != NUL
5893#ifdef FEAT_EVAL
5894 // If test_override("char_avail", 1) was called, ignore characters
5895 // waiting in the typeahead buffer.
5896 && !disable_char_avail_for_testing
5897#endif
5898 )
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005899 {
5900 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
5901 {
5902 c = safe_vgetc(); // Eat the character
5903 compl_shows_dir = ins_compl_key2dir(c);
5904 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
Girish Palya5fbe72e2025-06-18 19:15:45 +02005905 c != K_UP && c != K_DOWN);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005906 }
5907 else
5908 {
5909 // Need to get the character to have KeyTyped set. We'll put it
5910 // back with vungetc() below. But skip K_IGNORE.
5911 c = safe_vgetc();
5912 if (c != K_IGNORE)
5913 {
5914 // Don't interrupt completion when the character wasn't typed,
5915 // e.g., when doing @q to replay keys.
5916 if (c != Ctrl_R && KeyTyped)
5917 compl_interrupted = TRUE;
5918
5919 vungetc(c);
5920 }
5921 }
5922 }
zeertzjq529b9ad2024-06-05 20:27:06 +02005923 if (compl_pending != 0 && !got_int && !(cot_flags & COT_NOINSERT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005924 {
5925 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
5926
5927 compl_pending = 0;
Girish Palya5fbe72e2025-06-18 19:15:45 +02005928 (void)ins_compl_next(FALSE, todo, TRUE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005929 }
5930}
5931
5932/*
5933 * Decide the direction of Insert mode complete from the key typed.
5934 * Returns BACKWARD or FORWARD.
5935 */
5936 static int
5937ins_compl_key2dir(int c)
5938{
5939 if (c == Ctrl_P || c == Ctrl_L
5940 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
5941 return BACKWARD;
5942 return FORWARD;
5943}
5944
5945/*
5946 * Return TRUE for keys that are used for completion only when the popup menu
5947 * is visible.
5948 */
5949 static int
5950ins_compl_pum_key(int c)
5951{
5952 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
5953 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
5954 || c == K_UP || c == K_DOWN);
5955}
5956
5957/*
5958 * Decide the number of completions to move forward.
5959 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
5960 */
5961 static int
5962ins_compl_key2count(int c)
5963{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005964 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
5965 {
glepnir19e1dd62025-05-08 22:50:38 +02005966 int h = pum_get_height();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01005967 if (h > 3)
5968 h -= 2; // keep some context
5969 return h;
5970 }
5971 return 1;
5972}
5973
5974/*
5975 * Return TRUE if completion with "c" should insert the match, FALSE if only
5976 * to change the currently selected completion.
5977 */
5978 static int
5979ins_compl_use_match(int c)
5980{
5981 switch (c)
5982 {
5983 case K_UP:
5984 case K_DOWN:
5985 case K_PAGEDOWN:
5986 case K_KPAGEDOWN:
5987 case K_S_DOWN:
5988 case K_PAGEUP:
5989 case K_KPAGEUP:
5990 case K_S_UP:
5991 return FALSE;
5992 }
5993 return TRUE;
5994}
5995
5996/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00005997 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
5998 * completion)
John Marriott5e6ea922024-11-23 14:01:57 +01005999 * Sets the global variables: compl_col, compl_length and compl_pattern.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006000 * Uses the global variables: compl_cont_status and ctrl_x_mode
6001 */
6002 static int
6003get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
6004{
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006005 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode_path_defines())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006006 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006007 if (!compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006008 {
6009 while (--startcol >= 0 && vim_isIDc(line[startcol]))
6010 ;
6011 compl_col += ++startcol;
6012 compl_length = curs_col - startcol;
6013 }
6014 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006015 {
John Marriott5e6ea922024-11-23 14:01:57 +01006016 compl_pattern.string = str_foldcase(line + compl_col,
6017 compl_length, NULL, 0);
6018 if (compl_pattern.string == NULL)
6019 {
6020 compl_pattern.length = 0;
6021 return FAIL;
6022 }
6023 compl_pattern.length = STRLEN(compl_pattern.string);
6024 }
6025 else
6026 {
6027 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6028 if (compl_pattern.string == NULL)
6029 {
6030 compl_pattern.length = 0;
6031 return FAIL;
6032 }
6033 compl_pattern.length = (size_t)compl_length;
John Marriott8c85a2a2024-05-20 19:18:26 +02006034 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006035 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006036 else if (compl_status_adding())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006037 {
6038 char_u *prefix = (char_u *)"\\<";
John Marriott8c85a2a2024-05-20 19:18:26 +02006039 size_t prefixlen = STRLEN_LITERAL("\\<");
John Marriott5e6ea922024-11-23 14:01:57 +01006040 size_t n;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006041
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006042 if (!vim_iswordp(line + compl_col)
6043 || (compl_col > 0
6044 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
John Marriott8c85a2a2024-05-20 19:18:26 +02006045 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006046 prefix = (char_u *)"";
John Marriott8c85a2a2024-05-20 19:18:26 +02006047 prefixlen = 0;
6048 }
John Marriott5e6ea922024-11-23 14:01:57 +01006049
6050 // we need up to 2 extra chars for the prefix
6051 n = quote_meta(NULL, line + compl_col, compl_length) + prefixlen;
6052 compl_pattern.string = alloc(n);
6053 if (compl_pattern.string == NULL)
6054 {
6055 compl_pattern.length = 0;
6056 return FAIL;
6057 }
6058 STRCPY((char *)compl_pattern.string, prefix);
6059 (void)quote_meta(compl_pattern.string + prefixlen,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006060 line + compl_col, compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006061 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006062 }
6063 else if (--startcol < 0
6064 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
6065 {
John Marriott5e6ea922024-11-23 14:01:57 +01006066 size_t len = STRLEN_LITERAL("\\<\\k\\k");
6067
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006068 // Match any word of at least two chars
John Marriott5e6ea922024-11-23 14:01:57 +01006069 compl_pattern.string = vim_strnsave((char_u *)"\\<\\k\\k", len);
6070 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006071 {
John Marriott5e6ea922024-11-23 14:01:57 +01006072 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006073 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006074 }
John Marriott5e6ea922024-11-23 14:01:57 +01006075 compl_pattern.length = len;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006076 compl_col += curs_col;
6077 compl_length = 0;
6078 }
6079 else
6080 {
6081 // Search the point of change class of multibyte character
6082 // or not a word single byte character backward.
6083 if (has_mbyte)
6084 {
6085 int base_class;
6086 int head_off;
6087
6088 startcol -= (*mb_head_off)(line, line + startcol);
6089 base_class = mb_get_class(line + startcol);
6090 while (--startcol >= 0)
6091 {
6092 head_off = (*mb_head_off)(line, line + startcol);
6093 if (base_class != mb_get_class(line + startcol
6094 - head_off))
6095 break;
6096 startcol -= head_off;
6097 }
6098 }
6099 else
glepnir19e1dd62025-05-08 22:50:38 +02006100 {
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006101 while (--startcol >= 0 && vim_iswordc(line[startcol]))
6102 ;
glepnir19e1dd62025-05-08 22:50:38 +02006103 }
6104
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006105 compl_col += ++startcol;
6106 compl_length = (int)curs_col - startcol;
6107 if (compl_length == 1)
6108 {
6109 // Only match word with at least two chars -- webb
6110 // there's no need to call quote_meta,
6111 // alloc(7) is enough -- Acevedo
John Marriott5e6ea922024-11-23 14:01:57 +01006112 compl_pattern.string = alloc(7);
6113 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006114 {
John Marriott5e6ea922024-11-23 14:01:57 +01006115 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006116 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006117 }
John Marriott5e6ea922024-11-23 14:01:57 +01006118 STRCPY((char *)compl_pattern.string, "\\<");
6119 (void)quote_meta(compl_pattern.string + 2, line + compl_col, 1);
6120 STRCAT((char *)compl_pattern.string, "\\k");
6121 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006122 }
6123 else
6124 {
John Marriott5e6ea922024-11-23 14:01:57 +01006125 size_t n = quote_meta(NULL, line + compl_col, compl_length) + 2;
6126
6127 compl_pattern.string = alloc(n);
6128 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006129 {
John Marriott5e6ea922024-11-23 14:01:57 +01006130 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006131 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006132 }
John Marriott5e6ea922024-11-23 14:01:57 +01006133 STRCPY((char *)compl_pattern.string, "\\<");
6134 (void)quote_meta(compl_pattern.string + 2, line + compl_col,
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006135 compl_length);
John Marriott5e6ea922024-11-23 14:01:57 +01006136 compl_pattern.length = n - 1;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006137 }
6138 }
6139
6140 return OK;
6141}
6142
6143/*
6144 * Get the pattern, column and length for whole line completion or for the
6145 * complete() function.
6146 * Sets the global variables: compl_col, compl_length and compl_pattern.
6147 */
6148 static int
6149get_wholeline_compl_info(char_u *line, colnr_T curs_col)
6150{
6151 compl_col = (colnr_T)getwhitecols(line);
6152 compl_length = (int)curs_col - (int)compl_col;
6153 if (compl_length < 0) // cursor in indent: empty pattern
6154 compl_length = 0;
6155 if (p_ic)
John Marriott8c85a2a2024-05-20 19:18:26 +02006156 {
John Marriott5e6ea922024-11-23 14:01:57 +01006157 compl_pattern.string = str_foldcase(line + compl_col, compl_length,
6158 NULL, 0);
6159 if (compl_pattern.string == NULL)
6160 {
6161 compl_pattern.length = 0;
6162 return FAIL;
6163 }
6164 compl_pattern.length = STRLEN(compl_pattern.string);
John Marriott8c85a2a2024-05-20 19:18:26 +02006165 }
John Marriott5e6ea922024-11-23 14:01:57 +01006166 else
6167 {
6168 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6169 if (compl_pattern.string == NULL)
6170 {
6171 compl_pattern.length = 0;
6172 return FAIL;
6173 }
6174 compl_pattern.length = (size_t)compl_length;
6175 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006176
6177 return OK;
6178}
6179
6180/*
6181 * Get the pattern, column and length for filename completion.
6182 * Sets the global variables: compl_col, compl_length and compl_pattern.
6183 */
6184 static int
6185get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
6186{
6187 // Go back to just before the first filename character.
6188 if (startcol > 0)
6189 {
6190 char_u *p = line + startcol;
6191
6192 MB_PTR_BACK(line, p);
6193 while (p > line && vim_isfilec(PTR2CHAR(p)))
6194 MB_PTR_BACK(line, p);
6195 if (p == line && vim_isfilec(PTR2CHAR(p)))
6196 startcol = 0;
6197 else
6198 startcol = (int)(p - line) + 1;
6199 }
6200
6201 compl_col += startcol;
6202 compl_length = (int)curs_col - startcol;
John Marriott5e6ea922024-11-23 14:01:57 +01006203 compl_pattern.string = addstar(line + compl_col, compl_length, EXPAND_FILES);
6204 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006205 {
John Marriott5e6ea922024-11-23 14:01:57 +01006206 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006207 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006208 }
6209
John Marriott5e6ea922024-11-23 14:01:57 +01006210 compl_pattern.length = STRLEN(compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006211
6212 return OK;
6213}
6214
6215/*
6216 * Get the pattern, column and length for command-line completion.
6217 * Sets the global variables: compl_col, compl_length and compl_pattern.
6218 */
6219 static int
6220get_cmdline_compl_info(char_u *line, colnr_T curs_col)
6221{
John Marriott5e6ea922024-11-23 14:01:57 +01006222 compl_pattern.string = vim_strnsave(line, curs_col);
6223 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006224 {
John Marriott5e6ea922024-11-23 14:01:57 +01006225 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006226 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006227 }
John Marriott5e6ea922024-11-23 14:01:57 +01006228 compl_pattern.length = curs_col;
6229 set_cmd_context(&compl_xp, compl_pattern.string,
6230 (int)compl_pattern.length, curs_col, FALSE);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006231 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
6232 || compl_xp.xp_context == EXPAND_NOTHING)
6233 // No completion possible, use an empty pattern to get a
6234 // "pattern not found" message.
6235 compl_col = curs_col;
6236 else
John Marriott5e6ea922024-11-23 14:01:57 +01006237 compl_col = (int)(compl_xp.xp_pattern - compl_pattern.string);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006238 compl_length = curs_col - compl_col;
6239
6240 return OK;
6241}
6242
Girish Palya98c29db2025-06-01 19:40:00 +02006243#ifdef FEAT_COMPL_FUNC
6244/*
6245 * Set global variables related to completion:
6246 * compl_col, compl_length, compl_pattern, and cpt_compl_pattern.
6247 */
6248 static int
6249set_compl_globals(
6250 int startcol UNUSED,
6251 colnr_T curs_col UNUSED,
6252 int is_cpt_compl UNUSED)
6253{
Girish Palyaba11e782025-07-05 16:11:44 +02006254 if (is_cpt_compl)
Girish Palya98c29db2025-06-01 19:40:00 +02006255 {
Girish Palyaba11e782025-07-05 16:11:44 +02006256 VIM_CLEAR_STRING(cpt_compl_pattern);
6257 if (startcol < compl_col)
6258 return prepend_startcol_text(&cpt_compl_pattern, &compl_orig_text,
6259 startcol);
6260 else
6261 {
6262 cpt_compl_pattern.string = vim_strnsave(compl_orig_text.string,
6263 compl_orig_text.length);
6264 cpt_compl_pattern.length = compl_orig_text.length;
6265 }
Girish Palya98c29db2025-06-01 19:40:00 +02006266 }
Girish Palyaba11e782025-07-05 16:11:44 +02006267 else
Girish Palya98c29db2025-06-01 19:40:00 +02006268 {
Girish Palyaba11e782025-07-05 16:11:44 +02006269 if (startcol < 0 || startcol > curs_col)
6270 startcol = curs_col;
6271
6272 // Re-obtain line in case it has changed
6273 char_u *line = ml_get(curwin->w_cursor.lnum);
6274 int len = curs_col - startcol;
6275
6276 compl_pattern.string = vim_strnsave(line + startcol, (size_t)len);
6277 if (compl_pattern.string == NULL)
6278 {
6279 compl_pattern.length = 0;
6280 return FAIL;
6281 }
6282 compl_pattern.length = (size_t)len;
Girish Palya98c29db2025-06-01 19:40:00 +02006283 compl_col = startcol;
6284 compl_length = len;
6285 }
Girish Palyaba11e782025-07-05 16:11:44 +02006286
Girish Palya98c29db2025-06-01 19:40:00 +02006287 return OK;
6288}
6289#endif
6290
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006291/*
6292 * Get the pattern, column and length for user defined completion ('omnifunc',
6293 * 'completefunc' and 'thesaurusfunc')
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006294 * Uses the global variable: spell_bad_len
Girish Palyacbe53192025-04-14 22:13:15 +02006295 * Callback function "cb" is set if triggered by a function in the 'cpt'
6296 * option; otherwise, it is NULL.
6297 * "startcol", when not NULL, contains the column returned by function.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006298 */
6299 static int
glepnir19e1dd62025-05-08 22:50:38 +02006300get_userdefined_compl_info(
6301 colnr_T curs_col UNUSED,
6302 callback_T *cb UNUSED,
6303 int *startcol UNUSED)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006304{
6305 int ret = FAIL;
6306
6307#ifdef FEAT_COMPL_FUNC
6308 // Call user defined function 'completefunc' with "a:findstart"
6309 // set to 1 to obtain the length of text to use for completion.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006310 typval_T args[3];
6311 int col;
glepnir19e1dd62025-05-08 22:50:38 +02006312 char_u *funcname = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006313 pos_T pos;
6314 int save_State = State;
Girish Palyacbe53192025-04-14 22:13:15 +02006315 int is_cpt_function = (cb != NULL);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006316
Girish Palyacbe53192025-04-14 22:13:15 +02006317 if (!is_cpt_function)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006318 {
Girish Palyacbe53192025-04-14 22:13:15 +02006319 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
6320 // length as a string
6321 funcname = get_complete_funcname(ctrl_x_mode);
6322 if (*funcname == NUL)
6323 {
6324 semsg(_(e_option_str_is_not_set), ctrl_x_mode_function()
6325 ? "completefunc" : "omnifunc");
6326 return FAIL;
6327 }
6328 cb = get_insert_callback(ctrl_x_mode);
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006329 }
6330
6331 args[0].v_type = VAR_NUMBER;
6332 args[0].vval.v_number = 1;
6333 args[1].v_type = VAR_STRING;
6334 args[1].vval.v_string = (char_u *)"";
6335 args[2].v_type = VAR_UNKNOWN;
6336 pos = curwin->w_cursor;
zeertzjqcfe45652022-05-27 17:26:55 +01006337 ++textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006338 col = call_callback_retnr(cb, 2, args);
zeertzjqcfe45652022-05-27 17:26:55 +01006339 --textlock;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006340
6341 State = save_State;
6342 curwin->w_cursor = pos; // restore the cursor position
zeertzjq0a419e02024-04-02 19:01:14 +02006343 check_cursor(); // make sure cursor position is valid, just in case
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006344 validate_cursor();
6345 if (!EQUAL_POS(curwin->w_cursor, pos))
6346 {
Bram Moolenaar9d00e4a2022-01-05 17:49:15 +00006347 emsg(_(e_complete_function_deleted_text));
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006348 return FAIL;
6349 }
6350
Girish Palyacbe53192025-04-14 22:13:15 +02006351 if (startcol != NULL)
6352 *startcol = col;
6353
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006354 // Return value -2 means the user complete function wants to cancel the
6355 // complete without an error, do the same if the function did not execute
6356 // successfully.
6357 if (col == -2 || aborting())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006358 return FAIL;
glepnir19e1dd62025-05-08 22:50:38 +02006359
LemonBoy9bcb9ca2022-05-26 15:23:26 +01006360 // Return value -3 does the same as -2 and leaves CTRL-X mode.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006361 if (col == -3)
6362 {
Girish Palyacbe53192025-04-14 22:13:15 +02006363 if (is_cpt_function)
6364 return FAIL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006365 ctrl_x_mode = CTRL_X_NORMAL;
6366 edit_submode = NULL;
6367 if (!shortmess(SHM_COMPLETIONMENU))
6368 msg_clr_cmdline();
6369 return FAIL;
6370 }
6371
Yegappan Lakshmanan37079142022-01-08 10:38:48 +00006372 // Reset extended parameters of completion, when starting new
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006373 // completion.
6374 compl_opt_refresh_always = FALSE;
6375 compl_opt_suppress_empty = FALSE;
6376
Girish Palya98c29db2025-06-01 19:40:00 +02006377 ret = !is_cpt_function ? set_compl_globals(col, curs_col, FALSE) : OK;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006378#endif
6379
6380 return ret;
6381}
6382
6383/*
6384 * Get the pattern, column and length for spell completion.
6385 * Sets the global variables: compl_col, compl_length and compl_pattern.
6386 * Uses the global variable: spell_bad_len
6387 */
6388 static int
6389get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
6390{
6391 int ret = FAIL;
6392#ifdef FEAT_SPELL
glepnir19e1dd62025-05-08 22:50:38 +02006393 char_u *line = NULL;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006394
6395 if (spell_bad_len > 0)
6396 compl_col = curs_col - spell_bad_len;
6397 else
6398 compl_col = spell_word_start(startcol);
glepnir19e1dd62025-05-08 22:50:38 +02006399
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006400 if (compl_col >= (colnr_T)startcol)
6401 {
6402 compl_length = 0;
6403 compl_col = curs_col;
6404 }
6405 else
6406 {
6407 spell_expand_check_cap(compl_col);
6408 compl_length = (int)curs_col - compl_col;
6409 }
6410 // Need to obtain "line" again, it may have become invalid.
6411 line = ml_get(curwin->w_cursor.lnum);
John Marriott5e6ea922024-11-23 14:01:57 +01006412 compl_pattern.string = vim_strnsave(line + compl_col, (size_t)compl_length);
6413 if (compl_pattern.string == NULL)
John Marriott8c85a2a2024-05-20 19:18:26 +02006414 {
John Marriott5e6ea922024-11-23 14:01:57 +01006415 compl_pattern.length = 0;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006416 return FAIL;
John Marriott8c85a2a2024-05-20 19:18:26 +02006417 }
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006418
John Marriott5e6ea922024-11-23 14:01:57 +01006419 compl_pattern.length = (size_t)compl_length;
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006420 ret = OK;
6421#endif
6422
6423 return ret;
6424}
6425
6426/*
6427 * Get the completion pattern, column and length.
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006428 * "startcol" - start column number of the completion pattern/text
6429 * "cur_col" - current cursor column
6430 * On return, "line_invalid" is set to TRUE, if the current line may have
6431 * become invalid and needs to be fetched again.
6432 * Returns OK on success.
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006433 */
6434 static int
6435compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
6436{
glepnird5fdfa52025-06-02 19:45:41 +02006437 if (ctrl_x_mode_normal() || ctrl_x_mode_register()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006438 || (ctrl_x_mode & CTRL_X_WANT_IDENT
6439 && !thesaurus_func_complete(ctrl_x_mode)))
6440 {
Girish Palyaba11e782025-07-05 16:11:44 +02006441 if (get_normal_compl_info(line, startcol, curs_col) != OK)
6442 return FAIL;
6443 *line_invalid = TRUE; // 'cpt' func may have invalidated "line"
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006444 }
6445 else if (ctrl_x_mode_line_or_eval())
6446 {
6447 return get_wholeline_compl_info(line, curs_col);
6448 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006449 else if (ctrl_x_mode_files())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006450 {
6451 return get_filename_compl_info(line, startcol, curs_col);
6452 }
6453 else if (ctrl_x_mode == CTRL_X_CMDLINE)
6454 {
6455 return get_cmdline_compl_info(line, curs_col);
6456 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006457 else if (ctrl_x_mode_function() || ctrl_x_mode_omni()
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006458 || thesaurus_func_complete(ctrl_x_mode))
6459 {
Girish Palyacbe53192025-04-14 22:13:15 +02006460 if (get_userdefined_compl_info(curs_col, NULL, NULL) != OK)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006461 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006462 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006463 }
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006464 else if (ctrl_x_mode_spell())
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006465 {
6466 if (get_spell_compl_info(startcol, curs_col) == FAIL)
6467 return FAIL;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006468 *line_invalid = TRUE; // "line" may have become invalid
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00006469 }
6470 else
6471 {
6472 internal_error("ins_complete()");
6473 return FAIL;
6474 }
6475
6476 return OK;
6477}
6478
6479/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006480 * Continue an interrupted completion mode search in "line".
6481 *
6482 * If this same ctrl_x_mode has been interrupted use the text from
6483 * "compl_startpos" to the cursor as a pattern to add a new word instead of
6484 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
6485 * the same line as the cursor then fix it (the line has been split because it
6486 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
6487 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006488 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006489 static void
6490ins_compl_continue_search(char_u *line)
6491{
6492 // it is a continued search
6493 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006494 if (ctrl_x_mode_normal() || ctrl_x_mode_path_patterns()
6495 || ctrl_x_mode_path_defines())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006496 {
6497 if (compl_startpos.lnum != curwin->w_cursor.lnum)
6498 {
6499 // line (probably) wrapped, set compl_startpos to the
6500 // first non_blank in the line, if it is not a wordchar
6501 // include it to get a better pattern, but then we don't
6502 // want the "\\<" prefix, check it below
6503 compl_col = (colnr_T)getwhitecols(line);
6504 compl_startpos.col = compl_col;
6505 compl_startpos.lnum = curwin->w_cursor.lnum;
6506 compl_cont_status &= ~CONT_SOL; // clear SOL if present
6507 }
6508 else
6509 {
6510 // S_IPOS was set when we inserted a word that was at the
6511 // beginning of the line, which means that we'll go to SOL
6512 // mode but first we need to redefine compl_startpos
6513 if (compl_cont_status & CONT_S_IPOS)
6514 {
6515 compl_cont_status |= CONT_SOL;
6516 compl_startpos.col = (colnr_T)(skipwhite(
6517 line + compl_length
6518 + compl_startpos.col) - line);
6519 }
6520 compl_col = compl_startpos.col;
6521 }
6522 compl_length = curwin->w_cursor.col - (int)compl_col;
6523 // IObuff is used to add a "word from the next line" would we
6524 // have enough space? just being paranoid
6525#define MIN_SPACE 75
6526 if (compl_length > (IOSIZE - MIN_SPACE))
6527 {
6528 compl_cont_status &= ~CONT_SOL;
6529 compl_length = (IOSIZE - MIN_SPACE);
6530 compl_col = curwin->w_cursor.col - compl_length;
6531 }
6532 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
6533 if (compl_length < 1)
6534 compl_cont_status &= CONT_LOCAL;
6535 }
glepnird5fdfa52025-06-02 19:45:41 +02006536 else if (ctrl_x_mode_line_or_eval() || ctrl_x_mode_register())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006537 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
6538 else
6539 compl_cont_status = 0;
6540}
6541
6542/*
6543 * start insert mode completion
6544 */
6545 static int
6546ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006547{
glepnir19e1dd62025-05-08 22:50:38 +02006548 char_u *line = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006549 int startcol = 0; // column where searched text starts
6550 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006551 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006552 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02006553 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006554
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006555 // First time we hit ^N or ^P (in a row, I mean)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006556 did_ai = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006557 did_si = FALSE;
6558 can_si = FALSE;
6559 can_si_back = FALSE;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006560 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006561 return FAIL;
6562
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006563 line = ml_get(curwin->w_cursor.lnum);
6564 curs_col = curwin->w_cursor.col;
6565 compl_pending = 0;
glepnir76bdb822025-02-08 19:04:51 +01006566 compl_lnum = curwin->w_cursor.lnum;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006567
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006568 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
6569 && compl_cont_mode == ctrl_x_mode)
6570 // this same ctrl-x_mode was interrupted previously. Continue the
6571 // completion.
6572 ins_compl_continue_search(line);
6573 else
6574 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006575
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006576 if (!compl_status_adding()) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006577 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006578 compl_cont_mode = ctrl_x_mode;
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006579 if (ctrl_x_mode_not_default())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006580 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
6581 compl_cont_status = 0;
6582 compl_cont_status |= CONT_N_ADDS;
6583 compl_startpos = curwin->w_cursor;
6584 startcol = (int)curs_col;
6585 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006586 }
6587
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006588 // Work out completion pattern and original text -- webb
6589 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
6590 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006591 if (ctrl_x_mode_function() || ctrl_x_mode_omni()
6592 || thesaurus_func_complete(ctrl_x_mode))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006593 // restore did_ai, so that adding comment leader works
6594 did_ai = save_did_ai;
6595 return FAIL;
6596 }
6597 // If "line" was changed while getting completion info get it again.
6598 if (line_invalid)
6599 line = ml_get(curwin->w_cursor.lnum);
6600
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006601 if (compl_status_adding())
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006602 {
6603 edit_submode_pre = (char_u *)_(" Adding");
6604 if (ctrl_x_mode_line_or_eval())
6605 {
6606 // Insert a new line, keep indentation but ignore 'comments'.
6607 char_u *old = curbuf->b_p_com;
6608
6609 curbuf->b_p_com = (char_u *)"";
6610 compl_startpos.lnum = curwin->w_cursor.lnum;
6611 compl_startpos.col = compl_col;
6612 ins_eol('\r');
6613 curbuf->b_p_com = old;
6614 compl_length = 0;
6615 compl_col = curwin->w_cursor.col;
glepnir76bdb822025-02-08 19:04:51 +01006616 compl_lnum = curwin->w_cursor.lnum;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006617 }
glepnircfe502c2025-04-17 20:17:53 +02006618 else if (ctrl_x_mode_normal() && cfc_has_mode())
glepnir7cfe6932024-09-15 20:06:28 +02006619 {
6620 compl_startpos = curwin->w_cursor;
6621 compl_cont_status &= CONT_S_IPOS;
6622 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006623 }
6624 else
6625 {
6626 edit_submode_pre = NULL;
6627 compl_startpos.col = compl_col;
6628 }
6629
6630 if (compl_cont_status & CONT_LOCAL)
6631 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
6632 else
6633 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
6634
6635 // If any of the original typed text has been changed we need to fix
6636 // the redo buffer.
6637 ins_compl_fixRedoBufForLeader(NULL);
6638
6639 // Always add completion for the original text.
John Marriott5e6ea922024-11-23 14:01:57 +01006640 VIM_CLEAR_STRING(compl_orig_text);
6641 compl_orig_text.length = (size_t)compl_length;
6642 compl_orig_text.string = vim_strnsave(line + compl_col, (size_t)compl_length);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006643 if (p_ic)
6644 flags |= CP_ICASE;
zeertzjq4422de62025-03-07 19:06:02 +01006645 if (compl_orig_text.string == NULL
6646 || ins_compl_add(compl_orig_text.string,
6647 (int)compl_orig_text.length,
6648 NULL, NULL, NULL, 0, flags, FALSE, NULL, 0) != OK)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006649 {
John Marriott5e6ea922024-11-23 14:01:57 +01006650 VIM_CLEAR_STRING(compl_pattern);
6651 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006652 return FAIL;
6653 }
6654
6655 // showmode might reset the internal line pointers, so it must
6656 // be called before line = ml_get(), or when this address is no
6657 // longer needed. -- Acevedo.
6658 edit_submode_extra = (char_u *)_("-- Searching...");
6659 edit_submode_highl = HLF_COUNT;
6660 showmode();
6661 edit_submode_extra = NULL;
6662 out_flush();
6663
6664 return OK;
6665}
6666
6667/*
6668 * display the completion status message
6669 */
6670 static void
6671ins_compl_show_statusmsg(void)
6672{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006673 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006674 if (is_first_match(compl_first_match->cp_next))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006675 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006676 edit_submode_extra = compl_status_adding() && compl_length > 1
Bram Moolenaarb53a1902022-11-15 13:57:38 +00006677 ? (char_u *)_("Hit end of paragraph")
6678 : (char_u *)_("Pattern not found");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006679 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006680 }
6681
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006682 if (edit_submode_extra == NULL)
6683 {
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006684 if (match_at_original_text(compl_curr_match))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006685 {
6686 edit_submode_extra = (char_u *)_("Back at original");
6687 edit_submode_highl = HLF_W;
6688 }
6689 else if (compl_cont_status & CONT_S_IPOS)
6690 {
6691 edit_submode_extra = (char_u *)_("Word from other line");
6692 edit_submode_highl = HLF_COUNT;
6693 }
6694 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
6695 {
6696 edit_submode_extra = (char_u *)_("The only match");
6697 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006698 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006699 }
6700 else
6701 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006702#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006703 // Update completion sequence number when needed.
6704 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01006705 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01006706#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006707 // The match should always have a sequence number now, this is
6708 // just a safety check.
6709 if (compl_curr_match->cp_number != -1)
6710 {
6711 // Space for 10 text chars. + 2x10-digit no.s = 31.
6712 // Translations may need more than twice that.
6713 static char_u match_ref[81];
6714
6715 if (compl_matches > 0)
6716 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006717 _("match %d of %d"),
6718 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006719 else
6720 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006721 _("match %d"),
6722 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006723 edit_submode_extra = match_ref;
6724 edit_submode_highl = HLF_R;
6725 if (dollar_vcol >= 0)
6726 curs_columns(FALSE);
6727 }
6728 }
6729 }
6730
6731 // Show a message about what (completion) mode we're in.
6732 if (!compl_opt_suppress_empty)
6733 {
6734 showmode();
6735 if (!shortmess(SHM_COMPLETIONMENU))
6736 {
6737 if (edit_submode_extra != NULL)
6738 {
6739 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01006740 {
6741 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006742 msg_attr((char *)edit_submode_extra,
6743 edit_submode_highl < HLF_COUNT
6744 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01006745 msg_hist_off = FALSE;
6746 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006747 }
6748 else
6749 msg_clr_cmdline(); // necessary for "noshowmode"
6750 }
6751 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006752}
6753
6754/*
6755 * Do Insert mode completion.
6756 * Called when character "c" was typed, which has a meaning for completion.
6757 * Returns OK if completion was done, FAIL if something failed (out of mem).
6758 */
6759 int
6760ins_complete(int c, int enable_pum)
6761{
6762 int n;
6763 int save_w_wrow;
6764 int save_w_leftcol;
6765 int insert_match;
6766
6767 compl_direction = ins_compl_key2dir(c);
6768 insert_match = ins_compl_use_match(c);
6769
6770 if (!compl_started)
6771 {
6772 if (ins_compl_start() == FAIL)
6773 return FAIL;
6774 }
6775 else if (insert_match && stop_arrow() == FAIL)
6776 return FAIL;
6777
glepnircf7f0122025-04-15 19:02:00 +02006778 compl_curr_win = curwin;
6779 compl_curr_buf = curwin->w_buffer;
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006780 compl_shown_match = compl_curr_match;
6781 compl_shows_dir = compl_direction;
6782
6783 // Find next match (and following matches).
6784 save_w_wrow = curwin->w_wrow;
6785 save_w_leftcol = curwin->w_leftcol;
Girish Palya5fbe72e2025-06-18 19:15:45 +02006786 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match);
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006787
6788 // may undisplay the popup menu
6789 ins_compl_upd_pum();
6790
6791 if (n > 1) // all matches have been found
6792 compl_matches = n;
6793 compl_curr_match = compl_shown_match;
6794 compl_direction = compl_shows_dir;
6795
6796 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
6797 // mode.
6798 if (got_int && !global_busy)
6799 {
6800 (void)vgetc();
6801 got_int = FALSE;
6802 }
6803
6804 // we found no match if the list has only the "compl_orig_text"-entry
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006805 if (is_first_match(compl_first_match->cp_next))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006806 {
6807 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
6808 // because we couldn't expand anything at first place, but if we used
6809 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
6810 // (such as M in M'exico) if not tried already. -- Acevedo
6811 if (compl_length > 1
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006812 || compl_status_adding()
6813 || (ctrl_x_mode_not_default()
6814 && !ctrl_x_mode_path_patterns()
6815 && !ctrl_x_mode_path_defines()))
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00006816 compl_cont_status &= ~CONT_N_ADDS;
6817 }
6818
6819 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
6820 compl_cont_status |= CONT_S_IPOS;
6821 else
6822 compl_cont_status &= ~CONT_S_IPOS;
6823
6824 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006825
6826 // Show the popup menu, unless we got interrupted.
6827 if (enable_pum && !compl_interrupted)
6828 show_pum(save_w_wrow, save_w_leftcol);
6829
6830 compl_was_interrupted = compl_interrupted;
6831 compl_interrupted = FALSE;
6832
6833 return OK;
6834}
6835
Yegappan Lakshmanane9825862022-01-03 11:03:48 +00006836/*
6837 * Remove (if needed) and show the popup menu
6838 */
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006839 static void
6840show_pum(int prev_w_wrow, int prev_w_leftcol)
6841{
6842 // RedrawingDisabled may be set when invoked through complete().
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006843 int save_RedrawingDisabled = RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006844 RedrawingDisabled = 0;
6845
6846 // If the cursor moved or the display scrolled we need to remove the pum
6847 // first.
6848 setcursor();
6849 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
6850 ins_compl_del_pum();
6851
6852 ins_compl_show_pum();
6853 setcursor();
Bram Moolenaar79cdf022023-05-20 14:07:00 +01006854
6855 RedrawingDisabled = save_RedrawingDisabled;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006856}
6857
6858/*
6859 * Looks in the first "len" chars. of "src" for search-metachars.
6860 * If dest is not NULL the chars. are copied there quoting (with
6861 * a backslash) the metachars, and dest would be NUL terminated.
6862 * Returns the length (needed) of dest
6863 */
6864 static unsigned
6865quote_meta(char_u *dest, char_u *src, int len)
6866{
6867 unsigned m = (unsigned)len + 1; // one extra for the NUL
6868
6869 for ( ; --len >= 0; src++)
6870 {
6871 switch (*src)
6872 {
6873 case '.':
6874 case '*':
6875 case '[':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006876 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006877 break;
6878 // FALLTHROUGH
6879 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01006880 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006881 break;
6882 // FALLTHROUGH
6883 case '\\':
Yegappan Lakshmanand94fbfc2022-01-04 17:01:44 +00006884 if (ctrl_x_mode_dictionary() || ctrl_x_mode_thesaurus())
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006885 break;
6886 // FALLTHROUGH
6887 case '^': // currently it's not needed.
6888 case '$':
6889 m++;
6890 if (dest != NULL)
6891 *dest++ = '\\';
6892 break;
6893 }
6894 if (dest != NULL)
6895 *dest++ = *src;
6896 // Copy remaining bytes of a multibyte character.
6897 if (has_mbyte)
6898 {
glepnir19e1dd62025-05-08 22:50:38 +02006899 int mb_len = (*mb_ptr2len)(src) - 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006900 if (mb_len > 0 && len >= mb_len)
glepnir19e1dd62025-05-08 22:50:38 +02006901 for (int i = 0; i < mb_len; ++i)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006902 {
6903 --len;
6904 ++src;
6905 if (dest != NULL)
6906 *dest++ = *src;
6907 }
6908 }
6909 }
6910 if (dest != NULL)
6911 *dest = NUL;
6912
6913 return m;
6914}
6915
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006916#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006917 void
6918free_insexpand_stuff(void)
6919{
John Marriott5e6ea922024-11-23 14:01:57 +01006920 VIM_CLEAR_STRING(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00006921# ifdef FEAT_EVAL
6922 free_callback(&cfu_cb);
6923 free_callback(&ofu_cb);
6924 free_callback(&tsrfu_cb);
6925# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006926}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006927#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006928
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006929#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006930/*
6931 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
6932 * spelled word, if there is one.
6933 */
6934 static void
6935spell_back_to_badword(void)
6936{
6937 pos_T tpos = curwin->w_cursor;
6938
Christ van Willegen - van Noort8e4c4c72024-05-17 18:49:27 +02006939 spell_bad_len = spell_move_to(curwin, BACKWARD, SMT_ALL, TRUE, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01006940 if (curwin->w_cursor.col != tpos.col)
6941 start_arrow(&tpos);
6942}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02006943#endif
Girish Palyacbe53192025-04-14 22:13:15 +02006944
6945/*
6946 * Reset the info associated with completion sources.
6947 */
6948 static void
Girish Palya0ac1eb32025-04-16 20:18:33 +02006949cpt_sources_clear(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006950{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006951 VIM_CLEAR(cpt_sources_array);
6952 cpt_sources_index = -1;
6953 cpt_sources_count = 0;
Girish Palyacbe53192025-04-14 22:13:15 +02006954}
6955
6956/*
Girish Palya98c29db2025-06-01 19:40:00 +02006957 * Setup completion sources.
Girish Palyacbe53192025-04-14 22:13:15 +02006958 */
6959 static int
Girish Palya98c29db2025-06-01 19:40:00 +02006960setup_cpt_sources(void)
Girish Palyacbe53192025-04-14 22:13:15 +02006961{
Girish Palya0ac1eb32025-04-16 20:18:33 +02006962 char_u buf[LSIZE];
6963 int slen;
Girish Palya98c29db2025-06-01 19:40:00 +02006964 int count = 0, idx = 0;
Girish Palya0ac1eb32025-04-16 20:18:33 +02006965 char_u *p;
Girish Palyacbe53192025-04-14 22:13:15 +02006966
Girish Palya0ac1eb32025-04-16 20:18:33 +02006967 for (p = curbuf->b_p_cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02006968 {
6969 while (*p == ',' || *p == ' ') // Skip delimiters
6970 p++;
6971 if (*p) // If not end of string, count this segment
6972 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02006973 (void)copy_option_part(&p, buf, LSIZE, ","); // Advance p
Girish Palyacbe53192025-04-14 22:13:15 +02006974 count++;
Girish Palyacbe53192025-04-14 22:13:15 +02006975 }
6976 }
Girish Palya98c29db2025-06-01 19:40:00 +02006977 if (count == 0)
6978 return OK;
6979
Girish Palya0ac1eb32025-04-16 20:18:33 +02006980 cpt_sources_clear();
6981 cpt_sources_count = count;
Girish Palya98c29db2025-06-01 19:40:00 +02006982 cpt_sources_array = ALLOC_CLEAR_MULT(cpt_source_T, count);
6983 if (cpt_sources_array == NULL)
Girish Palyacbe53192025-04-14 22:13:15 +02006984 {
Girish Palya98c29db2025-06-01 19:40:00 +02006985 cpt_sources_count = 0;
6986 return FAIL;
6987 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02006988
Girish Palya98c29db2025-06-01 19:40:00 +02006989 for (p = curbuf->b_p_cpt; *p;)
6990 {
6991 while (*p == ',' || *p == ' ') // Skip delimiters
6992 p++;
6993 if (*p) // If not end of string, count this segment
6994 {
6995 char_u *t;
6996
6997 vim_memset(buf, 0, LSIZE);
6998 slen = copy_option_part(&p, buf, LSIZE, ","); // Advance p
6999 if (slen > 0 && (t = vim_strchr(buf, '^')) != NULL)
7000 cpt_sources_array[idx].cs_max_matches = atoi((char *)t + 1);
7001 idx++;
Girish Palya0ac1eb32025-04-16 20:18:33 +02007002 }
Girish Palyacbe53192025-04-14 22:13:15 +02007003 }
7004 return OK;
7005}
7006
7007/*
7008 * Return TRUE if any of the completion sources have 'refresh' set to 'always'.
7009 */
7010 static int
7011is_cpt_func_refresh_always(void)
7012{
7013#ifdef FEAT_COMPL_FUNC
glepnir19e1dd62025-05-08 22:50:38 +02007014 for (int i = 0; i < cpt_sources_count; i++)
Girish Palya98c29db2025-06-01 19:40:00 +02007015 if (cpt_sources_array[i].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007016 return TRUE;
7017#endif
7018 return FALSE;
7019}
7020
7021/*
7022 * Make the completion list non-cyclic.
7023 */
Girish Palyacbe53192025-04-14 22:13:15 +02007024 static void
7025ins_compl_make_linear(void)
7026{
7027 compl_T *m;
7028
7029 if (compl_first_match == NULL || compl_first_match->cp_prev == NULL)
7030 return;
7031 m = compl_first_match->cp_prev;
7032 m->cp_next = NULL;
7033 compl_first_match->cp_prev = NULL;
7034}
Girish Palyacbe53192025-04-14 22:13:15 +02007035
7036/*
7037 * Remove the matches linked to the current completion source (as indicated by
Girish Palya0ac1eb32025-04-16 20:18:33 +02007038 * cpt_sources_index) from the completion list.
Girish Palyacbe53192025-04-14 22:13:15 +02007039 */
7040#ifdef FEAT_COMPL_FUNC
7041 static compl_T *
7042remove_old_matches(void)
7043{
7044 compl_T *sublist_start = NULL, *sublist_end = NULL, *insert_at = NULL;
7045 compl_T *current, *next;
Girish Palya0ac1eb32025-04-16 20:18:33 +02007046 int compl_shown_removed = FALSE;
7047 int forward = (compl_first_match->cp_cpt_source_idx < 0);
7048
7049 compl_direction = forward ? FORWARD : BACKWARD;
7050 compl_shows_dir = compl_direction;
Girish Palyacbe53192025-04-14 22:13:15 +02007051
7052 // Identify the sublist of old matches that needs removal
7053 for (current = compl_first_match; current != NULL; current = current->cp_next)
7054 {
Girish Palya0ac1eb32025-04-16 20:18:33 +02007055 if (current->cp_cpt_source_idx < cpt_sources_index &&
7056 (forward || (!forward && !insert_at)))
Girish Palyacbe53192025-04-14 22:13:15 +02007057 insert_at = current;
7058
Girish Palya0ac1eb32025-04-16 20:18:33 +02007059 if (current->cp_cpt_source_idx == cpt_sources_index)
Girish Palyacbe53192025-04-14 22:13:15 +02007060 {
7061 if (!sublist_start)
7062 sublist_start = current;
7063 sublist_end = current;
7064 if (!compl_shown_removed && compl_shown_match == current)
7065 compl_shown_removed = TRUE;
7066 }
7067
Girish Palya0ac1eb32025-04-16 20:18:33 +02007068 if ((forward && current->cp_cpt_source_idx > cpt_sources_index)
7069 || (!forward && insert_at))
Girish Palyacbe53192025-04-14 22:13:15 +02007070 break;
7071 }
7072
7073 // Re-assign compl_shown_match if necessary
7074 if (compl_shown_removed)
7075 {
7076 if (forward)
7077 compl_shown_match = compl_first_match;
7078 else
7079 { // Last node will have the prefix that is being completed
Girish Palya0ac1eb32025-04-16 20:18:33 +02007080 for (current = compl_first_match; current->cp_next != NULL;
7081 current = current->cp_next)
Girish Palyacbe53192025-04-14 22:13:15 +02007082 ;
7083 compl_shown_match = current;
7084 }
7085 }
7086
7087 if (!sublist_start) // No nodes to remove
7088 return insert_at;
7089
7090 // Update links to remove sublist
7091 if (sublist_start->cp_prev)
7092 sublist_start->cp_prev->cp_next = sublist_end->cp_next;
7093 else
7094 compl_first_match = sublist_end->cp_next;
7095
7096 if (sublist_end->cp_next)
7097 sublist_end->cp_next->cp_prev = sublist_start->cp_prev;
7098
7099 // Free all nodes in the sublist
7100 sublist_end->cp_next = NULL;
7101 for (current = sublist_start; current != NULL; current = next)
7102 {
7103 next = current->cp_next;
7104 ins_compl_item_free(current);
7105 }
7106
7107 return insert_at;
7108}
7109#endif
7110
7111/*
7112 * Retrieve completion matches using the callback function "cb" and store the
7113 * 'refresh:always' flag.
7114 */
7115#ifdef FEAT_COMPL_FUNC
7116 static void
Girish Palyaba11e782025-07-05 16:11:44 +02007117get_cpt_func_completion_matches(callback_T *cb UNUSED)
Girish Palyacbe53192025-04-14 22:13:15 +02007118{
Girish Palya98c29db2025-06-01 19:40:00 +02007119 int startcol = cpt_sources_array[cpt_sources_index].cs_startcol;
Girish Palya98c29db2025-06-01 19:40:00 +02007120
7121 if (startcol == -2 || startcol == -3)
7122 return;
7123
Girish Palyaba11e782025-07-05 16:11:44 +02007124 if (set_compl_globals(startcol, curwin->w_cursor.col, TRUE) == OK)
Girish Palyacbe53192025-04-14 22:13:15 +02007125 {
7126 expand_by_function(0, cpt_compl_pattern.string, cb);
Girish Palya98c29db2025-06-01 19:40:00 +02007127 cpt_sources_array[cpt_sources_index].cs_refresh_always =
Girish Palya0ac1eb32025-04-16 20:18:33 +02007128 compl_opt_refresh_always;
Girish Palyacbe53192025-04-14 22:13:15 +02007129 compl_opt_refresh_always = FALSE;
7130 }
7131}
7132#endif
7133
7134/*
7135 * Retrieve completion matches from functions in the 'cpt' option where the
7136 * 'refresh:always' flag is set.
7137 */
7138 static void
7139cpt_compl_refresh(void)
7140{
7141#ifdef FEAT_COMPL_FUNC
7142 char_u *cpt;
7143 char_u *p;
Christian Brabandtd2079cf2025-04-15 18:10:26 +02007144 callback_T *cb = NULL;
Girish Palya98c29db2025-06-01 19:40:00 +02007145 int startcol, ret;
Girish Palyacbe53192025-04-14 22:13:15 +02007146
7147 // Make the completion list linear (non-cyclic)
7148 ins_compl_make_linear();
7149 // Make a copy of 'cpt' in case the buffer gets wiped out
7150 cpt = vim_strsave(curbuf->b_p_cpt);
Girish Palya0ac1eb32025-04-16 20:18:33 +02007151 strip_caret_numbers_in_place(cpt);
Girish Palyacbe53192025-04-14 22:13:15 +02007152
Girish Palya0ac1eb32025-04-16 20:18:33 +02007153 cpt_sources_index = 0;
Girish Palya7c621052025-05-26 19:41:59 +02007154 for (p = cpt; *p;)
Girish Palyacbe53192025-04-14 22:13:15 +02007155 {
7156 while (*p == ',' || *p == ' ') // Skip delimiters
7157 p++;
Girish Palyaba11e782025-07-05 16:11:44 +02007158 if (*p == NUL)
7159 break;
Girish Palyacbe53192025-04-14 22:13:15 +02007160
Girish Palya98c29db2025-06-01 19:40:00 +02007161 if (cpt_sources_array[cpt_sources_index].cs_refresh_always)
Girish Palyacbe53192025-04-14 22:13:15 +02007162 {
Girish Palya98c29db2025-06-01 19:40:00 +02007163 cb = get_callback_if_cpt_func(p);
Girish Palyacbe53192025-04-14 22:13:15 +02007164 if (cb)
7165 {
7166 compl_curr_match = remove_old_matches();
Girish Palya98c29db2025-06-01 19:40:00 +02007167 ret = get_userdefined_compl_info(curwin->w_cursor.col, cb,
7168 &startcol);
7169 if (ret == FAIL)
7170 {
7171 if (startcol == -3)
7172 cpt_sources_array[cpt_sources_index].cs_refresh_always
7173 = FALSE;
7174 else
7175 startcol = -2;
7176 }
7177 cpt_sources_array[cpt_sources_index].cs_startcol = startcol;
7178 if (ret == OK)
Girish Palyaba11e782025-07-05 16:11:44 +02007179 get_cpt_func_completion_matches(cb);
Girish Palyacbe53192025-04-14 22:13:15 +02007180 }
Girish Palyaba11e782025-07-05 16:11:44 +02007181 else
7182 cpt_sources_array[cpt_sources_index].cs_startcol
7183 = STARTCOL_NONE;
Girish Palyacbe53192025-04-14 22:13:15 +02007184 }
7185
Girish Palya7c621052025-05-26 19:41:59 +02007186 (void)copy_option_part(&p, IObuff, IOSIZE, ","); // Advance p
7187 if (may_advance_cpt_index(p))
7188 (void)advance_cpt_sources_index_safe();
Girish Palyacbe53192025-04-14 22:13:15 +02007189 }
Girish Palya0ac1eb32025-04-16 20:18:33 +02007190 cpt_sources_index = -1;
Girish Palyacbe53192025-04-14 22:13:15 +02007191
7192 vim_free(cpt);
7193 // Make the list cyclic
7194 compl_matches = ins_compl_make_cyclic();
7195#endif
7196}