blob: aecbf77b463d4e29295fc51c3d1cd8688453e4bc [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
zeertzjqdca29d92021-08-31 19:12:51 +020040# define CTRL_X_CMDLINE_CTRL_X 17 // CTRL-X typed in CTRL_X_CMDLINE
Bram Moolenaar7591bb32019-03-30 13:53:47 +010041
42# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
43
44// Message for CTRL-X mode, index is ctrl_x_mode.
45static char *ctrl_x_msgs[] =
46{
47 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
48 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
49 NULL, // CTRL_X_SCROLL: depends on state
50 N_(" Whole line completion (^L^N^P)"),
51 N_(" File name completion (^F^N^P)"),
52 N_(" Tag completion (^]^N^P)"),
53 N_(" Path pattern completion (^N^P)"),
54 N_(" Definition completion (^D^N^P)"),
55 NULL, // CTRL_X_FINISHED
56 N_(" Dictionary completion (^K^N^P)"),
57 N_(" Thesaurus completion (^T^N^P)"),
58 N_(" Command-line completion (^V^N^P)"),
59 N_(" User defined completion (^U^N^P)"),
60 N_(" Omni completion (^O^N^P)"),
61 N_(" Spelling suggestion (s^N^P)"),
62 N_(" Keyword Local completion (^N^P)"),
63 NULL, // CTRL_X_EVAL doesn't use msg.
zeertzjqdca29d92021-08-31 19:12:51 +020064 N_(" Command-line completion (^V^N^P)"),
Bram Moolenaar7591bb32019-03-30 13:53:47 +010065};
66
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020067#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010068static char *ctrl_x_mode_names[] = {
69 "keyword",
70 "ctrl_x",
zeertzjq27fef592021-10-03 12:01:27 +010071 "scroll",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010072 "whole_line",
73 "files",
74 "tags",
75 "path_patterns",
76 "path_defines",
77 "unknown", // CTRL_X_FINISHED
78 "dictionary",
79 "thesaurus",
80 "cmdline",
81 "function",
82 "omni",
83 "spell",
84 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
zeertzjqdca29d92021-08-31 19:12:51 +020085 "eval",
86 "cmdline",
Bram Moolenaar7591bb32019-03-30 13:53:47 +010087};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020088#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010089
90/*
91 * Array indexes used for cp_text[].
92 */
93#define CPT_ABBR 0 // "abbr"
94#define CPT_MENU 1 // "menu"
95#define CPT_KIND 2 // "kind"
96#define CPT_INFO 3 // "info"
Bram Moolenaar08928322020-01-04 14:32:48 +010097#define CPT_COUNT 4 // Number of entries
Bram Moolenaar7591bb32019-03-30 13:53:47 +010098
99/*
100 * Structure used to store one match for insert completion.
101 */
102typedef struct compl_S compl_T;
103struct compl_S
104{
105 compl_T *cp_next;
106 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200107 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200108 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100109#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100110 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100111#endif
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200112 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113 // cp_flags has CP_FREE_FNAME
114 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200115 int cp_number; // sequence number
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
126static char e_hitend[] = N_("Hit end of paragraph");
127# ifdef FEAT_COMPL_FUNC
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100128static char e_compldel[] = N_("E840: Completion function deleted text");
129# endif
130
131/*
132 * All the current matches are stored in a list.
133 * "compl_first_match" points to the start of the list.
134 * "compl_curr_match" points to the currently selected entry.
135 * "compl_shown_match" is different from compl_curr_match during
136 * ins_compl_get_exp().
137 */
138static compl_T *compl_first_match = NULL;
139static compl_T *compl_curr_match = NULL;
140static compl_T *compl_shown_match = NULL;
141static compl_T *compl_old_match = NULL;
142
143// After using a cursor key <Enter> selects a match in the popup menu,
144// otherwise it inserts a line break.
145static int compl_enter_selects = FALSE;
146
147// When "compl_leader" is not NULL only matches that start with this string
148// are used.
149static char_u *compl_leader = NULL;
150
151static int compl_get_longest = FALSE; // put longest common string
152 // in compl_leader
153
154static int compl_no_insert = FALSE; // FALSE: select & insert
155 // TRUE: noinsert
156static int compl_no_select = FALSE; // FALSE: select & insert
157 // TRUE: noselect
158
159// Selected one of the matches. When FALSE the match was edited or using the
160// longest common string.
161static int compl_used_match;
162
163// didn't finish finding completions.
164static int compl_was_interrupted = FALSE;
165
166// Set when character typed while looking for matches and it means we should
167// stop looking for matches.
168static int compl_interrupted = FALSE;
169
170static int compl_restarting = FALSE; // don't insert match
171
172// When the first completion is done "compl_started" is set. When it's
173// FALSE the word to be completed must be located.
174static int compl_started = FALSE;
175
176// Which Ctrl-X mode are we in?
177static int ctrl_x_mode = CTRL_X_NORMAL;
178
179static int compl_matches = 0;
180static char_u *compl_pattern = NULL;
181static int compl_direction = FORWARD;
182static int compl_shows_dir = FORWARD;
183static int compl_pending = 0; // > 1 for postponed CTRL-N
184static pos_T compl_startpos;
185static colnr_T compl_col = 0; // column where the text starts
186 // that is being completed
187static char_u *compl_orig_text = NULL; // text as it was before
188 // completion started
189static int compl_cont_mode = 0;
190static expand_T compl_xp;
191
192static int compl_opt_refresh_always = FALSE;
193static int compl_opt_suppress_empty = FALSE;
194
Bram Moolenaar08928322020-01-04 14:32:48 +0100195static 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);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100196static void ins_compl_longest_match(compl_T *match);
197static void ins_compl_del_pum(void);
198static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
199static char_u *find_line_end(char_u *ptr);
200static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100201static int ins_compl_need_restart(void);
202static void ins_compl_new_leader(void);
203static int ins_compl_len(void);
204static void ins_compl_restart(void);
205static void ins_compl_set_original_text(char_u *str);
206static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
207# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
208static void ins_compl_add_list(list_T *list);
209static void ins_compl_add_dict(dict_T *dict);
210# endif
211static int ins_compl_key2dir(int c);
212static int ins_compl_pum_key(int c);
213static int ins_compl_key2count(int c);
214static void show_pum(int prev_w_wrow, int prev_w_leftcol);
215static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100216
217#ifdef FEAT_SPELL
218static void spell_back_to_badword(void);
219static int spell_bad_len = 0; // length of located bad word
220#endif
221
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100222/*
223 * CTRL-X pressed in Insert mode.
224 */
225 void
226ins_ctrl_x(void)
227{
zeertzjqdca29d92021-08-31 19:12:51 +0200228 if (!ctrl_x_mode_cmdline())
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100229 {
230 // if the next ^X<> won't ADD nothing, then reset
231 // compl_cont_status
232 if (compl_cont_status & CONT_N_ADDS)
233 compl_cont_status |= CONT_INTRPT;
234 else
235 compl_cont_status = 0;
236 // We're not sure which CTRL-X mode it will be yet
237 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
238 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
239 edit_submode_pre = NULL;
240 showmode();
241 }
zeertzjqdca29d92021-08-31 19:12:51 +0200242 else
243 // CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X
244 // CTRL-V look like CTRL-N
245 ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X;
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +0100246
247 trigger_modechanged();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100248}
249
250/*
251 * Functions to check the current CTRL-X mode.
252 */
253int ctrl_x_mode_none(void) { return ctrl_x_mode == 0; }
254int ctrl_x_mode_normal(void) { return ctrl_x_mode == CTRL_X_NORMAL; }
255int ctrl_x_mode_scroll(void) { return ctrl_x_mode == CTRL_X_SCROLL; }
256int ctrl_x_mode_whole_line(void) { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
257int ctrl_x_mode_files(void) { return ctrl_x_mode == CTRL_X_FILES; }
258int ctrl_x_mode_tags(void) { return ctrl_x_mode == CTRL_X_TAGS; }
259int ctrl_x_mode_path_patterns(void) {
260 return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
261int ctrl_x_mode_path_defines(void) {
262 return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
263int ctrl_x_mode_dictionary(void) { return ctrl_x_mode == CTRL_X_DICTIONARY; }
264int ctrl_x_mode_thesaurus(void) { return ctrl_x_mode == CTRL_X_THESAURUS; }
zeertzjqdca29d92021-08-31 19:12:51 +0200265int ctrl_x_mode_cmdline(void) {
266 return ctrl_x_mode == CTRL_X_CMDLINE
267 || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X; }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100268int ctrl_x_mode_function(void) { return ctrl_x_mode == CTRL_X_FUNCTION; }
269int ctrl_x_mode_omni(void) { return ctrl_x_mode == CTRL_X_OMNI; }
270int ctrl_x_mode_spell(void) { return ctrl_x_mode == CTRL_X_SPELL; }
271int ctrl_x_mode_line_or_eval(void) {
272 return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
273
274/*
275 * Whether other than default completion has been selected.
276 */
277 int
278ctrl_x_mode_not_default(void)
279{
280 return ctrl_x_mode != CTRL_X_NORMAL;
281}
282
283/*
zeertzjqdca29d92021-08-31 19:12:51 +0200284 * Whether CTRL-X was typed without a following character,
285 * not including when in CTRL-X CTRL-V mode.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100286 */
287 int
288ctrl_x_mode_not_defined_yet(void)
289{
290 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
291}
292
293/*
294 * Return TRUE if the 'dict' or 'tsr' option can be used.
295 */
296 int
297has_compl_option(int dict_opt)
298{
299 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200300#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200302#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100303 )
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100304 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL
305#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +0100306 && *curbuf->b_p_tsrfu == NUL && *p_tsrfu == NUL
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +0100307#endif
308 ))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100309 {
310 ctrl_x_mode = CTRL_X_NORMAL;
311 edit_submode = NULL;
312 msg_attr(dict_opt ? _("'dictionary' option is empty")
313 : _("'thesaurus' option is empty"),
314 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100315 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100316 {
317 vim_beep(BO_COMPL);
318 setcursor();
319 out_flush();
320#ifdef FEAT_EVAL
321 if (!get_vim_var_nr(VV_TESTING))
322#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100323 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100324 }
325 return FALSE;
326 }
327 return TRUE;
328}
329
330/*
331 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
332 * This depends on the current mode.
333 */
334 int
335vim_is_ctrl_x_key(int c)
336{
337 // Always allow ^R - let its results then be checked
338 if (c == Ctrl_R)
339 return TRUE;
340
341 // Accept <PageUp> and <PageDown> if the popup menu is visible.
342 if (ins_compl_pum_key(c))
343 return TRUE;
344
345 switch (ctrl_x_mode)
346 {
347 case 0: // Not in any CTRL-X mode
348 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
349 case CTRL_X_NOT_DEFINED_YET:
zeertzjqdca29d92021-08-31 19:12:51 +0200350 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100351 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
352 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
353 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
354 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
355 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
zeertzjqdca29d92021-08-31 19:12:51 +0200356 || c == Ctrl_S || c == Ctrl_K || c == 's'
357 || c == Ctrl_Z);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100358 case CTRL_X_SCROLL:
359 return (c == Ctrl_Y || c == Ctrl_E);
360 case CTRL_X_WHOLE_LINE:
361 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
362 case CTRL_X_FILES:
363 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
364 case CTRL_X_DICTIONARY:
365 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
366 case CTRL_X_THESAURUS:
367 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
368 case CTRL_X_TAGS:
369 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
370#ifdef FEAT_FIND_ID
371 case CTRL_X_PATH_PATTERNS:
372 return (c == Ctrl_P || c == Ctrl_N);
373 case CTRL_X_PATH_DEFINES:
374 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
375#endif
376 case CTRL_X_CMDLINE:
377 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
378 || c == Ctrl_X);
379#ifdef FEAT_COMPL_FUNC
380 case CTRL_X_FUNCTION:
381 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
382 case CTRL_X_OMNI:
383 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
384#endif
385 case CTRL_X_SPELL:
386 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
387 case CTRL_X_EVAL:
388 return (c == Ctrl_P || c == Ctrl_N);
389 }
390 internal_error("vim_is_ctrl_x_key()");
391 return FALSE;
392}
393
394/*
395 * Return TRUE when character "c" is part of the item currently being
396 * completed. Used to decide whether to abandon complete mode when the menu
397 * is visible.
398 */
399 int
400ins_compl_accept_char(int c)
401{
402 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
403 // When expanding an identifier only accept identifier chars.
404 return vim_isIDc(c);
405
406 switch (ctrl_x_mode)
407 {
408 case CTRL_X_FILES:
409 // When expanding file name only accept file name chars. But not
410 // path separators, so that "proto/<Tab>" expands files in
411 // "proto", not "proto/" as a whole
412 return vim_isfilec(c) && !vim_ispathsep(c);
413
414 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +0200415 case CTRL_X_CMDLINE_CTRL_X:
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100416 case CTRL_X_OMNI:
417 // Command line and Omni completion can work with just about any
418 // printable character, but do stop at white space.
419 return vim_isprintc(c) && !VIM_ISWHITE(c);
420
421 case CTRL_X_WHOLE_LINE:
422 // For while line completion a space can be part of the line.
423 return vim_isprintc(c);
424 }
425 return vim_iswordc(c);
426}
427
428/*
429 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
430 * case of the originally typed text is used, and the case of the completed
431 * text is inferred, ie this tries to work out what case you probably wanted
432 * the rest of the word to be in -- webb
433 */
434 int
435ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200436 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100437 int len,
438 int icase,
439 char_u *fname,
440 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200441 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100442{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200443 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100444 char_u *p;
445 int i, c;
446 int actual_len; // Take multi-byte characters
447 int actual_compl_length; // into account.
448 int min_len;
449 int *wca; // Wide character array.
450 int has_lower = FALSE;
451 int was_letter = FALSE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200452 int flags = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100453
454 if (p_ic && curbuf->b_p_inf && len > 0)
455 {
456 // Infer case of completed part.
457
458 // Find actual length of completion.
459 if (has_mbyte)
460 {
461 p = str;
462 actual_len = 0;
463 while (*p != NUL)
464 {
465 MB_PTR_ADV(p);
466 ++actual_len;
467 }
468 }
469 else
470 actual_len = len;
471
472 // Find actual length of original text.
473 if (has_mbyte)
474 {
475 p = compl_orig_text;
476 actual_compl_length = 0;
477 while (*p != NUL)
478 {
479 MB_PTR_ADV(p);
480 ++actual_compl_length;
481 }
482 }
483 else
484 actual_compl_length = compl_length;
485
486 // "actual_len" may be smaller than "actual_compl_length" when using
487 // thesaurus, only use the minimum when comparing.
488 min_len = actual_len < actual_compl_length
489 ? actual_len : actual_compl_length;
490
491 // Allocate wide character array for the completion and fill it.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200492 wca = ALLOC_MULT(int, actual_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100493 if (wca != NULL)
494 {
495 p = str;
496 for (i = 0; i < actual_len; ++i)
497 if (has_mbyte)
498 wca[i] = mb_ptr2char_adv(&p);
499 else
500 wca[i] = *(p++);
501
502 // Rule 1: Were any chars converted to lower?
503 p = compl_orig_text;
504 for (i = 0; i < min_len; ++i)
505 {
506 if (has_mbyte)
507 c = mb_ptr2char_adv(&p);
508 else
509 c = *(p++);
510 if (MB_ISLOWER(c))
511 {
512 has_lower = TRUE;
513 if (MB_ISUPPER(wca[i]))
514 {
515 // Rule 1 is satisfied.
516 for (i = actual_compl_length; i < actual_len; ++i)
517 wca[i] = MB_TOLOWER(wca[i]);
518 break;
519 }
520 }
521 }
522
523 // Rule 2: No lower case, 2nd consecutive letter converted to
524 // upper case.
525 if (!has_lower)
526 {
527 p = compl_orig_text;
528 for (i = 0; i < min_len; ++i)
529 {
530 if (has_mbyte)
531 c = mb_ptr2char_adv(&p);
532 else
533 c = *(p++);
534 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
535 {
536 // Rule 2 is satisfied.
537 for (i = actual_compl_length; i < actual_len; ++i)
538 wca[i] = MB_TOUPPER(wca[i]);
539 break;
540 }
541 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
542 }
543 }
544
545 // Copy the original case of the part we typed.
546 p = compl_orig_text;
547 for (i = 0; i < min_len; ++i)
548 {
549 if (has_mbyte)
550 c = mb_ptr2char_adv(&p);
551 else
552 c = *(p++);
553 if (MB_ISLOWER(c))
554 wca[i] = MB_TOLOWER(wca[i]);
555 else if (MB_ISUPPER(c))
556 wca[i] = MB_TOUPPER(wca[i]);
557 }
558
559 // Generate encoding specific output from wide character array.
560 // Multi-byte characters can occupy up to five bytes more than
561 // ASCII characters, and we also need one byte for NUL, so stay
562 // six bytes away from the edge of IObuff.
563 p = IObuff;
564 i = 0;
565 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
566 if (has_mbyte)
567 p += (*mb_char2bytes)(wca[i++], p);
568 else
569 *(p++) = wca[i++];
570 *p = NUL;
571
572 vim_free(wca);
573 }
574
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200575 str = IObuff;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100576 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200577 if (cont_s_ipos)
578 flags |= CP_CONT_S_IPOS;
579 if (icase)
580 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200581
Bram Moolenaar08928322020-01-04 14:32:48 +0100582 return ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100583}
584
585/*
586 * Add a match to the list of matches.
587 * If the given string is already in the list of completions, then return
588 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
589 * maybe because alloc() returns NULL, then FAIL is returned.
590 */
591 static int
592ins_compl_add(
593 char_u *str,
594 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100595 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100596 char_u **cptext, // extra text for popup menu or NULL
597 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100598 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200599 int flags_arg,
Bram Moolenaar08928322020-01-04 14:32:48 +0100600 int adup) // accept duplicate match
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100601{
602 compl_T *match;
603 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200604 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100605
Bram Moolenaarceb06192021-04-04 15:05:22 +0200606 if (flags & CP_FAST)
607 fast_breakcheck();
608 else
609 ui_breakcheck();
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100610 if (got_int)
611 return FAIL;
612 if (len < 0)
613 len = (int)STRLEN(str);
614
615 // If the same match is already present, don't add it.
616 if (compl_first_match != NULL && !adup)
617 {
618 match = compl_first_match;
619 do
620 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200621 if ( !(match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100622 && STRNCMP(match->cp_str, str, len) == 0
623 && match->cp_str[len] == NUL)
624 return NOTDONE;
625 match = match->cp_next;
626 } while (match != NULL && match != compl_first_match);
627 }
628
629 // Remove any popup menu before changing the list of matches.
630 ins_compl_del_pum();
631
632 // Allocate a new match structure.
633 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200634 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100635 if (match == NULL)
636 return FAIL;
637 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200638 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100639 match->cp_number = 0;
640 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
641 {
642 vim_free(match);
643 return FAIL;
644 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100645
646 // match-fname is:
647 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200648 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100649 // - NULL otherwise. --Acevedo
650 if (fname != NULL
651 && compl_curr_match != NULL
652 && compl_curr_match->cp_fname != NULL
653 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
654 match->cp_fname = compl_curr_match->cp_fname;
655 else if (fname != NULL)
656 {
657 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200658 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100659 }
660 else
661 match->cp_fname = NULL;
662 match->cp_flags = flags;
663
664 if (cptext != NULL)
665 {
666 int i;
667
668 for (i = 0; i < CPT_COUNT; ++i)
669 if (cptext[i] != NULL && *cptext[i] != NUL)
670 match->cp_text[i] = vim_strsave(cptext[i]);
671 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100672#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100673 if (user_data != NULL)
674 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100675#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100676
677 // Link the new match structure in the list of matches.
678 if (compl_first_match == NULL)
679 match->cp_next = match->cp_prev = NULL;
680 else if (dir == FORWARD)
681 {
682 match->cp_next = compl_curr_match->cp_next;
683 match->cp_prev = compl_curr_match;
684 }
685 else // BACKWARD
686 {
687 match->cp_next = compl_curr_match;
688 match->cp_prev = compl_curr_match->cp_prev;
689 }
690 if (match->cp_next)
691 match->cp_next->cp_prev = match;
692 if (match->cp_prev)
693 match->cp_prev->cp_next = match;
694 else // if there's nothing before, it is the first match
695 compl_first_match = match;
696 compl_curr_match = match;
697
698 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200699 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100700 ins_compl_longest_match(match);
701
702 return OK;
703}
704
705/*
706 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200707 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100708 */
709 static int
710ins_compl_equal(compl_T *match, char_u *str, int len)
711{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200712 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200713 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200714 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100715 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
716 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
717}
718
719/*
720 * Reduce the longest common string for match "match".
721 */
722 static void
723ins_compl_longest_match(compl_T *match)
724{
725 char_u *p, *s;
726 int c1, c2;
727 int had_match;
728
729 if (compl_leader == NULL)
730 {
731 // First match, use it as a whole.
732 compl_leader = vim_strsave(match->cp_str);
733 if (compl_leader != NULL)
734 {
735 had_match = (curwin->w_cursor.col > compl_col);
736 ins_compl_delete();
737 ins_bytes(compl_leader + ins_compl_len());
738 ins_redraw(FALSE);
739
740 // When the match isn't there (to avoid matching itself) remove it
741 // again after redrawing.
742 if (!had_match)
743 ins_compl_delete();
744 compl_used_match = FALSE;
745 }
746 }
747 else
748 {
749 // Reduce the text if this match differs from compl_leader.
750 p = compl_leader;
751 s = match->cp_str;
752 while (*p != NUL)
753 {
754 if (has_mbyte)
755 {
756 c1 = mb_ptr2char(p);
757 c2 = mb_ptr2char(s);
758 }
759 else
760 {
761 c1 = *p;
762 c2 = *s;
763 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200764 if ((match->cp_flags & CP_ICASE)
765 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100766 break;
767 if (has_mbyte)
768 {
769 MB_PTR_ADV(p);
770 MB_PTR_ADV(s);
771 }
772 else
773 {
774 ++p;
775 ++s;
776 }
777 }
778
779 if (*p != NUL)
780 {
781 // Leader was shortened, need to change the inserted text.
782 *p = NUL;
783 had_match = (curwin->w_cursor.col > compl_col);
784 ins_compl_delete();
785 ins_bytes(compl_leader + ins_compl_len());
786 ins_redraw(FALSE);
787
788 // When the match isn't there (to avoid matching itself) remove it
789 // again after redrawing.
790 if (!had_match)
791 ins_compl_delete();
792 }
793
794 compl_used_match = FALSE;
795 }
796}
797
798/*
799 * Add an array of matches to the list of matches.
800 * Frees matches[].
801 */
802 static void
803ins_compl_add_matches(
804 int num_matches,
805 char_u **matches,
806 int icase)
807{
808 int i;
809 int add_r = OK;
810 int dir = compl_direction;
811
812 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100813 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
Bram Moolenaar440cf092021-04-03 20:13:30 +0200814 CP_FAST | (icase ? CP_ICASE : 0), FALSE)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100815 // if dir was BACKWARD then honor it just once
816 dir = FORWARD;
817 FreeWild(num_matches, matches);
818}
819
820/*
821 * Make the completion list cyclic.
822 * Return the number of matches (excluding the original).
823 */
824 static int
825ins_compl_make_cyclic(void)
826{
827 compl_T *match;
828 int count = 0;
829
830 if (compl_first_match != NULL)
831 {
832 // Find the end of the list.
833 match = compl_first_match;
834 // there's always an entry for the compl_orig_text, it doesn't count.
835 while (match->cp_next != NULL && match->cp_next != compl_first_match)
836 {
837 match = match->cp_next;
838 ++count;
839 }
840 match->cp_next = compl_first_match;
841 compl_first_match->cp_prev = match;
842 }
843 return count;
844}
845
846/*
847 * Return whether there currently is a shown match.
848 */
849 int
850ins_compl_has_shown_match(void)
851{
852 return compl_shown_match == NULL
853 || compl_shown_match != compl_shown_match->cp_next;
854}
855
856/*
857 * Return whether the shown match is long enough.
858 */
859 int
860ins_compl_long_shown_match(void)
861{
862 return (int)STRLEN(compl_shown_match->cp_str)
863 > curwin->w_cursor.col - compl_col;
864}
865
866/*
867 * Set variables that store noselect and noinsert behavior from the
868 * 'completeopt' value.
869 */
870 void
871completeopt_was_set(void)
872{
873 compl_no_insert = FALSE;
874 compl_no_select = FALSE;
875 if (strstr((char *)p_cot, "noselect") != NULL)
876 compl_no_select = TRUE;
877 if (strstr((char *)p_cot, "noinsert") != NULL)
878 compl_no_insert = TRUE;
879}
880
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100881
882// "compl_match_array" points the currently displayed list of entries in the
883// popup menu. It is NULL when there is no popup menu.
884static pumitem_T *compl_match_array = NULL;
885static int compl_match_arraysize;
886
887/*
888 * Update the screen and when there is any scrolling remove the popup menu.
889 */
890 static void
891ins_compl_upd_pum(void)
892{
893 int h;
894
895 if (compl_match_array != NULL)
896 {
897 h = curwin->w_cline_height;
898 // Update the screen later, before drawing the popup menu over it.
899 pum_call_update_screen();
900 if (h != curwin->w_cline_height)
901 ins_compl_del_pum();
902 }
903}
904
905/*
906 * Remove any popup menu.
907 */
908 static void
909ins_compl_del_pum(void)
910{
911 if (compl_match_array != NULL)
912 {
913 pum_undisplay();
914 VIM_CLEAR(compl_match_array);
915 }
916}
917
918/*
919 * Return TRUE if the popup menu should be displayed.
920 */
921 int
922pum_wanted(void)
923{
924 // 'completeopt' must contain "menu" or "menuone"
925 if (vim_strchr(p_cot, 'm') == NULL)
926 return FALSE;
927
928 // The display looks bad on a B&W display.
929 if (t_colors < 8
930#ifdef FEAT_GUI
931 && !gui.in_use
932#endif
933 )
934 return FALSE;
935 return TRUE;
936}
937
938/*
939 * Return TRUE if there are two or more matches to be shown in the popup menu.
940 * One if 'completopt' contains "menuone".
941 */
942 static int
943pum_enough_matches(void)
944{
945 compl_T *compl;
946 int i;
947
948 // Don't display the popup menu if there are no matches or there is only
949 // one (ignoring the original text).
950 compl = compl_first_match;
951 i = 0;
952 do
953 {
954 if (compl == NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200955 || ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0 && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100956 break;
957 compl = compl->cp_next;
958 } while (compl != compl_first_match);
959
960 if (strstr((char *)p_cot, "menuone") != NULL)
961 return (i >= 1);
962 return (i >= 2);
963}
964
Bram Moolenaar3075a452021-11-17 15:51:52 +0000965#if defined(FEAT_EVAL) || defined(PROTO)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200966/*
967 * Allocate Dict for the completed item.
968 * { word, abbr, menu, kind, info }
969 */
970 static dict_T *
971ins_compl_dict_alloc(compl_T *match)
972{
973 dict_T *dict = dict_alloc_lock(VAR_FIXED);
974
975 if (dict != NULL)
976 {
977 dict_add_string(dict, "word", match->cp_str);
978 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
979 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
980 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
981 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
Bram Moolenaar08928322020-01-04 14:32:48 +0100982 if (match->cp_user_data.v_type == VAR_UNKNOWN)
983 dict_add_string(dict, "user_data", (char_u *)"");
984 else
985 dict_add_tv(dict, "user_data", &match->cp_user_data);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200986 }
987 return dict;
988}
989
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200990 static void
991trigger_complete_changed_event(int cur)
992{
993 dict_T *v_event;
994 dict_T *item;
995 static int recursive = FALSE;
Bram Moolenaar3075a452021-11-17 15:51:52 +0000996 save_v_event_T save_v_event;
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200997
998 if (recursive)
999 return;
1000
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001001 if (cur < 0)
1002 item = dict_alloc();
1003 else
1004 item = ins_compl_dict_alloc(compl_curr_match);
1005 if (item == NULL)
1006 return;
Bram Moolenaar3075a452021-11-17 15:51:52 +00001007 v_event = get_v_event(&save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001008 dict_add_dict(v_event, "completed_item", item);
1009 pum_set_event_info(v_event);
1010 dict_set_items_ro(v_event);
1011
1012 recursive = TRUE;
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001013 textwinlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001014 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001015 textwinlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001016 recursive = FALSE;
1017
Bram Moolenaar3075a452021-11-17 15:51:52 +00001018 restore_v_event(v_event, &save_v_event);
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001019}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001020#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001021
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001022/*
1023 * Show the popup menu for the list of matches.
1024 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1025 */
1026 void
1027ins_compl_show_pum(void)
1028{
1029 compl_T *compl;
1030 compl_T *shown_compl = NULL;
1031 int did_find_shown_match = FALSE;
1032 int shown_match_ok = FALSE;
1033 int i;
1034 int cur = -1;
1035 colnr_T col;
1036 int lead_len = 0;
1037
1038 if (!pum_wanted() || !pum_enough_matches())
1039 return;
1040
1041#if defined(FEAT_EVAL)
1042 // Dirty hard-coded hack: remove any matchparen highlighting.
Bram Moolenaar179eb562020-12-27 18:03:22 +01001043 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|:3match none|endif");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001044#endif
1045
1046 // Update the screen later, before drawing the popup menu over it.
1047 pum_call_update_screen();
1048
1049 if (compl_match_array == NULL)
1050 {
1051 // Need to build the popup menu list.
1052 compl_match_arraysize = 0;
1053 compl = compl_first_match;
1054 if (compl_leader != NULL)
1055 lead_len = (int)STRLEN(compl_leader);
1056 do
1057 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001058 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001059 && (compl_leader == NULL
1060 || ins_compl_equal(compl, compl_leader, lead_len)))
1061 ++compl_match_arraysize;
1062 compl = compl->cp_next;
1063 } while (compl != NULL && compl != compl_first_match);
1064 if (compl_match_arraysize == 0)
1065 return;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001066 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001067 if (compl_match_array != NULL)
1068 {
1069 // If the current match is the original text don't find the first
1070 // match after it, don't highlight anything.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001071 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001072 shown_match_ok = TRUE;
1073
1074 i = 0;
1075 compl = compl_first_match;
1076 do
1077 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001078 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001079 && (compl_leader == NULL
1080 || ins_compl_equal(compl, compl_leader, lead_len)))
1081 {
1082 if (!shown_match_ok)
1083 {
1084 if (compl == compl_shown_match || did_find_shown_match)
1085 {
1086 // This item is the shown match or this is the
1087 // first displayed item after the shown match.
1088 compl_shown_match = compl;
1089 did_find_shown_match = TRUE;
1090 shown_match_ok = TRUE;
1091 }
1092 else
1093 // Remember this displayed match for when the
1094 // shown match is just below it.
1095 shown_compl = compl;
1096 cur = i;
1097 }
1098
1099 if (compl->cp_text[CPT_ABBR] != NULL)
1100 compl_match_array[i].pum_text =
1101 compl->cp_text[CPT_ABBR];
1102 else
1103 compl_match_array[i].pum_text = compl->cp_str;
1104 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1105 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1106 if (compl->cp_text[CPT_MENU] != NULL)
1107 compl_match_array[i++].pum_extra =
1108 compl->cp_text[CPT_MENU];
1109 else
1110 compl_match_array[i++].pum_extra = compl->cp_fname;
1111 }
1112
1113 if (compl == compl_shown_match)
1114 {
1115 did_find_shown_match = TRUE;
1116
1117 // When the original text is the shown match don't set
1118 // compl_shown_match.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001119 if (compl->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001120 shown_match_ok = TRUE;
1121
1122 if (!shown_match_ok && shown_compl != NULL)
1123 {
1124 // The shown match isn't displayed, set it to the
1125 // previously displayed match.
1126 compl_shown_match = shown_compl;
1127 shown_match_ok = TRUE;
1128 }
1129 }
1130 compl = compl->cp_next;
1131 } while (compl != NULL && compl != compl_first_match);
1132
1133 if (!shown_match_ok) // no displayed match at all
1134 cur = -1;
1135 }
1136 }
1137 else
1138 {
1139 // popup menu already exists, only need to find the current item.
1140 for (i = 0; i < compl_match_arraysize; ++i)
1141 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1142 || compl_match_array[i].pum_text
1143 == compl_shown_match->cp_text[CPT_ABBR])
1144 {
1145 cur = i;
1146 break;
1147 }
1148 }
1149
1150 if (compl_match_array != NULL)
1151 {
1152 // In Replace mode when a $ is displayed at the end of the line only
1153 // part of the screen would be updated. We do need to redraw here.
1154 dollar_vcol = -1;
1155
1156 // Compute the screen column of the start of the completed text.
1157 // Use the cursor to get all wrapping and other settings right.
1158 col = curwin->w_cursor.col;
1159 curwin->w_cursor.col = compl_col;
1160 pum_display(compl_match_array, compl_match_arraysize, cur);
1161 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001162
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001163#ifdef FEAT_EVAL
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001164 if (has_completechanged())
1165 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001166#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001167 }
1168}
1169
1170#define DICT_FIRST (1) // use just first element in "dict"
1171#define DICT_EXACT (2) // "dict" is the exact name of a file
1172
1173/*
1174 * Add any identifiers that match the given pattern in the list of dictionary
1175 * files "dict_start" to the list of completions.
1176 */
1177 static void
1178ins_compl_dictionaries(
1179 char_u *dict_start,
1180 char_u *pat,
1181 int flags, // DICT_FIRST and/or DICT_EXACT
1182 int thesaurus) // Thesaurus completion
1183{
1184 char_u *dict = dict_start;
1185 char_u *ptr;
1186 char_u *buf;
1187 regmatch_T regmatch;
1188 char_u **files;
1189 int count;
1190 int save_p_scs;
1191 int dir = compl_direction;
1192
1193 if (*dict == NUL)
1194 {
1195#ifdef FEAT_SPELL
1196 // When 'dictionary' is empty and spell checking is enabled use
1197 // "spell".
1198 if (!thesaurus && curwin->w_p_spell)
1199 dict = (char_u *)"spell";
1200 else
1201#endif
1202 return;
1203 }
1204
1205 buf = alloc(LSIZE);
1206 if (buf == NULL)
1207 return;
1208 regmatch.regprog = NULL; // so that we can goto theend
1209
1210 // If 'infercase' is set, don't use 'smartcase' here
1211 save_p_scs = p_scs;
1212 if (curbuf->b_p_inf)
1213 p_scs = FALSE;
1214
1215 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1216 // to only match at the start of a line. Otherwise just match the
1217 // pattern. Also need to double backslashes.
1218 if (ctrl_x_mode_line_or_eval())
1219 {
1220 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1221 size_t len;
1222
1223 if (pat_esc == NULL)
1224 goto theend;
1225 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001226 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001227 if (ptr == NULL)
1228 {
1229 vim_free(pat_esc);
1230 goto theend;
1231 }
1232 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1233 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1234 vim_free(pat_esc);
1235 vim_free(ptr);
1236 }
1237 else
1238 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001239 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001240 if (regmatch.regprog == NULL)
1241 goto theend;
1242 }
1243
1244 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1245 regmatch.rm_ic = ignorecase(pat);
1246 while (*dict != NUL && !got_int && !compl_interrupted)
1247 {
1248 // copy one dictionary file name into buf
1249 if (flags == DICT_EXACT)
1250 {
1251 count = 1;
1252 files = &dict;
1253 }
1254 else
1255 {
1256 // Expand wildcards in the dictionary name, but do not allow
1257 // backticks (for security, the 'dict' option may have been set in
1258 // a modeline).
1259 copy_option_part(&dict, buf, LSIZE, ",");
1260# ifdef FEAT_SPELL
1261 if (!thesaurus && STRCMP(buf, "spell") == 0)
1262 count = -1;
1263 else
1264# endif
1265 if (vim_strchr(buf, '`') != NULL
1266 || expand_wildcards(1, &buf, &count, &files,
1267 EW_FILE|EW_SILENT) != OK)
1268 count = 0;
1269 }
1270
1271# ifdef FEAT_SPELL
1272 if (count == -1)
1273 {
1274 // Complete from active spelling. Skip "\<" in the pattern, we
1275 // don't use it as a RE.
1276 if (pat[0] == '\\' && pat[1] == '<')
1277 ptr = pat + 2;
1278 else
1279 ptr = pat;
1280 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1281 }
1282 else
1283# endif
1284 if (count > 0) // avoid warning for using "files" uninit
1285 {
1286 ins_compl_files(count, files, thesaurus, flags,
1287 &regmatch, buf, &dir);
1288 if (flags != DICT_EXACT)
1289 FreeWild(count, files);
1290 }
1291 if (flags != 0)
1292 break;
1293 }
1294
1295theend:
1296 p_scs = save_p_scs;
1297 vim_regfree(regmatch.regprog);
1298 vim_free(buf);
1299}
1300
1301 static void
1302ins_compl_files(
1303 int count,
1304 char_u **files,
1305 int thesaurus,
1306 int flags,
1307 regmatch_T *regmatch,
1308 char_u *buf,
1309 int *dir)
1310{
1311 char_u *ptr;
1312 int i;
1313 FILE *fp;
1314 int add_r;
1315
1316 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1317 {
1318 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
1319 if (flags != DICT_EXACT)
1320 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001321 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001322 vim_snprintf((char *)IObuff, IOSIZE,
1323 _("Scanning dictionary: %s"), (char *)files[i]);
1324 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1325 }
1326
1327 if (fp != NULL)
1328 {
1329 // Read dictionary file line by line.
1330 // Check each line for a match.
1331 while (!got_int && !compl_interrupted
1332 && !vim_fgets(buf, LSIZE, fp))
1333 {
1334 ptr = buf;
1335 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
1336 {
1337 ptr = regmatch->startp[0];
1338 if (ctrl_x_mode_line_or_eval())
1339 ptr = find_line_end(ptr);
1340 else
1341 ptr = find_word_end(ptr);
1342 add_r = ins_compl_add_infercase(regmatch->startp[0],
1343 (int)(ptr - regmatch->startp[0]),
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001344 p_ic, files[i], *dir, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001345 if (thesaurus)
1346 {
1347 char_u *wstart;
1348
1349 // Add the other matches on the line
1350 ptr = buf;
1351 while (!got_int)
1352 {
1353 // Find start of the next word. Skip white
1354 // space and punctuation.
1355 ptr = find_word_start(ptr);
1356 if (*ptr == NUL || *ptr == NL)
1357 break;
1358 wstart = ptr;
1359
1360 // Find end of the word.
1361 if (has_mbyte)
1362 // Japanese words may have characters in
1363 // different classes, only separate words
1364 // with single-byte non-word characters.
1365 while (*ptr != NUL)
1366 {
1367 int l = (*mb_ptr2len)(ptr);
1368
1369 if (l < 2 && !vim_iswordc(*ptr))
1370 break;
1371 ptr += l;
1372 }
1373 else
1374 ptr = find_word_end(ptr);
1375
1376 // Add the word. Skip the regexp match.
1377 if (wstart != regmatch->startp[0])
1378 add_r = ins_compl_add_infercase(wstart,
1379 (int)(ptr - wstart),
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001380 p_ic, files[i], *dir, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001381 }
1382 }
1383 if (add_r == OK)
1384 // if dir was BACKWARD then honor it just once
1385 *dir = FORWARD;
1386 else if (add_r == FAIL)
1387 break;
1388 // avoid expensive call to vim_regexec() when at end
1389 // of line
1390 if (*ptr == '\n' || got_int)
1391 break;
1392 }
1393 line_breakcheck();
1394 ins_compl_check_keys(50, FALSE);
1395 }
1396 fclose(fp);
1397 }
1398 }
1399}
1400
1401/*
1402 * Find the start of the next word.
1403 * Returns a pointer to the first char of the word. Also stops at a NUL.
1404 */
1405 char_u *
1406find_word_start(char_u *ptr)
1407{
1408 if (has_mbyte)
1409 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1410 ptr += (*mb_ptr2len)(ptr);
1411 else
1412 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1413 ++ptr;
1414 return ptr;
1415}
1416
1417/*
1418 * Find the end of the word. Assumes it starts inside a word.
1419 * Returns a pointer to just after the word.
1420 */
1421 char_u *
1422find_word_end(char_u *ptr)
1423{
1424 int start_class;
1425
1426 if (has_mbyte)
1427 {
1428 start_class = mb_get_class(ptr);
1429 if (start_class > 1)
1430 while (*ptr != NUL)
1431 {
1432 ptr += (*mb_ptr2len)(ptr);
1433 if (mb_get_class(ptr) != start_class)
1434 break;
1435 }
1436 }
1437 else
1438 while (vim_iswordc(*ptr))
1439 ++ptr;
1440 return ptr;
1441}
1442
1443/*
1444 * Find the end of the line, omitting CR and NL at the end.
1445 * Returns a pointer to just after the line.
1446 */
1447 static char_u *
1448find_line_end(char_u *ptr)
1449{
1450 char_u *s;
1451
1452 s = ptr + STRLEN(ptr);
1453 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1454 --s;
1455 return s;
1456}
1457
1458/*
1459 * Free the list of completions
1460 */
1461 static void
1462ins_compl_free(void)
1463{
1464 compl_T *match;
1465 int i;
1466
1467 VIM_CLEAR(compl_pattern);
1468 VIM_CLEAR(compl_leader);
1469
1470 if (compl_first_match == NULL)
1471 return;
1472
1473 ins_compl_del_pum();
1474 pum_clear();
1475
1476 compl_curr_match = compl_first_match;
1477 do
1478 {
1479 match = compl_curr_match;
1480 compl_curr_match = compl_curr_match->cp_next;
1481 vim_free(match->cp_str);
1482 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001483 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001484 vim_free(match->cp_fname);
1485 for (i = 0; i < CPT_COUNT; ++i)
1486 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001487#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001488 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001489#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001490 vim_free(match);
1491 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
1492 compl_first_match = compl_curr_match = NULL;
1493 compl_shown_match = NULL;
1494 compl_old_match = NULL;
1495}
1496
1497 void
1498ins_compl_clear(void)
1499{
1500 compl_cont_status = 0;
1501 compl_started = FALSE;
1502 compl_matches = 0;
1503 VIM_CLEAR(compl_pattern);
1504 VIM_CLEAR(compl_leader);
1505 edit_submode_extra = NULL;
1506 VIM_CLEAR(compl_orig_text);
1507 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001508#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001509 // clear v:completed_item
1510 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001511#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001512}
1513
1514/*
1515 * Return TRUE when Insert completion is active.
1516 */
1517 int
1518ins_compl_active(void)
1519{
1520 return compl_started;
1521}
1522
1523/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001524 * Selected one of the matches. When FALSE the match was edited or using the
1525 * longest common string.
1526 */
1527 int
1528ins_compl_used_match(void)
1529{
1530 return compl_used_match;
1531}
1532
1533/*
1534 * Initialize get longest common string.
1535 */
1536 void
1537ins_compl_init_get_longest(void)
1538{
1539 compl_get_longest = FALSE;
1540}
1541
1542/*
1543 * Returns TRUE when insert completion is interrupted.
1544 */
1545 int
1546ins_compl_interrupted(void)
1547{
1548 return compl_interrupted;
1549}
1550
1551/*
1552 * Returns TRUE if the <Enter> key selects a match in the completion popup
1553 * menu.
1554 */
1555 int
1556ins_compl_enter_selects(void)
1557{
1558 return compl_enter_selects;
1559}
1560
1561/*
1562 * Return the column where the text starts that is being completed
1563 */
1564 colnr_T
1565ins_compl_col(void)
1566{
1567 return compl_col;
1568}
1569
1570/*
1571 * Delete one character before the cursor and show the subset of the matches
1572 * that match the word that is now before the cursor.
1573 * Returns the character to be used, NUL if the work is done and another char
1574 * to be got from the user.
1575 */
1576 int
1577ins_compl_bs(void)
1578{
1579 char_u *line;
1580 char_u *p;
1581
1582 line = ml_get_curline();
1583 p = line + curwin->w_cursor.col;
1584 MB_PTR_BACK(line, p);
1585
1586 // Stop completion when the whole word was deleted. For Omni completion
1587 // allow the word to be deleted, we won't match everything.
1588 // Respect the 'backspace' option.
1589 if ((int)(p - line) - (int)compl_col < 0
1590 || ((int)(p - line) - (int)compl_col == 0
Bram Moolenaar440cf092021-04-03 20:13:30 +02001591 && ctrl_x_mode != CTRL_X_OMNI)
1592 || ctrl_x_mode == CTRL_X_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001593 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1594 - compl_length < 0))
1595 return K_BS;
1596
1597 // Deleted more than what was used to find matches or didn't finish
1598 // finding all matches: need to look for matches all over again.
1599 if (curwin->w_cursor.col <= compl_col + compl_length
1600 || ins_compl_need_restart())
1601 ins_compl_restart();
1602
1603 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001604 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001605 if (compl_leader != NULL)
1606 {
1607 ins_compl_new_leader();
1608 if (compl_shown_match != NULL)
1609 // Make sure current match is not a hidden item.
1610 compl_curr_match = compl_shown_match;
1611 return NUL;
1612 }
1613 return K_BS;
1614}
1615
1616/*
1617 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1618 * be called.
1619 */
1620 static int
1621ins_compl_need_restart(void)
1622{
1623 // Return TRUE if we didn't complete finding matches or when the
1624 // 'completefunc' returned "always" in the "refresh" dictionary item.
1625 return compl_was_interrupted
1626 || ((ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
1627 && compl_opt_refresh_always);
1628}
1629
1630/*
1631 * Called after changing "compl_leader".
1632 * Show the popup menu with a different set of matches.
1633 * May also search for matches again if the previous search was interrupted.
1634 */
1635 static void
1636ins_compl_new_leader(void)
1637{
1638 ins_compl_del_pum();
1639 ins_compl_delete();
1640 ins_bytes(compl_leader + ins_compl_len());
1641 compl_used_match = FALSE;
1642
1643 if (compl_started)
1644 ins_compl_set_original_text(compl_leader);
1645 else
1646 {
1647#ifdef FEAT_SPELL
1648 spell_bad_len = 0; // need to redetect bad word
1649#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001650 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001651 // the popup menu display the changed text before the cursor. Set
1652 // "compl_restarting" to avoid that the first match is inserted.
1653 pum_call_update_screen();
1654#ifdef FEAT_GUI
1655 if (gui.in_use)
1656 {
1657 // Show the cursor after the match, not after the redrawn text.
1658 setcursor();
1659 out_flush_cursor(FALSE, FALSE);
1660 }
1661#endif
1662 compl_restarting = TRUE;
1663 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1664 compl_cont_status = 0;
1665 compl_restarting = FALSE;
1666 }
1667
1668 compl_enter_selects = !compl_used_match;
1669
1670 // Show the popup menu with a different set of matches.
1671 ins_compl_show_pum();
1672
1673 // Don't let Enter select the original text when there is no popup menu.
1674 if (compl_match_array == NULL)
1675 compl_enter_selects = FALSE;
1676}
1677
1678/*
1679 * Return the length of the completion, from the completion start column to
1680 * the cursor column. Making sure it never goes below zero.
1681 */
1682 static int
1683ins_compl_len(void)
1684{
1685 int off = (int)curwin->w_cursor.col - (int)compl_col;
1686
1687 if (off < 0)
1688 return 0;
1689 return off;
1690}
1691
1692/*
1693 * Append one character to the match leader. May reduce the number of
1694 * matches.
1695 */
1696 void
1697ins_compl_addleader(int c)
1698{
1699 int cc;
1700
1701 if (stop_arrow() == FAIL)
1702 return;
1703 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
1704 {
1705 char_u buf[MB_MAXBYTES + 1];
1706
1707 (*mb_char2bytes)(c, buf);
1708 buf[cc] = NUL;
1709 ins_char_bytes(buf, cc);
1710 if (compl_opt_refresh_always)
1711 AppendToRedobuff(buf);
1712 }
1713 else
1714 {
1715 ins_char(c);
1716 if (compl_opt_refresh_always)
1717 AppendCharToRedobuff(c);
1718 }
1719
1720 // If we didn't complete finding matches we must search again.
1721 if (ins_compl_need_restart())
1722 ins_compl_restart();
1723
1724 // When 'always' is set, don't reset compl_leader. While completing,
1725 // cursor doesn't point original position, changing compl_leader would
1726 // break redo.
1727 if (!compl_opt_refresh_always)
1728 {
1729 vim_free(compl_leader);
1730 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001731 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001732 if (compl_leader != NULL)
1733 ins_compl_new_leader();
1734 }
1735}
1736
1737/*
1738 * Setup for finding completions again without leaving CTRL-X mode. Used when
1739 * BS or a key was typed while still searching for matches.
1740 */
1741 static void
1742ins_compl_restart(void)
1743{
1744 ins_compl_free();
1745 compl_started = FALSE;
1746 compl_matches = 0;
1747 compl_cont_status = 0;
1748 compl_cont_mode = 0;
1749}
1750
1751/*
1752 * Set the first match, the original text.
1753 */
1754 static void
1755ins_compl_set_original_text(char_u *str)
1756{
1757 char_u *p;
1758
1759 // Replace the original text entry.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001760 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly be
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001761 // at the last item for backward completion
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001762 if (compl_first_match->cp_flags & CP_ORIGINAL_TEXT) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001763 {
1764 p = vim_strsave(str);
1765 if (p != NULL)
1766 {
1767 vim_free(compl_first_match->cp_str);
1768 compl_first_match->cp_str = p;
1769 }
1770 }
1771 else if (compl_first_match->cp_prev != NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001772 && (compl_first_match->cp_prev->cp_flags & CP_ORIGINAL_TEXT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001773 {
1774 p = vim_strsave(str);
1775 if (p != NULL)
1776 {
1777 vim_free(compl_first_match->cp_prev->cp_str);
1778 compl_first_match->cp_prev->cp_str = p;
1779 }
1780 }
1781}
1782
1783/*
1784 * Append one character to the match leader. May reduce the number of
1785 * matches.
1786 */
1787 void
1788ins_compl_addfrommatch(void)
1789{
1790 char_u *p;
1791 int len = (int)curwin->w_cursor.col - (int)compl_col;
1792 int c;
1793 compl_T *cp;
1794
1795 p = compl_shown_match->cp_str;
1796 if ((int)STRLEN(p) <= len) // the match is too short
1797 {
1798 // When still at the original match use the first entry that matches
1799 // the leader.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001800 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001801 {
1802 p = NULL;
1803 for (cp = compl_shown_match->cp_next; cp != NULL
1804 && cp != compl_first_match; cp = cp->cp_next)
1805 {
1806 if (compl_leader == NULL
1807 || ins_compl_equal(cp, compl_leader,
1808 (int)STRLEN(compl_leader)))
1809 {
1810 p = cp->cp_str;
1811 break;
1812 }
1813 }
1814 if (p == NULL || (int)STRLEN(p) <= len)
1815 return;
1816 }
1817 else
1818 return;
1819 }
1820 p += len;
1821 c = PTR2CHAR(p);
1822 ins_compl_addleader(c);
1823}
1824
1825/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00001826 * Set the CTRL-X completion mode based on the key 'c' typed after a CTRL-X.
1827 * Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre,
1828 * compl_cont_mode and compl_cont_status.
1829 * Returns TRUE when the character is not to be inserted.
1830 */
1831 static int
1832set_ctrl_x_mode(int c)
1833{
1834 int retval = FALSE;
1835
1836 switch (c)
1837 {
1838 case Ctrl_E:
1839 case Ctrl_Y:
1840 // scroll the window one line up or down
1841 ctrl_x_mode = CTRL_X_SCROLL;
1842 if (!(State & REPLACE_FLAG))
1843 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
1844 else
1845 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
1846 edit_submode_pre = NULL;
1847 showmode();
1848 break;
1849 case Ctrl_L:
1850 // complete whole line
1851 ctrl_x_mode = CTRL_X_WHOLE_LINE;
1852 break;
1853 case Ctrl_F:
1854 // complete filenames
1855 ctrl_x_mode = CTRL_X_FILES;
1856 break;
1857 case Ctrl_K:
1858 // complete words from a dictinoary
1859 ctrl_x_mode = CTRL_X_DICTIONARY;
1860 break;
1861 case Ctrl_R:
1862 // Register insertion without exiting CTRL-X mode
1863 // Simply allow ^R to happen without affecting ^X mode
1864 break;
1865 case Ctrl_T:
1866 // complete words from a thesaurus
1867 ctrl_x_mode = CTRL_X_THESAURUS;
1868 break;
1869#ifdef FEAT_COMPL_FUNC
1870 case Ctrl_U:
1871 // user defined completion
1872 ctrl_x_mode = CTRL_X_FUNCTION;
1873 break;
1874 case Ctrl_O:
1875 // omni completion
1876 ctrl_x_mode = CTRL_X_OMNI;
1877 break;
1878#endif
1879 case 's':
1880 case Ctrl_S:
1881 // complete spelling suggestions
1882 ctrl_x_mode = CTRL_X_SPELL;
1883#ifdef FEAT_SPELL
1884 ++emsg_off; // Avoid getting the E756 error twice.
1885 spell_back_to_badword();
1886 --emsg_off;
1887#endif
1888 break;
1889 case Ctrl_RSB:
1890 // complete tag names
1891 ctrl_x_mode = CTRL_X_TAGS;
1892 break;
1893#ifdef FEAT_FIND_ID
1894 case Ctrl_I:
1895 case K_S_TAB:
1896 // complete keywords from included files
1897 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
1898 break;
1899 case Ctrl_D:
1900 // complete definitions from included files
1901 ctrl_x_mode = CTRL_X_PATH_DEFINES;
1902 break;
1903#endif
1904 case Ctrl_V:
1905 case Ctrl_Q:
1906 // complete vim commands
1907 ctrl_x_mode = CTRL_X_CMDLINE;
1908 break;
1909 case Ctrl_Z:
1910 // stop completion
1911 ctrl_x_mode = CTRL_X_NORMAL;
1912 edit_submode = NULL;
1913 showmode();
1914 retval = TRUE;
1915 break;
1916 case Ctrl_P:
1917 case Ctrl_N:
1918 // ^X^P means LOCAL expansion if nothing interrupted (eg we
1919 // just started ^X mode, or there were enough ^X's to cancel
1920 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
1921 // do normal expansion when interrupting a different mode (say
1922 // ^X^F^X^P or ^P^X^X^P, see below)
1923 // nothing changes if interrupting mode 0, (eg, the flag
1924 // doesn't change when going to ADDING mode -- Acevedo
1925 if (!(compl_cont_status & CONT_INTRPT))
1926 compl_cont_status |= CONT_LOCAL;
1927 else if (compl_cont_mode != 0)
1928 compl_cont_status &= ~CONT_LOCAL;
1929 // FALLTHROUGH
1930 default:
1931 // If we have typed at least 2 ^X's... for modes != 0, we set
1932 // compl_cont_status = 0 (eg, as if we had just started ^X
1933 // mode).
1934 // For mode 0, we set "compl_cont_mode" to an impossible
1935 // value, in both cases ^X^X can be used to restart the same
1936 // mode (avoiding ADDING mode).
1937 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
1938 // 'complete' and local ^P expansions respectively.
1939 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
1940 // mode -- Acevedo
1941 if (c == Ctrl_X)
1942 {
1943 if (compl_cont_mode != 0)
1944 compl_cont_status = 0;
1945 else
1946 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
1947 }
1948 ctrl_x_mode = CTRL_X_NORMAL;
1949 edit_submode = NULL;
1950 showmode();
1951 break;
1952 }
1953
1954 return retval;
1955}
1956
1957/*
1958 * Stop insert completion mode
1959 */
1960 static int
1961ins_compl_stop(int c, int prev_mode, int retval)
1962{
1963 char_u *ptr;
1964#ifdef FEAT_CINDENT
1965 int want_cindent;
1966#endif
1967
1968 // Get here when we have finished typing a sequence of ^N and
1969 // ^P or other completion characters in CTRL-X mode. Free up
1970 // memory that was used, and make sure we can redo the insert.
1971 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
1972 {
1973 // If any of the original typed text has been changed, eg when
1974 // ignorecase is set, we must add back-spaces to the redo
1975 // buffer. We add as few as necessary to delete just the part
1976 // of the original text that has changed.
1977 // When using the longest match, edited the match or used
1978 // CTRL-E then don't use the current match.
1979 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
1980 ptr = compl_curr_match->cp_str;
1981 else
1982 ptr = NULL;
1983 ins_compl_fixRedoBufForLeader(ptr);
1984 }
1985
1986#ifdef FEAT_CINDENT
1987 want_cindent = (get_can_cindent() && cindent_on());
1988#endif
1989 // When completing whole lines: fix indent for 'cindent'.
1990 // Otherwise, break line if it's too long.
1991 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
1992 {
1993#ifdef FEAT_CINDENT
1994 // re-indent the current line
1995 if (want_cindent)
1996 {
1997 do_c_expr_indent();
1998 want_cindent = FALSE; // don't do it again
1999 }
2000#endif
2001 }
2002 else
2003 {
2004 int prev_col = curwin->w_cursor.col;
2005
2006 // put the cursor on the last char, for 'tw' formatting
2007 if (prev_col > 0)
2008 dec_cursor();
2009 // only format when something was inserted
2010 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2011 insertchar(NUL, 0, -1);
2012 if (prev_col > 0
2013 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2014 inc_cursor();
2015 }
2016
2017 // If the popup menu is displayed pressing CTRL-Y means accepting
2018 // the selection without inserting anything. When
2019 // compl_enter_selects is set the Enter key does the same.
2020 if ((c == Ctrl_Y || (compl_enter_selects
2021 && (c == CAR || c == K_KENTER || c == NL)))
2022 && pum_visible())
2023 retval = TRUE;
2024
2025 // CTRL-E means completion is Ended, go back to the typed text.
2026 // but only do this, if the Popup is still visible
2027 if (c == Ctrl_E)
2028 {
2029 ins_compl_delete();
2030 if (compl_leader != NULL)
2031 ins_bytes(compl_leader + ins_compl_len());
2032 else if (compl_first_match != NULL)
2033 ins_bytes(compl_orig_text + ins_compl_len());
2034 retval = TRUE;
2035 }
2036
2037 auto_format(FALSE, TRUE);
2038
2039 // Trigger the CompleteDonePre event to give scripts a chance to
2040 // act upon the completion before clearing the info, and restore
2041 // ctrl_x_mode, so that complete_info() can be used.
2042 ctrl_x_mode = prev_mode;
2043 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
2044
2045 ins_compl_free();
2046 compl_started = FALSE;
2047 compl_matches = 0;
2048 if (!shortmess(SHM_COMPLETIONMENU))
2049 msg_clr_cmdline(); // necessary for "noshowmode"
2050 ctrl_x_mode = CTRL_X_NORMAL;
2051 compl_enter_selects = FALSE;
2052 if (edit_submode != NULL)
2053 {
2054 edit_submode = NULL;
2055 showmode();
2056 }
2057
2058#ifdef FEAT_CMDWIN
2059 if (c == Ctrl_C && cmdwin_type != 0)
2060 // Avoid the popup menu remains displayed when leaving the
2061 // command line window.
2062 update_screen(0);
2063#endif
2064#ifdef FEAT_CINDENT
2065 // Indent now if a key was typed that is in 'cinkeys'.
2066 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2067 do_c_expr_indent();
2068#endif
2069 // Trigger the CompleteDone event to give scripts a chance to act
2070 // upon the end of completion.
2071 ins_apply_autocmds(EVENT_COMPLETEDONE);
2072
2073 return retval;
2074}
2075
2076/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002077 * Prepare for Insert mode completion, or stop it.
2078 * Called just after typing a character in Insert mode.
2079 * Returns TRUE when the character is not to be inserted;
2080 */
2081 int
2082ins_compl_prep(int c)
2083{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002084 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01002085 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002086
2087 // Forget any previous 'special' messages if this is actually
2088 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
2089 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
2090 edit_submode_extra = NULL;
2091
2092 // Ignore end of Select mode mapping and mouse scroll buttons.
2093 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
Bram Moolenaar957cf672020-11-12 14:21:06 +01002094 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002095 return retval;
2096
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01002097#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02002098 // Ignore mouse events in a popup window
2099 if (is_mouse_key(c))
2100 {
2101 // Ignore drag and release events, the position does not need to be in
2102 // the popup and it may have just closed.
2103 if (c == K_LEFTRELEASE
2104 || c == K_LEFTRELEASE_NM
2105 || c == K_MIDDLERELEASE
2106 || c == K_RIGHTRELEASE
2107 || c == K_X1RELEASE
2108 || c == K_X2RELEASE
2109 || c == K_LEFTDRAG
2110 || c == K_MIDDLEDRAG
2111 || c == K_RIGHTDRAG
2112 || c == K_X1DRAG
2113 || c == K_X2DRAG)
2114 return retval;
2115 if (popup_visible)
2116 {
2117 int row = mouse_row;
2118 int col = mouse_col;
2119 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
2120
2121 if (wp != NULL && WIN_IS_POPUP(wp))
2122 return retval;
2123 }
2124 }
2125#endif
2126
zeertzjqdca29d92021-08-31 19:12:51 +02002127 if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X)
2128 {
2129 if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key(c)
2130 || !vim_is_ctrl_x_key(c))
2131 {
2132 // Not starting another completion mode.
2133 ctrl_x_mode = CTRL_X_CMDLINE;
2134
2135 // CTRL-X CTRL-Z should stop completion without inserting anything
2136 if (c == Ctrl_Z)
2137 retval = TRUE;
2138 }
2139 else
2140 {
2141 ctrl_x_mode = CTRL_X_CMDLINE;
2142
2143 // Other CTRL-X keys first stop completion, then start another
2144 // completion mode.
2145 ins_compl_prep(' ');
2146 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
2147 }
2148 }
2149
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002150 // Set "compl_get_longest" when finding the first matches.
2151 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
2152 || (ctrl_x_mode == CTRL_X_NORMAL && !compl_started))
2153 {
2154 compl_get_longest = (strstr((char *)p_cot, "longest") != NULL);
2155 compl_used_match = TRUE;
2156
2157 }
2158
2159 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002160 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
2161 // it will be yet. Now we decide.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002162 retval = set_ctrl_x_mode(c);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002163 else if (ctrl_x_mode != CTRL_X_NORMAL)
2164 {
2165 // We're already in CTRL-X mode, do we stay in it?
2166 if (!vim_is_ctrl_x_key(c))
2167 {
2168 if (ctrl_x_mode == CTRL_X_SCROLL)
2169 ctrl_x_mode = CTRL_X_NORMAL;
2170 else
2171 ctrl_x_mode = CTRL_X_FINISHED;
2172 edit_submode = NULL;
2173 }
2174 showmode();
2175 }
2176
2177 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
2178 {
2179 // Show error message from attempted keyword completion (probably
2180 // 'Pattern not found') until another key is hit, then go back to
2181 // showing what mode we are in.
2182 showmode();
2183 if ((ctrl_x_mode == CTRL_X_NORMAL && c != Ctrl_N && c != Ctrl_P
2184 && c != Ctrl_R && !ins_compl_pum_key(c))
2185 || ctrl_x_mode == CTRL_X_FINISHED)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00002186 retval = ins_compl_stop(c, prev_mode, retval);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002187 }
2188 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2189 // Trigger the CompleteDone event to give scripts a chance to act
2190 // upon the (possibly failed) completion.
2191 ins_apply_autocmds(EVENT_COMPLETEDONE);
2192
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002193 trigger_modechanged();
2194
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002195 // reset continue_* if we left expansion-mode, if we stay they'll be
2196 // (re)set properly in ins_complete()
2197 if (!vim_is_ctrl_x_key(c))
2198 {
2199 compl_cont_status = 0;
2200 compl_cont_mode = 0;
2201 }
2202
2203 return retval;
2204}
2205
2206/*
2207 * Fix the redo buffer for the completion leader replacing some of the typed
2208 * text. This inserts backspaces and appends the changed text.
2209 * "ptr" is the known leader text or NUL.
2210 */
2211 static void
2212ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2213{
2214 int len;
2215 char_u *p;
2216 char_u *ptr = ptr_arg;
2217
2218 if (ptr == NULL)
2219 {
2220 if (compl_leader != NULL)
2221 ptr = compl_leader;
2222 else
2223 return; // nothing to do
2224 }
2225 if (compl_orig_text != NULL)
2226 {
2227 p = compl_orig_text;
2228 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2229 ;
2230 if (len > 0)
2231 len -= (*mb_head_off)(p, p + len);
2232 for (p += len; *p != NUL; MB_PTR_ADV(p))
2233 AppendCharToRedobuff(K_BS);
2234 }
2235 else
2236 len = 0;
2237 if (ptr != NULL)
2238 AppendToRedobuffLit(ptr + len, -1);
2239}
2240
2241/*
2242 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2243 * (depending on flag) starting from buf and looking for a non-scanned
2244 * buffer (other than curbuf). curbuf is special, if it is called with
2245 * buf=curbuf then it has to be the first call for a given flag/expansion.
2246 *
2247 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2248 */
2249 static buf_T *
2250ins_compl_next_buf(buf_T *buf, int flag)
2251{
2252 static win_T *wp = NULL;
2253
2254 if (flag == 'w') // just windows
2255 {
2256 if (buf == curbuf || wp == NULL) // first call for this flag/expansion
2257 wp = curwin;
2258 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2259 && wp->w_buffer->b_scanned)
2260 ;
2261 buf = wp->w_buffer;
2262 }
2263 else
2264 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2265 // (unlisted buffers)
2266 // When completing whole lines skip unloaded buffers.
2267 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2268 && ((flag == 'U'
2269 ? buf->b_p_bl
2270 : (!buf->b_p_bl
2271 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2272 || buf->b_scanned))
2273 ;
2274 return buf;
2275}
2276
2277#ifdef FEAT_COMPL_FUNC
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002278
2279# ifdef FEAT_EVAL
2280static callback_T cfu_cb; // 'completefunc' callback function
2281static callback_T ofu_cb; // 'omnifunc' callback function
2282static callback_T tsrfu_cb; // 'thesaurusfunc' callback function
2283# endif
2284
2285/*
2286 * Copy a global callback function to a buffer local callback.
2287 */
2288 static void
2289copy_global_to_buflocal_cb(callback_T *globcb, callback_T *bufcb)
2290{
2291 free_callback(bufcb);
2292 if (globcb->cb_name != NULL && *globcb->cb_name != NUL)
2293 copy_callback(bufcb, globcb);
2294}
2295
2296/*
2297 * Parse the 'completefunc' option value and set the callback function.
2298 * Invoked when the 'completefunc' option is set. The option value can be a
2299 * name of a function (string), or function(<name>) or funcref(<name>) or a
2300 * lambda expression.
2301 */
2302 int
2303set_completefunc_option(void)
2304{
2305 int retval;
2306
2307 retval = option_set_callback_func(curbuf->b_p_cfu, &cfu_cb);
2308 if (retval == OK)
2309 set_buflocal_cfu_callback(curbuf);
2310
2311 return retval;
2312}
2313
2314/*
2315 * Copy the global 'completefunc' callback function to the buffer-local
2316 * 'completefunc' callback for 'buf'.
2317 */
2318 void
2319set_buflocal_cfu_callback(buf_T *buf UNUSED)
2320{
2321# ifdef FEAT_EVAL
2322 copy_global_to_buflocal_cb(&cfu_cb, &buf->b_cfu_cb);
2323# endif
2324}
2325
2326/*
2327 * Parse the 'omnifunc' option value and set the callback function.
2328 * Invoked when the 'omnifunc' option is set. The option value can be a
2329 * name of a function (string), or function(<name>) or funcref(<name>) or a
2330 * lambda expression.
2331 */
2332 int
2333set_omnifunc_option(void)
2334{
2335 int retval;
2336
2337 retval = option_set_callback_func(curbuf->b_p_ofu, &ofu_cb);
2338 if (retval == OK)
2339 set_buflocal_ofu_callback(curbuf);
2340
2341 return retval;
2342}
2343
2344/*
2345 * Copy the global 'omnifunc' callback function to the buffer-local 'omnifunc'
2346 * callback for 'buf'.
2347 */
2348 void
2349set_buflocal_ofu_callback(buf_T *buf UNUSED)
2350{
2351# ifdef FEAT_EVAL
2352 copy_global_to_buflocal_cb(&ofu_cb, &buf->b_ofu_cb);
2353# endif
2354}
2355
2356/*
2357 * Parse the 'thesaurusfunc' option value and set the callback function.
2358 * Invoked when the 'thesaurusfunc' option is set. The option value can be a
2359 * name of a function (string), or function(<name>) or funcref(<name>) or a
2360 * lambda expression.
2361 */
2362 int
2363set_thesaurusfunc_option(void)
2364{
2365 int retval;
2366
2367 if (*curbuf->b_p_tsrfu != NUL)
2368 {
2369 // buffer-local option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002370 retval = option_set_callback_func(curbuf->b_p_tsrfu,
2371 &curbuf->b_tsrfu_cb);
2372 }
2373 else
2374 {
2375 // global option set
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002376 retval = option_set_callback_func(p_tsrfu, &tsrfu_cb);
2377 }
2378
2379 return retval;
2380}
2381
Yegappan Lakshmanan6ae8fae2021-12-12 16:26:44 +00002382/*
2383 * Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with
2384 * 'copyID' so that they are not garbage collected.
2385 */
2386 int
2387set_ref_in_insexpand_funcs(int copyID)
2388{
2389 int abort = FALSE;
2390
2391 abort = set_ref_in_callback(&cfu_cb, copyID);
2392 abort = abort || set_ref_in_callback(&ofu_cb, copyID);
2393 abort = abort || set_ref_in_callback(&tsrfu_cb, copyID);
2394
2395 return abort;
2396}
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002397
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002398/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002399 * Get the user-defined completion function name for completion 'type'
2400 */
2401 static char_u *
2402get_complete_funcname(int type)
2403{
2404 switch (type)
2405 {
2406 case CTRL_X_FUNCTION:
2407 return curbuf->b_p_cfu;
2408 case CTRL_X_OMNI:
2409 return curbuf->b_p_ofu;
2410 case CTRL_X_THESAURUS:
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002411 return *curbuf->b_p_tsrfu == NUL ? p_tsrfu : curbuf->b_p_tsrfu;
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002412 default:
2413 return (char_u *)"";
2414 }
2415}
2416
2417/*
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002418 * Get the callback to use for insert mode completion.
2419 */
2420 callback_T *
2421get_insert_callback(int type)
2422{
2423 if (type == CTRL_X_FUNCTION)
2424 return &curbuf->b_cfu_cb;
2425 if (type == CTRL_X_OMNI)
2426 return &curbuf->b_ofu_cb;
2427 // CTRL_X_THESAURUS
2428 return (*curbuf->b_p_tsrfu != NUL) ? &curbuf->b_tsrfu_cb : &tsrfu_cb;
2429}
2430
2431/*
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002432 * Execute user defined complete function 'completefunc', 'omnifunc' or
2433 * 'thesaurusfunc', and get matches in "matches".
2434 * "type" is either CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002435 */
2436 static void
Yegappan Lakshmanan05e59e32021-12-01 10:30:07 +00002437expand_by_function(int type, char_u *base)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002438{
2439 list_T *matchlist = NULL;
2440 dict_T *matchdict = NULL;
2441 typval_T args[3];
2442 char_u *funcname;
2443 pos_T pos;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002444 callback_T *cb;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002445 typval_T rettv;
2446 int save_State = State;
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002447 int retval;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002448
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002449 funcname = get_complete_funcname(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002450 if (*funcname == NUL)
2451 return;
2452
2453 // Call 'completefunc' to obtain the list of matches.
2454 args[0].v_type = VAR_NUMBER;
2455 args[0].vval.v_number = 0;
2456 args[1].v_type = VAR_STRING;
2457 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2458 args[2].v_type = VAR_UNKNOWN;
2459
2460 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002461 // Lock the text to avoid weird things from happening. Also disallow
2462 // switching to another window, it should not be needed and may end up in
2463 // Insert mode in another buffer.
2464 ++textwinlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002465
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002466 cb = get_insert_callback(type);
2467 retval = call_callback(cb, 0, &rettv, 2, args);
2468
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002469 // Call a function, which returns a list or dict.
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00002470 if (retval == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002471 {
2472 switch (rettv.v_type)
2473 {
2474 case VAR_LIST:
2475 matchlist = rettv.vval.v_list;
2476 break;
2477 case VAR_DICT:
2478 matchdict = rettv.vval.v_dict;
2479 break;
2480 case VAR_SPECIAL:
2481 if (rettv.vval.v_number == VVAL_NONE)
2482 compl_opt_suppress_empty = TRUE;
2483 // FALLTHROUGH
2484 default:
2485 // TODO: Give error message?
2486 clear_tv(&rettv);
2487 break;
2488 }
2489 }
Bram Moolenaar28976e22021-01-29 21:07:07 +01002490 --textwinlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002491
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002492 curwin->w_cursor = pos; // restore the cursor position
2493 validate_cursor();
2494 if (!EQUAL_POS(curwin->w_cursor, pos))
2495 {
2496 emsg(_(e_compldel));
2497 goto theend;
2498 }
2499
2500 if (matchlist != NULL)
2501 ins_compl_add_list(matchlist);
2502 else if (matchdict != NULL)
2503 ins_compl_add_dict(matchdict);
2504
2505theend:
2506 // Restore State, it might have been changed.
2507 State = save_State;
2508
2509 if (matchdict != NULL)
2510 dict_unref(matchdict);
2511 if (matchlist != NULL)
2512 list_unref(matchlist);
2513}
2514#endif // FEAT_COMPL_FUNC
2515
2516#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2517/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002518 * Add a match to the list of matches from a typeval_T.
2519 * If the given string is already in the list of completions, then return
2520 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2521 * maybe because alloc() returns NULL, then FAIL is returned.
Bram Moolenaar440cf092021-04-03 20:13:30 +02002522 * When "fast" is TRUE use fast_breakcheck() instead of ui_breakcheck().
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002523 */
2524 static int
Bram Moolenaar440cf092021-04-03 20:13:30 +02002525ins_compl_add_tv(typval_T *tv, int dir, int fast)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002526{
2527 char_u *word;
2528 int dup = FALSE;
2529 int empty = FALSE;
Bram Moolenaar440cf092021-04-03 20:13:30 +02002530 int flags = fast ? CP_FAST : 0;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002531 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002532 typval_T user_data;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002533
Bram Moolenaar08928322020-01-04 14:32:48 +01002534 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002535 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2536 {
2537 word = dict_get_string(tv->vval.v_dict, (char_u *)"word", FALSE);
2538 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict,
2539 (char_u *)"abbr", FALSE);
2540 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict,
2541 (char_u *)"menu", FALSE);
2542 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict,
2543 (char_u *)"kind", FALSE);
2544 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict,
2545 (char_u *)"info", FALSE);
Bram Moolenaar08928322020-01-04 14:32:48 +01002546 dict_get_tv(tv->vval.v_dict, (char_u *)"user_data", &user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002547 if (dict_get_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL
2548 && dict_get_number(tv->vval.v_dict, (char_u *)"icase"))
2549 flags |= CP_ICASE;
2550 if (dict_get_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
2551 dup = dict_get_number(tv->vval.v_dict, (char_u *)"dup");
2552 if (dict_get_string(tv->vval.v_dict, (char_u *)"empty", FALSE) != NULL)
2553 empty = dict_get_number(tv->vval.v_dict, (char_u *)"empty");
2554 if (dict_get_string(tv->vval.v_dict, (char_u *)"equal", FALSE) != NULL
2555 && dict_get_number(tv->vval.v_dict, (char_u *)"equal"))
2556 flags |= CP_EQUAL;
2557 }
2558 else
2559 {
2560 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002561 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002562 }
2563 if (word == NULL || (!empty && *word == NUL))
2564 return FAIL;
Bram Moolenaar08928322020-01-04 14:32:48 +01002565 return ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002566}
2567
2568/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002569 * Add completions from a list.
2570 */
2571 static void
2572ins_compl_add_list(list_T *list)
2573{
2574 listitem_T *li;
2575 int dir = compl_direction;
2576
2577 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002578 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002579 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002580 {
Bram Moolenaar440cf092021-04-03 20:13:30 +02002581 if (ins_compl_add_tv(&li->li_tv, dir, TRUE) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002582 // if dir was BACKWARD then honor it just once
2583 dir = FORWARD;
2584 else if (did_emsg)
2585 break;
2586 }
2587}
2588
2589/*
2590 * Add completions from a dict.
2591 */
2592 static void
2593ins_compl_add_dict(dict_T *dict)
2594{
2595 dictitem_T *di_refresh;
2596 dictitem_T *di_words;
2597
2598 // Check for optional "refresh" item.
2599 compl_opt_refresh_always = FALSE;
2600 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2601 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2602 {
2603 char_u *v = di_refresh->di_tv.vval.v_string;
2604
2605 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2606 compl_opt_refresh_always = TRUE;
2607 }
2608
2609 // Add completions from a "words" list.
2610 di_words = dict_find(dict, (char_u *)"words", 5);
2611 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2612 ins_compl_add_list(di_words->di_tv.vval.v_list);
2613}
2614
2615/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002616 * Start completion for the complete() function.
2617 * "startcol" is where the matched text starts (1 is first column).
2618 * "list" is the list of matches.
2619 */
2620 static void
2621set_completion(colnr_T startcol, list_T *list)
2622{
2623 int save_w_wrow = curwin->w_wrow;
2624 int save_w_leftcol = curwin->w_leftcol;
2625 int flags = CP_ORIGINAL_TEXT;
2626
2627 // If already doing completions stop it.
2628 if (ctrl_x_mode != CTRL_X_NORMAL)
2629 ins_compl_prep(' ');
2630 ins_compl_clear();
2631 ins_compl_free();
2632
2633 compl_direction = FORWARD;
2634 if (startcol > curwin->w_cursor.col)
2635 startcol = curwin->w_cursor.col;
2636 compl_col = startcol;
2637 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2638 // compl_pattern doesn't need to be set
2639 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2640 if (p_ic)
2641 flags |= CP_ICASE;
2642 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar440cf092021-04-03 20:13:30 +02002643 -1, NULL, NULL, NULL, 0,
2644 flags | CP_FAST, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002645 return;
2646
2647 ctrl_x_mode = CTRL_X_EVAL;
2648
2649 ins_compl_add_list(list);
2650 compl_matches = ins_compl_make_cyclic();
2651 compl_started = TRUE;
2652 compl_used_match = TRUE;
2653 compl_cont_status = 0;
2654
2655 compl_curr_match = compl_first_match;
2656 if (compl_no_insert || compl_no_select)
2657 {
2658 ins_complete(K_DOWN, FALSE);
2659 if (compl_no_select)
2660 // Down/Up has no real effect.
2661 ins_complete(K_UP, FALSE);
2662 }
2663 else
2664 ins_complete(Ctrl_N, FALSE);
2665 compl_enter_selects = compl_no_insert;
2666
2667 // Lazily show the popup menu, unless we got interrupted.
2668 if (!compl_interrupted)
2669 show_pum(save_w_wrow, save_w_leftcol);
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01002670 trigger_modechanged();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002671 out_flush();
2672}
2673
2674/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002675 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002676 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002677 void
2678f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002679{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002680 int startcol;
Bram Moolenaarff06f282020-04-21 22:01:14 +02002681 int save_textlock = textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002682
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002683 if (in_vim9script()
2684 && (check_for_number_arg(argvars, 0) == FAIL
2685 || check_for_list_arg(argvars, 1) == FAIL))
2686 return;
2687
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002688 if ((State & INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002689 {
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002690 emsg(_("E785: complete() can only be used in Insert mode"));
2691 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002692 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002693
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02002694 // "textlock" is set when evaluating 'completefunc' but we can change
2695 // text here.
Bram Moolenaarff06f282020-04-21 22:01:14 +02002696 textlock = 0;
2697
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002698 // Check for undo allowed here, because if something was already inserted
2699 // the line was already saved for undo and this check isn't done.
2700 if (!undo_allowed())
2701 return;
2702
2703 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002704 emsg(_(e_invarg));
Bram Moolenaarff06f282020-04-21 22:01:14 +02002705 else
2706 {
2707 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
2708 if (startcol > 0)
2709 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002710 }
Bram Moolenaarff06f282020-04-21 22:01:14 +02002711 textlock = save_textlock;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002712}
2713
2714/*
2715 * "complete_add()" function
2716 */
2717 void
2718f_complete_add(typval_T *argvars, typval_T *rettv)
2719{
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002720 if (in_vim9script() && check_for_string_or_dict_arg(argvars, 0) == FAIL)
Yegappan Lakshmanan83494b42021-07-20 17:51:51 +02002721 return;
2722
Bram Moolenaar440cf092021-04-03 20:13:30 +02002723 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0, FALSE);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002724}
2725
2726/*
2727 * "complete_check()" function
2728 */
2729 void
2730f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
2731{
2732 int saved = RedrawingDisabled;
2733
2734 RedrawingDisabled = 0;
2735 ins_compl_check_keys(0, TRUE);
2736 rettv->vval.v_number = ins_compl_interrupted();
2737 RedrawingDisabled = saved;
2738}
2739
2740/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002741 * Return Insert completion mode name string
2742 */
2743 static char_u *
2744ins_compl_mode(void)
2745{
zeertzjq27fef592021-10-03 12:01:27 +01002746 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || ctrl_x_mode == CTRL_X_SCROLL
2747 || compl_started)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002748 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
2749
2750 return (char_u *)"";
2751}
2752
Bram Moolenaarf9d51352020-10-26 19:22:42 +01002753 static void
2754ins_compl_update_sequence_numbers()
2755{
2756 int number = 0;
2757 compl_T *match;
2758
2759 if (compl_direction == FORWARD)
2760 {
2761 // search backwards for the first valid (!= -1) number.
2762 // This should normally succeed already at the first loop
2763 // cycle, so it's fast!
2764 for (match = compl_curr_match->cp_prev; match != NULL
2765 && match != compl_first_match;
2766 match = match->cp_prev)
2767 if (match->cp_number != -1)
2768 {
2769 number = match->cp_number;
2770 break;
2771 }
2772 if (match != NULL)
2773 // go up and assign all numbers which are not assigned
2774 // yet
2775 for (match = match->cp_next;
2776 match != NULL && match->cp_number == -1;
2777 match = match->cp_next)
2778 match->cp_number = ++number;
2779 }
2780 else // BACKWARD
2781 {
2782 // search forwards (upwards) for the first valid (!= -1)
2783 // number. This should normally succeed already at the
2784 // first loop cycle, so it's fast!
2785 for (match = compl_curr_match->cp_next; match != NULL
2786 && match != compl_first_match;
2787 match = match->cp_next)
2788 if (match->cp_number != -1)
2789 {
2790 number = match->cp_number;
2791 break;
2792 }
2793 if (match != NULL)
2794 // go down and assign all numbers which are not
2795 // assigned yet
2796 for (match = match->cp_prev; match
2797 && match->cp_number == -1;
2798 match = match->cp_prev)
2799 match->cp_number = ++number;
2800 }
2801}
2802
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002803/*
2804 * Get complete information
2805 */
2806 static void
2807get_complete_info(list_T *what_list, dict_T *retdict)
2808{
2809 int ret = OK;
2810 listitem_T *item;
2811#define CI_WHAT_MODE 0x01
2812#define CI_WHAT_PUM_VISIBLE 0x02
2813#define CI_WHAT_ITEMS 0x04
2814#define CI_WHAT_SELECTED 0x08
2815#define CI_WHAT_INSERTED 0x10
2816#define CI_WHAT_ALL 0xff
2817 int what_flag;
2818
2819 if (what_list == NULL)
2820 what_flag = CI_WHAT_ALL;
2821 else
2822 {
2823 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002824 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002825 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002826 {
2827 char_u *what = tv_get_string(&item->li_tv);
2828
2829 if (STRCMP(what, "mode") == 0)
2830 what_flag |= CI_WHAT_MODE;
2831 else if (STRCMP(what, "pum_visible") == 0)
2832 what_flag |= CI_WHAT_PUM_VISIBLE;
2833 else if (STRCMP(what, "items") == 0)
2834 what_flag |= CI_WHAT_ITEMS;
2835 else if (STRCMP(what, "selected") == 0)
2836 what_flag |= CI_WHAT_SELECTED;
2837 else if (STRCMP(what, "inserted") == 0)
2838 what_flag |= CI_WHAT_INSERTED;
2839 }
2840 }
2841
2842 if (ret == OK && (what_flag & CI_WHAT_MODE))
2843 ret = dict_add_string(retdict, "mode", ins_compl_mode());
2844
2845 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
2846 ret = dict_add_number(retdict, "pum_visible", pum_visible());
2847
2848 if (ret == OK && (what_flag & CI_WHAT_ITEMS))
2849 {
2850 list_T *li;
2851 dict_T *di;
2852 compl_T *match;
2853
2854 li = list_alloc();
2855 if (li == NULL)
2856 return;
2857 ret = dict_add_list(retdict, "items", li);
2858 if (ret == OK && compl_first_match != NULL)
2859 {
2860 match = compl_first_match;
2861 do
2862 {
2863 if (!(match->cp_flags & CP_ORIGINAL_TEXT))
2864 {
2865 di = dict_alloc();
2866 if (di == NULL)
2867 return;
2868 ret = list_append_dict(li, di);
2869 if (ret != OK)
2870 return;
2871 dict_add_string(di, "word", match->cp_str);
2872 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
2873 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
2874 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
2875 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002876 if (match->cp_user_data.v_type == VAR_UNKNOWN)
2877 // Add an empty string for backwards compatibility
2878 dict_add_string(di, "user_data", (char_u *)"");
2879 else
2880 dict_add_tv(di, "user_data", &match->cp_user_data);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002881 }
2882 match = match->cp_next;
2883 }
2884 while (match != NULL && match != compl_first_match);
2885 }
2886 }
2887
2888 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
Bram Moolenaarf9d51352020-10-26 19:22:42 +01002889 {
2890 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
2891 ins_compl_update_sequence_numbers();
2892 ret = dict_add_number(retdict, "selected", compl_curr_match != NULL
2893 ? compl_curr_match->cp_number - 1 : -1);
2894 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002895
2896 // TODO
2897 // if (ret == OK && (what_flag & CI_WHAT_INSERTED))
2898}
2899
2900/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002901 * "complete_info()" function
2902 */
2903 void
2904f_complete_info(typval_T *argvars, typval_T *rettv)
2905{
2906 list_T *what_list = NULL;
2907
2908 if (rettv_dict_alloc(rettv) != OK)
2909 return;
2910
Yegappan Lakshmanan4490ec42021-07-27 22:00:44 +02002911 if (in_vim9script() && check_for_opt_list_arg(argvars, 0) == FAIL)
2912 return;
2913
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002914 if (argvars[0].v_type != VAR_UNKNOWN)
2915 {
2916 if (argvars[0].v_type != VAR_LIST)
2917 {
2918 emsg(_(e_listreq));
2919 return;
2920 }
2921 what_list = argvars[0].vval.v_list;
2922 }
2923 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002924}
2925#endif
2926
2927/*
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002928 * Returns TRUE when using a user-defined function for thesaurus completion.
2929 */
2930 static int
2931thesaurus_func_complete(int type UNUSED)
2932{
2933#ifdef FEAT_COMPL_FUNC
Bram Moolenaarf4d8b762021-10-17 14:13:09 +01002934 return type == CTRL_X_THESAURUS
2935 && (*curbuf->b_p_tsrfu != NUL || *p_tsrfu != NUL);
Yegappan Lakshmanan160e9942021-10-16 15:41:29 +01002936#else
2937 return FALSE;
2938#endif
2939}
2940
2941/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00002942 * Return value of process_next_cpt_value()
2943 */
2944enum
2945{
2946 INS_COMPL_CPT_OK = 1,
2947 INS_COMPL_CPT_CONT,
2948 INS_COMPL_CPT_END
2949};
2950
2951/*
2952 * Process the next 'complete' option value in "e_cpt_arg".
2953 *
2954 * If successful, the arguments are set as below:
2955 * e_cpt_arg - pointer to the next option value in 'e_cpt_arg'
2956 * compl_type_arg - type of insert mode completion to use
2957 * found_all_arg - all matches of this type are found
2958 * buf_arg - search for completions in this buffer
2959 * first_match_pos - position of the first completion match
2960 * last_match_pos - position of the last completion match
2961 * set_match_pos - TRUE if the first match position should be saved to avoid
2962 * loops after the search wraps around.
2963 * dict - name of the dictionary or thesaurus file to search
2964 * dict_f - flag specifying whether "dict" is an exact file name or not
2965 *
2966 * Returns INS_COMPL_CPT_OK if the next value is processed successfully.
2967 * Returns INS_COMPL_CPT_CONT to skip the current value and process the next
2968 * option value.
2969 * Returns INS_COMPL_CPT_END if all the values in "e_cpt" are processed.
2970 */
2971 static int
2972process_next_cpt_value(
2973 char_u **e_cpt_arg,
2974 int *compl_type_arg,
2975 int *found_all_arg,
2976 buf_T **buf_arg,
2977 pos_T *start_match_pos,
2978 pos_T *first_match_pos,
2979 pos_T *last_match_pos,
2980 int *set_match_pos,
2981 char_u **dict_arg,
2982 int *dict_flag)
2983{
2984 char_u *e_cpt = *e_cpt_arg;
2985 int compl_type = -1;
2986 int status = INS_COMPL_CPT_OK;
2987 buf_T *buf = *buf_arg;
2988 int found_all = FALSE;
2989 char_u *dict = NULL;
2990 int dict_f = 0;
2991
2992 while (*e_cpt == ',' || *e_cpt == ' ')
2993 e_cpt++;
2994
2995 if (*e_cpt == '.' && !curbuf->b_scanned)
2996 {
2997 buf = curbuf;
2998 *first_match_pos = *start_match_pos;
2999 // Move the cursor back one character so that ^N can match the
3000 // word immediately after the cursor.
3001 if (ctrl_x_mode == CTRL_X_NORMAL && dec(first_match_pos) < 0)
3002 {
3003 // Move the cursor to after the last character in the
3004 // buffer, so that word at start of buffer is found
3005 // correctly.
3006 first_match_pos->lnum = buf->b_ml.ml_line_count;
3007 first_match_pos->col =
3008 (colnr_T)STRLEN(ml_get(first_match_pos->lnum));
3009 }
3010 *last_match_pos = *first_match_pos;
3011 compl_type = 0;
3012
3013 // Remember the first match so that the loop stops when we
3014 // wrap and come back there a second time.
3015 *set_match_pos = TRUE;
3016 }
3017 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
3018 && (buf = ins_compl_next_buf(buf, *e_cpt)) != curbuf)
3019 {
3020 // Scan a buffer, but not the current one.
3021 if (buf->b_ml.ml_mfp != NULL) // loaded buffer
3022 {
3023 compl_started = TRUE;
3024 first_match_pos->col = last_match_pos->col = 0;
3025 first_match_pos->lnum = buf->b_ml.ml_line_count + 1;
3026 last_match_pos->lnum = 0;
3027 compl_type = 0;
3028 }
3029 else // unloaded buffer, scan like dictionary
3030 {
3031 found_all = TRUE;
3032 if (buf->b_fname == NULL)
3033 {
3034 status = INS_COMPL_CPT_CONT;
3035 goto done;
3036 }
3037 compl_type = CTRL_X_DICTIONARY;
3038 dict = buf->b_fname;
3039 dict_f = DICT_EXACT;
3040 }
3041 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3042 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
3043 buf->b_fname == NULL
3044 ? buf_spname(buf)
3045 : buf->b_sfname == NULL
3046 ? buf->b_fname
3047 : buf->b_sfname);
3048 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3049 }
3050 else if (*e_cpt == NUL)
3051 status = INS_COMPL_CPT_END;
3052 else
3053 {
3054 if (ctrl_x_mode_line_or_eval())
3055 compl_type = -1;
3056 else if (*e_cpt == 'k' || *e_cpt == 's')
3057 {
3058 if (*e_cpt == 'k')
3059 compl_type = CTRL_X_DICTIONARY;
3060 else
3061 compl_type = CTRL_X_THESAURUS;
3062 if (*++e_cpt != ',' && *e_cpt != NUL)
3063 {
3064 dict = e_cpt;
3065 dict_f = DICT_FIRST;
3066 }
3067 }
3068#ifdef FEAT_FIND_ID
3069 else if (*e_cpt == 'i')
3070 compl_type = CTRL_X_PATH_PATTERNS;
3071 else if (*e_cpt == 'd')
3072 compl_type = CTRL_X_PATH_DEFINES;
3073#endif
3074 else if (*e_cpt == ']' || *e_cpt == 't')
3075 {
3076 msg_hist_off = TRUE; // reset in msg_trunc_attr()
3077 compl_type = CTRL_X_TAGS;
3078 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
3079 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
3080 }
3081 else
3082 compl_type = -1;
3083
3084 // in any case e_cpt is advanced to the next entry
3085 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
3086
3087 found_all = TRUE;
3088 if (compl_type == -1)
3089 status = INS_COMPL_CPT_CONT;
3090 }
3091
3092done:
3093 *e_cpt_arg = e_cpt;
3094 *compl_type_arg = compl_type;
3095 *found_all_arg = found_all;
3096 *buf_arg = buf;
3097 *dict_arg = dict;
3098 *dict_flag = dict_f;
3099 return status;
3100}
3101
3102#ifdef FEAT_FIND_ID
3103/*
3104 * Get the next set of identifiers or defines matching "compl_pattern" in
3105 * included files.
3106 */
3107 static void
3108get_next_include_file_completion(int compl_type)
3109{
3110 find_pattern_in_path(compl_pattern, compl_direction,
3111 (int)STRLEN(compl_pattern), FALSE, FALSE,
3112 (compl_type == CTRL_X_PATH_DEFINES
3113 && !(compl_cont_status & CONT_SOL))
3114 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
3115 (linenr_T)1, (linenr_T)MAXLNUM);
3116}
3117#endif
3118
3119/*
3120 * Get the next set of words matching "compl_pattern" in dictionary or
3121 * thesaurus files.
3122 */
3123 static void
3124get_next_dict_tsr_completion(int compl_type, char_u **dict, int dict_f)
3125{
3126#ifdef FEAT_COMPL_FUNC
3127 if (thesaurus_func_complete(compl_type))
3128 expand_by_function(compl_type, compl_pattern);
3129 else
3130#endif
3131 ins_compl_dictionaries(
3132 *dict != NULL ? *dict
3133 : (compl_type == CTRL_X_THESAURUS
3134 ? (*curbuf->b_p_tsr == NUL ? p_tsr : curbuf->b_p_tsr)
3135 : (*curbuf->b_p_dict == NUL ? p_dict : curbuf->b_p_dict)),
3136 compl_pattern,
3137 *dict != NULL ? dict_f : 0,
3138 compl_type == CTRL_X_THESAURUS);
3139 *dict = NULL;
3140}
3141
3142/*
3143 * Get the next set of tag names matching "compl_pattern".
3144 */
3145 static void
3146get_next_tag_completion(void)
3147{
3148 int save_p_ic;
3149 char_u **matches;
3150 int num_matches;
3151
3152 // set p_ic according to p_ic, p_scs and pat for find_tags().
3153 save_p_ic = p_ic;
3154 p_ic = ignorecase(compl_pattern);
3155
3156 // Find up to TAG_MANY matches. Avoids that an enormous number
3157 // of matches is found when compl_pattern is empty
3158 g_tag_at_cursor = TRUE;
3159 if (find_tags(compl_pattern, &num_matches, &matches,
3160 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
3161 | (ctrl_x_mode != CTRL_X_NORMAL ? TAG_VERBOSE : 0),
3162 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
3163 ins_compl_add_matches(num_matches, matches, p_ic);
3164 g_tag_at_cursor = FALSE;
3165 p_ic = save_p_ic;
3166}
3167
3168/*
3169 * Get the next set of filename matching "compl_pattern".
3170 */
3171 static void
3172get_next_filename_completion(void)
3173{
3174 char_u **matches;
3175 int num_matches;
3176
3177 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
3178 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) != OK)
3179 return;
3180
3181 // May change home directory back to "~".
3182 tilde_replace(compl_pattern, num_matches, matches);
3183#ifdef BACKSLASH_IN_FILENAME
3184 if (curbuf->b_p_csl[0] != NUL)
3185 {
3186 int i;
3187
3188 for (i = 0; i < num_matches; ++i)
3189 {
3190 char_u *ptr = matches[i];
3191
3192 while (*ptr != NUL)
3193 {
3194 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
3195 *ptr = '/';
3196 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
3197 *ptr = '\\';
3198 ptr += (*mb_ptr2len)(ptr);
3199 }
3200 }
3201 }
3202#endif
3203 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
3204}
3205
3206/*
3207 * Get the next set of command-line completions matching "compl_pattern".
3208 */
3209 static void
3210get_next_cmdline_completion()
3211{
3212 char_u **matches;
3213 int num_matches;
3214
3215 if (expand_cmdline(&compl_xp, compl_pattern,
3216 (int)STRLEN(compl_pattern),
3217 &num_matches, &matches) == EXPAND_OK)
3218 ins_compl_add_matches(num_matches, matches, FALSE);
3219}
3220
3221/*
3222 * Get the next set of spell suggestions matching "compl_pattern".
3223 */
3224 static void
3225get_next_spell_completion(linenr_T lnum UNUSED)
3226{
3227#ifdef FEAT_SPELL
3228 char_u **matches;
3229 int num_matches;
3230
3231 num_matches = expand_spelling(lnum, compl_pattern, &matches);
3232 if (num_matches > 0)
3233 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar8e7cc6b2021-12-30 10:32:25 +00003234 else
3235 vim_free(matches);
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003236#endif
3237}
3238
3239/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003240 * Return the next word or line from buffer "ins_buf" at position
3241 * "cur_match_pos" for completion. The length of the match is set in "len".
3242 */
3243 static char_u *
3244ins_comp_get_next_word_or_line(
3245 buf_T *ins_buf, // buffer being scanned
3246 pos_T *cur_match_pos, // current match position
3247 int *match_len,
3248 int *cont_s_ipos) // next ^X<> will set initial_pos
3249{
3250 char_u *ptr;
3251 int len;
3252
3253 *match_len = 0;
3254 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum, FALSE) +
3255 cur_match_pos->col;
3256 if (ctrl_x_mode_line_or_eval())
3257 {
3258 if (compl_cont_status & CONT_ADDING)
3259 {
3260 if (cur_match_pos->lnum >= ins_buf->b_ml.ml_line_count)
3261 return NULL;
3262 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3263 if (!p_paste)
3264 ptr = skipwhite(ptr);
3265 }
3266 len = (int)STRLEN(ptr);
3267 }
3268 else
3269 {
3270 char_u *tmp_ptr = ptr;
3271
3272 if (compl_cont_status & CONT_ADDING)
3273 {
3274 tmp_ptr += compl_length;
3275 // Skip if already inside a word.
3276 if (vim_iswordp(tmp_ptr))
3277 return NULL;
3278 // Find start of next word.
3279 tmp_ptr = find_word_start(tmp_ptr);
3280 }
3281 // Find end of this word.
3282 tmp_ptr = find_word_end(tmp_ptr);
3283 len = (int)(tmp_ptr - ptr);
3284
3285 if ((compl_cont_status & CONT_ADDING) && len == compl_length)
3286 {
3287 if (cur_match_pos->lnum < ins_buf->b_ml.ml_line_count)
3288 {
3289 // Try next line, if any. the new word will be
3290 // "join" as if the normal command "J" was used.
3291 // IOSIZE is always greater than
3292 // compl_length, so the next STRNCPY always
3293 // works -- Acevedo
3294 STRNCPY(IObuff, ptr, len);
3295 ptr = ml_get_buf(ins_buf, cur_match_pos->lnum + 1, FALSE);
3296 tmp_ptr = ptr = skipwhite(ptr);
3297 // Find start of next word.
3298 tmp_ptr = find_word_start(tmp_ptr);
3299 // Find end of next word.
3300 tmp_ptr = find_word_end(tmp_ptr);
3301 if (tmp_ptr > ptr)
3302 {
3303 if (*ptr != ')' && IObuff[len - 1] != TAB)
3304 {
3305 if (IObuff[len - 1] != ' ')
3306 IObuff[len++] = ' ';
3307 // IObuf =~ "\k.* ", thus len >= 2
3308 if (p_js
3309 && (IObuff[len - 2] == '.'
3310 || (vim_strchr(p_cpo, CPO_JOINSP)
3311 == NULL
3312 && (IObuff[len - 2] == '?'
3313 || IObuff[len - 2] == '!'))))
3314 IObuff[len++] = ' ';
3315 }
3316 // copy as much as possible of the new word
3317 if (tmp_ptr - ptr >= IOSIZE - len)
3318 tmp_ptr = ptr + IOSIZE - len - 1;
3319 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3320 len += (int)(tmp_ptr - ptr);
3321 *cont_s_ipos = TRUE;
3322 }
3323 IObuff[len] = NUL;
3324 ptr = IObuff;
3325 }
3326 if (len == compl_length)
3327 return NULL;
3328 }
3329 }
3330
3331 *match_len = len;
3332 return ptr;
3333}
3334
3335/*
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003336 * Get the next set of words matching "compl_pattern" for default completion(s)
3337 * (normal ^P/^N and ^X^L).
3338 * Search for "compl_pattern" in the buffer "ins_buf" starting from the
3339 * position "start_pos" in the "compl_direction" direction. If "save_match_pos"
3340 * is TRUE, then set the "first_match_pos" and "last_match_pos".
3341 * Returns OK if a new next match is found, otherwise returns FAIL.
3342 */
3343 static int
3344get_next_default_completion(
3345 buf_T *ins_buf, // buffer being scanned
3346 pos_T *start_pos, // search start position
3347 pos_T *cur_match_pos, // current match position
3348 pos_T *prev_match_pos, // previous match position
3349 int *save_match_pos, // set first_match_pos/last_match_pos
3350 pos_T *first_match_pos, // first match position
3351 pos_T *last_match_pos, // last match position
3352 int scan_curbuf) // scan current buffer for completion
3353{
3354 int found_new_match = FAIL;
3355 int save_p_scs;
3356 int save_p_ws;
3357 int looped_around = FALSE;
3358 char_u *ptr;
3359 int len;
3360
3361 // If 'infercase' is set, don't use 'smartcase' here
3362 save_p_scs = p_scs;
3363 if (ins_buf->b_p_inf)
3364 p_scs = FALSE;
3365
3366 // Buffers other than curbuf are scanned from the beginning or the
3367 // end but never from the middle, thus setting nowrapscan in this
3368 // buffer is a good idea, on the other hand, we always set
3369 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
3370 save_p_ws = p_ws;
3371 if (ins_buf != curbuf)
3372 p_ws = FALSE;
3373 else if (scan_curbuf)
3374 p_ws = TRUE;
3375 looped_around = FALSE;
3376 for (;;)
3377 {
3378 int cont_s_ipos = FALSE;
3379
3380 ++msg_silent; // Don't want messages for wrapscan.
3381
3382 // ctrl_x_mode_line_or_eval() || word-wise search that
3383 // has added a word that was at the beginning of the line
3384 if (ctrl_x_mode_line_or_eval()
3385 || (compl_cont_status & CONT_SOL))
3386 found_new_match = search_for_exact_line(ins_buf, cur_match_pos,
3387 compl_direction, compl_pattern);
3388 else
3389 found_new_match = searchit(NULL, ins_buf, cur_match_pos, NULL,
3390 compl_direction,
3391 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
3392 RE_LAST, NULL);
3393 --msg_silent;
3394 if (!compl_started || *save_match_pos)
3395 {
3396 // set "compl_started" even on fail
3397 compl_started = TRUE;
3398 *first_match_pos = *cur_match_pos;
3399 *last_match_pos = *cur_match_pos;
3400 *save_match_pos = FALSE;
3401 }
3402 else if (first_match_pos->lnum == last_match_pos->lnum
3403 && first_match_pos->col == last_match_pos->col)
3404 {
3405 found_new_match = FAIL;
3406 }
3407 else if ((compl_direction == FORWARD)
3408 && (prev_match_pos->lnum > cur_match_pos->lnum
3409 || (prev_match_pos->lnum == cur_match_pos->lnum
3410 && prev_match_pos->col >= cur_match_pos->col)))
3411 {
3412 if (looped_around)
3413 found_new_match = FAIL;
3414 else
3415 looped_around = TRUE;
3416 }
3417 else if ((compl_direction != FORWARD)
3418 && (prev_match_pos->lnum < cur_match_pos->lnum
3419 || (prev_match_pos->lnum == cur_match_pos->lnum
3420 && prev_match_pos->col <= cur_match_pos->col)))
3421 {
3422 if (looped_around)
3423 found_new_match = FAIL;
3424 else
3425 looped_around = TRUE;
3426 }
3427 *prev_match_pos = *cur_match_pos;
3428 if (found_new_match == FAIL)
3429 break;
3430
3431 // when ADDING, the text before the cursor matches, skip it
3432 if ((compl_cont_status & CONT_ADDING) && ins_buf == curbuf
3433 && start_pos->lnum == cur_match_pos->lnum
3434 && start_pos->col == cur_match_pos->col)
3435 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003436
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003437 ptr = ins_comp_get_next_word_or_line(ins_buf, cur_match_pos, &len,
3438 &cont_s_ipos);
3439 if (ptr == NULL)
3440 continue;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003441
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003442 if (ins_compl_add_infercase(ptr, len, p_ic,
3443 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
3444 0, cont_s_ipos) != NOTDONE)
3445 {
3446 found_new_match = OK;
3447 break;
3448 }
3449 }
3450 p_scs = save_p_scs;
3451 p_ws = save_p_ws;
3452
3453 return found_new_match;
3454}
3455
3456/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003457 * Get the next expansion(s), using "compl_pattern".
3458 * The search starts at position "ini" in curbuf and in the direction
3459 * compl_direction.
3460 * When "compl_started" is FALSE start at that position, otherwise continue
3461 * where we stopped searching before.
3462 * This may return before finding all the matches.
3463 * Return the total number of matches or -1 if still unknown -- Acevedo
3464 */
3465 static int
3466ins_compl_get_exp(pos_T *ini)
3467{
3468 static pos_T first_match_pos;
3469 static pos_T last_match_pos;
3470 static char_u *e_cpt = (char_u *)""; // curr. entry in 'complete'
3471 static int found_all = FALSE; // Found all matches of a
3472 // certain type.
3473 static buf_T *ins_buf = NULL; // buffer being scanned
3474
3475 pos_T *pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003476 int i;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003477 int found_new_match;
3478 int type = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003479 char_u *dict = NULL;
3480 int dict_f = 0;
3481 int set_match_pos;
Andy Gozas6a230c62021-08-05 16:23:27 +02003482 pos_T prev_pos = {0, 0, 0};
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003483
3484 if (!compl_started)
3485 {
3486 FOR_ALL_BUFFERS(ins_buf)
3487 ins_buf->b_scanned = 0;
3488 found_all = FALSE;
3489 ins_buf = curbuf;
3490 e_cpt = (compl_cont_status & CONT_LOCAL)
3491 ? (char_u *)"." : curbuf->b_p_cpt;
3492 last_match_pos = first_match_pos = *ini;
3493 }
3494 else if (ins_buf != curbuf && !buf_valid(ins_buf))
3495 ins_buf = curbuf; // In case the buffer was wiped out.
3496
3497 compl_old_match = compl_curr_match; // remember the last current match
3498 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
3499
3500 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
3501 for (;;)
3502 {
3503 found_new_match = FAIL;
3504 set_match_pos = FALSE;
3505
3506 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
3507 // or if found_all says this entry is done. For ^X^L only use the
3508 // entries from 'complete' that look in loaded buffers.
3509 if ((ctrl_x_mode == CTRL_X_NORMAL
3510 || ctrl_x_mode_line_or_eval())
3511 && (!compl_started || found_all))
3512 {
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003513 int status = process_next_cpt_value(&e_cpt, &type, &found_all,
3514 &ins_buf, ini, &first_match_pos, &last_match_pos,
3515 &set_match_pos, &dict, &dict_f);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003516
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003517 if (status == INS_COMPL_CPT_END)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003518 break;
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003519 if (status == INS_COMPL_CPT_CONT)
3520 continue;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003521 }
3522
3523 // If complete() was called then compl_pattern has been reset. The
3524 // following won't work then, bail out.
3525 if (compl_pattern == NULL)
3526 break;
3527
3528 switch (type)
3529 {
3530 case -1:
3531 break;
3532#ifdef FEAT_FIND_ID
3533 case CTRL_X_PATH_PATTERNS:
3534 case CTRL_X_PATH_DEFINES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003535 get_next_include_file_completion(type);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003536 break;
3537#endif
3538
3539 case CTRL_X_DICTIONARY:
3540 case CTRL_X_THESAURUS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003541 get_next_dict_tsr_completion(type, &dict, dict_f);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003542 break;
3543
3544 case CTRL_X_TAGS:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003545 get_next_tag_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003546 break;
3547
3548 case CTRL_X_FILES:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003549 get_next_filename_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003550 break;
3551
3552 case CTRL_X_CMDLINE:
zeertzjqdca29d92021-08-31 19:12:51 +02003553 case CTRL_X_CMDLINE_CTRL_X:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003554 get_next_cmdline_completion();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003555 break;
3556
3557#ifdef FEAT_COMPL_FUNC
3558 case CTRL_X_FUNCTION:
3559 case CTRL_X_OMNI:
3560 expand_by_function(type, compl_pattern);
3561 break;
3562#endif
3563
3564 case CTRL_X_SPELL:
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003565 get_next_spell_completion(first_match_pos.lnum);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003566 break;
3567
3568 default: // normal ^P/^N and ^X^L
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00003569 found_new_match = get_next_default_completion(ins_buf, ini, pos,
3570 &prev_pos, &set_match_pos, &first_match_pos,
3571 &last_match_pos, (*e_cpt == '.'));
3572 if (found_new_match == FAIL && ins_buf == curbuf)
3573 found_all = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003574 }
3575
3576 // check if compl_curr_match has changed, (e.g. other type of
3577 // expansion added something)
3578 if (type != 0 && compl_curr_match != compl_old_match)
3579 found_new_match = OK;
3580
3581 // break the loop for specialized modes (use 'complete' just for the
3582 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3583 // match
3584 if ((ctrl_x_mode != CTRL_X_NORMAL
3585 && !ctrl_x_mode_line_or_eval()) || found_new_match != FAIL)
3586 {
3587 if (got_int)
3588 break;
3589 // Fill the popup menu as soon as possible.
3590 if (type != -1)
3591 ins_compl_check_keys(0, FALSE);
3592
3593 if ((ctrl_x_mode != CTRL_X_NORMAL
3594 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3595 break;
3596 compl_started = TRUE;
3597 }
3598 else
3599 {
3600 // Mark a buffer scanned when it has been scanned completely
3601 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3602 ins_buf->b_scanned = TRUE;
3603
3604 compl_started = FALSE;
3605 }
3606 }
3607 compl_started = TRUE;
3608
3609 if ((ctrl_x_mode == CTRL_X_NORMAL || ctrl_x_mode_line_or_eval())
3610 && *e_cpt == NUL) // Got to end of 'complete'
3611 found_new_match = FAIL;
3612
3613 i = -1; // total of matches, unknown
3614 if (found_new_match == FAIL || (ctrl_x_mode != CTRL_X_NORMAL
3615 && !ctrl_x_mode_line_or_eval()))
3616 i = ins_compl_make_cyclic();
3617
3618 if (compl_old_match != NULL)
3619 {
3620 // If several matches were added (FORWARD) or the search failed and has
3621 // just been made cyclic then we have to move compl_curr_match to the
3622 // next or previous entry (if any) -- Acevedo
3623 compl_curr_match = compl_direction == FORWARD ? compl_old_match->cp_next
3624 : compl_old_match->cp_prev;
3625 if (compl_curr_match == NULL)
3626 compl_curr_match = compl_old_match;
3627 }
=?UTF-8?q?Magnus=20Gro=C3=9F?=25def2c2021-10-22 18:56:39 +01003628 trigger_modechanged();
3629
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003630 return i;
3631}
3632
3633/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003634 * Update "compl_shown_match" to the actually shown match, it may differ when
3635 * "compl_leader" is used to omit some of the matches.
3636 */
3637 static void
3638ins_compl_update_shown_match(void)
3639{
3640 while (!ins_compl_equal(compl_shown_match,
3641 compl_leader, (int)STRLEN(compl_leader))
3642 && compl_shown_match->cp_next != NULL
3643 && compl_shown_match->cp_next != compl_first_match)
3644 compl_shown_match = compl_shown_match->cp_next;
3645
3646 // If we didn't find it searching forward, and compl_shows_dir is
3647 // backward, find the last match.
3648 if (compl_shows_dir == BACKWARD
3649 && !ins_compl_equal(compl_shown_match,
3650 compl_leader, (int)STRLEN(compl_leader))
3651 && (compl_shown_match->cp_next == NULL
3652 || compl_shown_match->cp_next == compl_first_match))
3653 {
3654 while (!ins_compl_equal(compl_shown_match,
3655 compl_leader, (int)STRLEN(compl_leader))
3656 && compl_shown_match->cp_prev != NULL
3657 && compl_shown_match->cp_prev != compl_first_match)
3658 compl_shown_match = compl_shown_match->cp_prev;
3659 }
3660}
3661
3662/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003663 * Delete the old text being completed.
3664 */
3665 void
3666ins_compl_delete(void)
3667{
3668 int col;
3669
3670 // In insert mode: Delete the typed part.
3671 // In replace mode: Put the old characters back, if any.
3672 col = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
3673 if ((int)curwin->w_cursor.col > col)
3674 {
3675 if (stop_arrow() == FAIL)
3676 return;
3677 backspace_until_column(col);
3678 }
3679
3680 // TODO: is this sufficient for redrawing? Redrawing everything causes
3681 // flicker, thus we can't do that.
3682 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003683#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003684 // clear v:completed_item
3685 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003686#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003687}
3688
3689/*
3690 * Insert the new text being completed.
3691 * "in_compl_func" is TRUE when called from complete_check().
3692 */
3693 void
3694ins_compl_insert(int in_compl_func)
3695{
Bram Moolenaar4b28ba32021-12-27 19:28:37 +00003696 int compl_len = ins_compl_len();
3697
3698 // Make sure we don't go over the end of the string, this can happen with
3699 // illegal bytes.
3700 if (compl_len < (int)STRLEN(compl_shown_match->cp_str))
3701 ins_bytes(compl_shown_match->cp_str + compl_len);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003702 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003703 compl_used_match = FALSE;
3704 else
3705 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003706#ifdef FEAT_EVAL
3707 {
3708 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
3709
3710 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
3711 }
3712#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003713 if (!in_compl_func)
3714 compl_curr_match = compl_shown_match;
3715}
3716
3717/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003718 * show the file name for the completion match (if any). Truncate the file
3719 * name to avoid a wait for return.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003720 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003721 static void
3722ins_compl_show_filename(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003723{
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003724 char *lead = _("match in file");
3725 int space = sc_col - vim_strsize((char_u *)lead) - 2;
3726 char_u *s;
3727 char_u *e;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003728
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003729 if (space <= 0)
3730 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003731
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003732 // We need the tail that fits. With double-byte encoding going
3733 // back from the end is very slow, thus go from the start and keep
3734 // the text that fits in "space" between "s" and "e".
3735 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003736 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003737 space -= ptr2cells(e);
3738 while (space < 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003739 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003740 space += ptr2cells(s);
3741 MB_PTR_ADV(s);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003742 }
3743 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003744 msg_hist_off = TRUE;
3745 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
3746 s > compl_shown_match->cp_fname ? "<" : "", s);
3747 msg((char *)IObuff);
3748 msg_hist_off = FALSE;
3749 redraw_cmdline = FALSE; // don't overwrite!
3750}
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003751
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003752/*
3753 * Find the next set of matches for completion. Repeat the completion 'todo'
3754 * times. The number of matches found is returned in 'num_matches'.
3755 *
3756 * If "allow_get_expansion" is TRUE, then ins_compl_get_exp() may be called to
3757 * get more completions. If it is FALSE, then do nothing when there are no more
3758 * completions in the given direction.
3759 *
3760 * If "advance" is TRUE, then completion will move to the first match.
3761 * Otherwise, the original text will be shown.
3762 *
3763 * Returns OK on success and -1 if the number of matches are unknown.
3764 */
3765 static int
3766find_next_completion_match(
3767 int allow_get_expansion,
3768 int todo, // repeat completion this many times
3769 int advance,
3770 int *num_matches)
3771{
3772 int found_end = FALSE;
3773 compl_T *found_compl = NULL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003774
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003775 while (--todo >= 0)
3776 {
3777 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
3778 {
3779 compl_shown_match = compl_shown_match->cp_next;
3780 found_end = (compl_first_match != NULL
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003781 && (compl_shown_match->cp_next == compl_first_match
3782 || compl_shown_match == compl_first_match));
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003783 }
3784 else if (compl_shows_dir == BACKWARD
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003785 && compl_shown_match->cp_prev != NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003786 {
3787 found_end = (compl_shown_match == compl_first_match);
3788 compl_shown_match = compl_shown_match->cp_prev;
3789 found_end |= (compl_shown_match == compl_first_match);
3790 }
3791 else
3792 {
3793 if (!allow_get_expansion)
3794 {
3795 if (advance)
3796 {
3797 if (compl_shows_dir == BACKWARD)
3798 compl_pending -= todo + 1;
3799 else
3800 compl_pending += todo + 1;
3801 }
3802 return -1;
3803 }
3804
3805 if (!compl_no_select && advance)
3806 {
3807 if (compl_shows_dir == BACKWARD)
3808 --compl_pending;
3809 else
3810 ++compl_pending;
3811 }
3812
3813 // Find matches.
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003814 *num_matches = ins_compl_get_exp(&compl_startpos);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003815
3816 // handle any pending completions
3817 while (compl_pending != 0 && compl_direction == compl_shows_dir
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003818 && advance)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003819 {
3820 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
3821 {
3822 compl_shown_match = compl_shown_match->cp_next;
3823 --compl_pending;
3824 }
3825 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
3826 {
3827 compl_shown_match = compl_shown_match->cp_prev;
3828 ++compl_pending;
3829 }
3830 else
3831 break;
3832 }
3833 found_end = FALSE;
3834 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003835 if ((compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003836 && compl_leader != NULL
3837 && !ins_compl_equal(compl_shown_match,
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003838 compl_leader, (int)STRLEN(compl_leader)))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003839 ++todo;
3840 else
3841 // Remember a matching item.
3842 found_compl = compl_shown_match;
3843
3844 // Stop at the end of the list when we found a usable match.
3845 if (found_end)
3846 {
3847 if (found_compl != NULL)
3848 {
3849 compl_shown_match = found_compl;
3850 break;
3851 }
3852 todo = 1; // use first usable match after wrapping around
3853 }
3854 }
3855
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003856 return OK;
3857}
3858
3859/*
3860 * Fill in the next completion in the current direction.
3861 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
3862 * get more completions. If it is FALSE, then we just do nothing when there
3863 * are no more completions in a given direction. The latter case is used when
3864 * we are still in the middle of finding completions, to allow browsing
3865 * through the ones found so far.
3866 * Return the total number of matches, or -1 if still unknown -- webb.
3867 *
3868 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
3869 * compl_shown_match here.
3870 *
3871 * Note that this function may be called recursively once only. First with
3872 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
3873 * calls this function with "allow_get_expansion" FALSE.
3874 */
3875 static int
3876ins_compl_next(
3877 int allow_get_expansion,
3878 int count, // repeat completion this many times; should
3879 // be at least 1
3880 int insert_match, // Insert the newly selected match
3881 int in_compl_func) // called from complete_check()
3882{
3883 int num_matches = -1;
3884 int todo = count;
3885 int advance;
3886 int started = compl_started;
3887
3888 // When user complete function return -1 for findstart which is next
3889 // time of 'always', compl_shown_match become NULL.
3890 if (compl_shown_match == NULL)
3891 return -1;
3892
3893 if (compl_leader != NULL
3894 && (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0)
3895 // Update "compl_shown_match" to the actually shown match
3896 ins_compl_update_shown_match();
3897
3898 if (allow_get_expansion && insert_match
3899 && (!(compl_get_longest || compl_restarting) || compl_used_match))
3900 // Delete old text to be replaced
3901 ins_compl_delete();
3902
3903 // When finding the longest common text we stick at the original text,
3904 // don't let CTRL-N or CTRL-P move to the first match.
3905 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
3906
3907 // When restarting the search don't insert the first match either.
3908 if (compl_restarting)
3909 {
3910 advance = FALSE;
3911 compl_restarting = FALSE;
3912 }
3913
3914 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
3915 // around.
3916 if (find_next_completion_match(allow_get_expansion, todo, advance,
3917 &num_matches) == -1)
3918 return -1;
3919
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003920 // Insert the text of the new completion, or the compl_leader.
3921 if (compl_no_insert && !started)
3922 {
3923 ins_bytes(compl_orig_text + ins_compl_len());
3924 compl_used_match = FALSE;
3925 }
3926 else if (insert_match)
3927 {
3928 if (!compl_get_longest || compl_used_match)
3929 ins_compl_insert(in_compl_func);
3930 else
3931 ins_bytes(compl_leader + ins_compl_len());
3932 }
3933 else
3934 compl_used_match = FALSE;
3935
3936 if (!allow_get_expansion)
3937 {
3938 // may undisplay the popup menu first
3939 ins_compl_upd_pum();
3940
3941 if (pum_enough_matches())
3942 // Will display the popup menu, don't redraw yet to avoid flicker.
3943 pum_call_update_screen();
3944 else
3945 // Not showing the popup menu yet, redraw to show the user what was
3946 // inserted.
3947 update_screen(0);
3948
3949 // display the updated popup menu
3950 ins_compl_show_pum();
3951#ifdef FEAT_GUI
3952 if (gui.in_use)
3953 {
3954 // Show the cursor after the match, not after the redrawn text.
3955 setcursor();
3956 out_flush_cursor(FALSE, FALSE);
3957 }
3958#endif
3959
3960 // Delete old text to be replaced, since we're still searching and
3961 // don't want to match ourselves!
3962 ins_compl_delete();
3963 }
3964
3965 // Enter will select a match when the match wasn't inserted and the popup
3966 // menu is visible.
3967 if (compl_no_insert && !started)
3968 compl_enter_selects = TRUE;
3969 else
3970 compl_enter_selects = !insert_match && compl_match_array != NULL;
3971
3972 // Show the file name for the match (if any)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003973 if (compl_shown_match->cp_fname != NULL)
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00003974 ins_compl_show_filename();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003975
3976 return num_matches;
3977}
3978
3979/*
3980 * Call this while finding completions, to check whether the user has hit a key
3981 * that should change the currently displayed completion, or exit completion
3982 * mode. Also, when compl_pending is not zero, show a completion as soon as
3983 * possible. -- webb
3984 * "frequency" specifies out of how many calls we actually check.
3985 * "in_compl_func" is TRUE when called from complete_check(), don't set
3986 * compl_curr_match.
3987 */
3988 void
3989ins_compl_check_keys(int frequency, int in_compl_func)
3990{
3991 static int count = 0;
3992 int c;
3993
3994 // Don't check when reading keys from a script, :normal or feedkeys().
3995 // That would break the test scripts. But do check for keys when called
3996 // from complete_check().
3997 if (!in_compl_func && (using_script() || ex_normal_busy))
3998 return;
3999
4000 // Only do this at regular intervals
4001 if (++count < frequency)
4002 return;
4003 count = 0;
4004
4005 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
4006 // can't do its work correctly.
4007 c = vpeekc_any();
4008 if (c != NUL)
4009 {
4010 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
4011 {
4012 c = safe_vgetc(); // Eat the character
4013 compl_shows_dir = ins_compl_key2dir(c);
4014 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
4015 c != K_UP && c != K_DOWN, in_compl_func);
4016 }
4017 else
4018 {
4019 // Need to get the character to have KeyTyped set. We'll put it
4020 // back with vungetc() below. But skip K_IGNORE.
4021 c = safe_vgetc();
4022 if (c != K_IGNORE)
4023 {
4024 // Don't interrupt completion when the character wasn't typed,
4025 // e.g., when doing @q to replay keys.
4026 if (c != Ctrl_R && KeyTyped)
4027 compl_interrupted = TRUE;
4028
4029 vungetc(c);
4030 }
4031 }
4032 }
4033 if (compl_pending != 0 && !got_int && !compl_no_insert)
4034 {
4035 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
4036
4037 compl_pending = 0;
4038 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
4039 }
4040}
4041
4042/*
4043 * Decide the direction of Insert mode complete from the key typed.
4044 * Returns BACKWARD or FORWARD.
4045 */
4046 static int
4047ins_compl_key2dir(int c)
4048{
4049 if (c == Ctrl_P || c == Ctrl_L
4050 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
4051 return BACKWARD;
4052 return FORWARD;
4053}
4054
4055/*
4056 * Return TRUE for keys that are used for completion only when the popup menu
4057 * is visible.
4058 */
4059 static int
4060ins_compl_pum_key(int c)
4061{
4062 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
4063 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
4064 || c == K_UP || c == K_DOWN);
4065}
4066
4067/*
4068 * Decide the number of completions to move forward.
4069 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
4070 */
4071 static int
4072ins_compl_key2count(int c)
4073{
4074 int h;
4075
4076 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
4077 {
4078 h = pum_get_height();
4079 if (h > 3)
4080 h -= 2; // keep some context
4081 return h;
4082 }
4083 return 1;
4084}
4085
4086/*
4087 * Return TRUE if completion with "c" should insert the match, FALSE if only
4088 * to change the currently selected completion.
4089 */
4090 static int
4091ins_compl_use_match(int c)
4092{
4093 switch (c)
4094 {
4095 case K_UP:
4096 case K_DOWN:
4097 case K_PAGEDOWN:
4098 case K_KPAGEDOWN:
4099 case K_S_DOWN:
4100 case K_PAGEUP:
4101 case K_KPAGEUP:
4102 case K_S_UP:
4103 return FALSE;
4104 }
4105 return TRUE;
4106}
4107
4108/*
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004109 * Get the pattern, column and length for normal completion (CTRL-N CTRL-P
4110 * completion)
4111 * Sets the global variables: compl_col, compl_length and compl_pattern.
4112 * Uses the global variables: compl_cont_status and ctrl_x_mode
4113 */
4114 static int
4115get_normal_compl_info(char_u *line, int startcol, colnr_T curs_col)
4116{
Yegappan Lakshmananedc6f102021-12-29 17:38:46 +00004117 if ((compl_cont_status & CONT_SOL) || ctrl_x_mode == CTRL_X_PATH_DEFINES)
Bram Moolenaarbf7ff612021-12-27 12:52:07 +00004118 {
4119 if (!(compl_cont_status & CONT_ADDING))
4120 {
4121 while (--startcol >= 0 && vim_isIDc(line[startcol]))
4122 ;
4123 compl_col += ++startcol;
4124 compl_length = curs_col - startcol;
4125 }
4126 if (p_ic)
4127 compl_pattern = str_foldcase(line + compl_col,
4128 compl_length, NULL, 0);
4129 else
4130 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4131 if (compl_pattern == NULL)
4132 return FAIL;
4133 }
4134 else if (compl_cont_status & CONT_ADDING)
4135 {
4136 char_u *prefix = (char_u *)"\\<";
4137
4138 // we need up to 2 extra chars for the prefix
4139 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4140 compl_length) + 2);
4141 if (compl_pattern == NULL)
4142 return FAIL;
4143 if (!vim_iswordp(line + compl_col)
4144 || (compl_col > 0
4145 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
4146 prefix = (char_u *)"";
4147 STRCPY((char *)compl_pattern, prefix);
4148 (void)quote_meta(compl_pattern + STRLEN(prefix),
4149 line + compl_col, compl_length);
4150 }
4151 else if (--startcol < 0
4152 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
4153 {
4154 // Match any word of at least two chars
4155 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
4156 if (compl_pattern == NULL)
4157 return FAIL;
4158 compl_col += curs_col;
4159 compl_length = 0;
4160 }
4161 else
4162 {
4163 // Search the point of change class of multibyte character
4164 // or not a word single byte character backward.
4165 if (has_mbyte)
4166 {
4167 int base_class;
4168 int head_off;
4169
4170 startcol -= (*mb_head_off)(line, line + startcol);
4171 base_class = mb_get_class(line + startcol);
4172 while (--startcol >= 0)
4173 {
4174 head_off = (*mb_head_off)(line, line + startcol);
4175 if (base_class != mb_get_class(line + startcol
4176 - head_off))
4177 break;
4178 startcol -= head_off;
4179 }
4180 }
4181 else
4182 while (--startcol >= 0 && vim_iswordc(line[startcol]))
4183 ;
4184 compl_col += ++startcol;
4185 compl_length = (int)curs_col - startcol;
4186 if (compl_length == 1)
4187 {
4188 // Only match word with at least two chars -- webb
4189 // there's no need to call quote_meta,
4190 // alloc(7) is enough -- Acevedo
4191 compl_pattern = alloc(7);
4192 if (compl_pattern == NULL)
4193 return FAIL;
4194 STRCPY((char *)compl_pattern, "\\<");
4195 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
4196 STRCAT((char *)compl_pattern, "\\k");
4197 }
4198 else
4199 {
4200 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
4201 compl_length) + 2);
4202 if (compl_pattern == NULL)
4203 return FAIL;
4204 STRCPY((char *)compl_pattern, "\\<");
4205 (void)quote_meta(compl_pattern + 2, line + compl_col,
4206 compl_length);
4207 }
4208 }
4209
4210 return OK;
4211}
4212
4213/*
4214 * Get the pattern, column and length for whole line completion or for the
4215 * complete() function.
4216 * Sets the global variables: compl_col, compl_length and compl_pattern.
4217 */
4218 static int
4219get_wholeline_compl_info(char_u *line, colnr_T curs_col)
4220{
4221 compl_col = (colnr_T)getwhitecols(line);
4222 compl_length = (int)curs_col - (int)compl_col;
4223 if (compl_length < 0) // cursor in indent: empty pattern
4224 compl_length = 0;
4225 if (p_ic)
4226 compl_pattern = str_foldcase(line + compl_col, compl_length,
4227 NULL, 0);
4228 else
4229 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4230 if (compl_pattern == NULL)
4231 return FAIL;
4232
4233 return OK;
4234}
4235
4236/*
4237 * Get the pattern, column and length for filename completion.
4238 * Sets the global variables: compl_col, compl_length and compl_pattern.
4239 */
4240 static int
4241get_filename_compl_info(char_u *line, int startcol, colnr_T curs_col)
4242{
4243 // Go back to just before the first filename character.
4244 if (startcol > 0)
4245 {
4246 char_u *p = line + startcol;
4247
4248 MB_PTR_BACK(line, p);
4249 while (p > line && vim_isfilec(PTR2CHAR(p)))
4250 MB_PTR_BACK(line, p);
4251 if (p == line && vim_isfilec(PTR2CHAR(p)))
4252 startcol = 0;
4253 else
4254 startcol = (int)(p - line) + 1;
4255 }
4256
4257 compl_col += startcol;
4258 compl_length = (int)curs_col - startcol;
4259 compl_pattern = addstar(line + compl_col, compl_length, EXPAND_FILES);
4260 if (compl_pattern == NULL)
4261 return FAIL;
4262
4263 return OK;
4264}
4265
4266/*
4267 * Get the pattern, column and length for command-line completion.
4268 * Sets the global variables: compl_col, compl_length and compl_pattern.
4269 */
4270 static int
4271get_cmdline_compl_info(char_u *line, colnr_T curs_col)
4272{
4273 compl_pattern = vim_strnsave(line, curs_col);
4274 if (compl_pattern == NULL)
4275 return FAIL;
4276 set_cmd_context(&compl_xp, compl_pattern,
4277 (int)STRLEN(compl_pattern), curs_col, FALSE);
4278 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
4279 || compl_xp.xp_context == EXPAND_NOTHING)
4280 // No completion possible, use an empty pattern to get a
4281 // "pattern not found" message.
4282 compl_col = curs_col;
4283 else
4284 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
4285 compl_length = curs_col - compl_col;
4286
4287 return OK;
4288}
4289
4290/*
4291 * Get the pattern, column and length for user defined completion ('omnifunc',
4292 * 'completefunc' and 'thesaurusfunc')
4293 * Sets the global variables: compl_col, compl_length and compl_pattern.
4294 * Uses the global variable: spell_bad_len
4295 */
4296 static int
4297get_userdefined_compl_info(colnr_T curs_col UNUSED)
4298{
4299 int ret = FAIL;
4300
4301#ifdef FEAT_COMPL_FUNC
4302 // Call user defined function 'completefunc' with "a:findstart"
4303 // set to 1 to obtain the length of text to use for completion.
4304 char_u *line;
4305 typval_T args[3];
4306 int col;
4307 char_u *funcname;
4308 pos_T pos;
4309 int save_State = State;
4310 callback_T *cb;
4311
4312 // Call 'completefunc' or 'omnifunc' or 'thesaurusfunc' and get pattern
4313 // length as a string
4314 funcname = get_complete_funcname(ctrl_x_mode);
4315 if (*funcname == NUL)
4316 {
4317 semsg(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
4318 ? "completefunc" : "omnifunc");
4319 return FAIL;
4320 }
4321
4322 args[0].v_type = VAR_NUMBER;
4323 args[0].vval.v_number = 1;
4324 args[1].v_type = VAR_STRING;
4325 args[1].vval.v_string = (char_u *)"";
4326 args[2].v_type = VAR_UNKNOWN;
4327 pos = curwin->w_cursor;
4328 ++textwinlock;
4329 cb = get_insert_callback(ctrl_x_mode);
4330 col = call_callback_retnr(cb, 2, args);
4331 --textwinlock;
4332
4333 State = save_State;
4334 curwin->w_cursor = pos; // restore the cursor position
4335 validate_cursor();
4336 if (!EQUAL_POS(curwin->w_cursor, pos))
4337 {
4338 emsg(_(e_compldel));
4339 return FAIL;
4340 }
4341
4342 // Return value -2 means the user complete function wants to
4343 // cancel the complete without an error.
4344 // Return value -3 does the same as -2 and leaves CTRL-X mode.
4345 if (col == -2)
4346 return FAIL;
4347 if (col == -3)
4348 {
4349 ctrl_x_mode = CTRL_X_NORMAL;
4350 edit_submode = NULL;
4351 if (!shortmess(SHM_COMPLETIONMENU))
4352 msg_clr_cmdline();
4353 return FAIL;
4354 }
4355
4356 // Reset extended parameters of completion, when start new
4357 // completion.
4358 compl_opt_refresh_always = FALSE;
4359 compl_opt_suppress_empty = FALSE;
4360
4361 if (col < 0)
4362 col = curs_col;
4363 compl_col = col;
4364 if (compl_col > curs_col)
4365 compl_col = curs_col;
4366
4367 // Setup variables for completion. Need to obtain "line" again,
4368 // it may have become invalid.
4369 line = ml_get(curwin->w_cursor.lnum);
4370 compl_length = curs_col - compl_col;
4371 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4372 if (compl_pattern == NULL)
4373 return FAIL;
4374
4375 ret = OK;
4376#endif
4377
4378 return ret;
4379}
4380
4381/*
4382 * Get the pattern, column and length for spell completion.
4383 * Sets the global variables: compl_col, compl_length and compl_pattern.
4384 * Uses the global variable: spell_bad_len
4385 */
4386 static int
4387get_spell_compl_info(int startcol UNUSED, colnr_T curs_col UNUSED)
4388{
4389 int ret = FAIL;
4390#ifdef FEAT_SPELL
4391 char_u *line;
4392
4393 if (spell_bad_len > 0)
4394 compl_col = curs_col - spell_bad_len;
4395 else
4396 compl_col = spell_word_start(startcol);
4397 if (compl_col >= (colnr_T)startcol)
4398 {
4399 compl_length = 0;
4400 compl_col = curs_col;
4401 }
4402 else
4403 {
4404 spell_expand_check_cap(compl_col);
4405 compl_length = (int)curs_col - compl_col;
4406 }
4407 // Need to obtain "line" again, it may have become invalid.
4408 line = ml_get(curwin->w_cursor.lnum);
4409 compl_pattern = vim_strnsave(line + compl_col, compl_length);
4410 if (compl_pattern == NULL)
4411 return FAIL;
4412
4413 ret = OK;
4414#endif
4415
4416 return ret;
4417}
4418
4419/*
4420 * Get the completion pattern, column and length.
4421 */
4422 static int
4423compl_get_info(char_u *line, int startcol, colnr_T curs_col, int *line_invalid)
4424{
4425 if (ctrl_x_mode == CTRL_X_NORMAL
4426 || (ctrl_x_mode & CTRL_X_WANT_IDENT
4427 && !thesaurus_func_complete(ctrl_x_mode)))
4428 {
4429 return get_normal_compl_info(line, startcol, curs_col);
4430 }
4431 else if (ctrl_x_mode_line_or_eval())
4432 {
4433 return get_wholeline_compl_info(line, curs_col);
4434 }
4435 else if (ctrl_x_mode == CTRL_X_FILES)
4436 {
4437 return get_filename_compl_info(line, startcol, curs_col);
4438 }
4439 else if (ctrl_x_mode == CTRL_X_CMDLINE)
4440 {
4441 return get_cmdline_compl_info(line, curs_col);
4442 }
4443 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI
4444 || thesaurus_func_complete(ctrl_x_mode))
4445 {
4446 if (get_userdefined_compl_info(curs_col) == FAIL)
4447 return FAIL;
4448 *line_invalid = TRUE; // 'line' may have become invalid
4449 }
4450 else if (ctrl_x_mode == CTRL_X_SPELL)
4451 {
4452 if (get_spell_compl_info(startcol, curs_col) == FAIL)
4453 return FAIL;
4454 *line_invalid = TRUE; // 'line' may have become invalid
4455 }
4456 else
4457 {
4458 internal_error("ins_complete()");
4459 return FAIL;
4460 }
4461
4462 return OK;
4463}
4464
4465/*
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004466 * Continue an interrupted completion mode search in "line".
4467 *
4468 * If this same ctrl_x_mode has been interrupted use the text from
4469 * "compl_startpos" to the cursor as a pattern to add a new word instead of
4470 * expand the one before the cursor, in word-wise if "compl_startpos" is not in
4471 * the same line as the cursor then fix it (the line has been split because it
4472 * was longer than 'tw'). if SOL is set then skip the previous pattern, a word
4473 * at the beginning of the line has been inserted, we'll look for that.
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004474 */
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004475 static void
4476ins_compl_continue_search(char_u *line)
4477{
4478 // it is a continued search
4479 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
4480 if (ctrl_x_mode == CTRL_X_NORMAL
4481 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
4482 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
4483 {
4484 if (compl_startpos.lnum != curwin->w_cursor.lnum)
4485 {
4486 // line (probably) wrapped, set compl_startpos to the
4487 // first non_blank in the line, if it is not a wordchar
4488 // include it to get a better pattern, but then we don't
4489 // want the "\\<" prefix, check it below
4490 compl_col = (colnr_T)getwhitecols(line);
4491 compl_startpos.col = compl_col;
4492 compl_startpos.lnum = curwin->w_cursor.lnum;
4493 compl_cont_status &= ~CONT_SOL; // clear SOL if present
4494 }
4495 else
4496 {
4497 // S_IPOS was set when we inserted a word that was at the
4498 // beginning of the line, which means that we'll go to SOL
4499 // mode but first we need to redefine compl_startpos
4500 if (compl_cont_status & CONT_S_IPOS)
4501 {
4502 compl_cont_status |= CONT_SOL;
4503 compl_startpos.col = (colnr_T)(skipwhite(
4504 line + compl_length
4505 + compl_startpos.col) - line);
4506 }
4507 compl_col = compl_startpos.col;
4508 }
4509 compl_length = curwin->w_cursor.col - (int)compl_col;
4510 // IObuff is used to add a "word from the next line" would we
4511 // have enough space? just being paranoid
4512#define MIN_SPACE 75
4513 if (compl_length > (IOSIZE - MIN_SPACE))
4514 {
4515 compl_cont_status &= ~CONT_SOL;
4516 compl_length = (IOSIZE - MIN_SPACE);
4517 compl_col = curwin->w_cursor.col - compl_length;
4518 }
4519 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
4520 if (compl_length < 1)
4521 compl_cont_status &= CONT_LOCAL;
4522 }
4523 else if (ctrl_x_mode_line_or_eval())
4524 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
4525 else
4526 compl_cont_status = 0;
4527}
4528
4529/*
4530 * start insert mode completion
4531 */
4532 static int
4533ins_compl_start(void)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004534{
4535 char_u *line;
4536 int startcol = 0; // column where searched text starts
4537 colnr_T curs_col; // cursor column
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004538 int line_invalid = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004539 int save_did_ai = did_ai;
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004540 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004541
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004542 // First time we hit ^N or ^P (in a row, I mean)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004543
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004544 did_ai = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004545#ifdef FEAT_SMARTINDENT
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004546 did_si = FALSE;
4547 can_si = FALSE;
4548 can_si_back = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004549#endif
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004550 if (stop_arrow() == FAIL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004551 return FAIL;
4552
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004553 line = ml_get(curwin->w_cursor.lnum);
4554 curs_col = curwin->w_cursor.col;
4555 compl_pending = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004556
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004557 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
4558 && compl_cont_mode == ctrl_x_mode)
4559 // this same ctrl-x_mode was interrupted previously. Continue the
4560 // completion.
4561 ins_compl_continue_search(line);
4562 else
4563 compl_cont_status &= CONT_LOCAL;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004564
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004565 if (!(compl_cont_status & CONT_ADDING)) // normal expansion
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004566 {
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004567 compl_cont_mode = ctrl_x_mode;
4568 if (ctrl_x_mode != CTRL_X_NORMAL)
4569 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
4570 compl_cont_status = 0;
4571 compl_cont_status |= CONT_N_ADDS;
4572 compl_startpos = curwin->w_cursor;
4573 startcol = (int)curs_col;
4574 compl_col = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004575 }
4576
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004577 // Work out completion pattern and original text -- webb
4578 if (compl_get_info(line, startcol, curs_col, &line_invalid) == FAIL)
4579 {
4580 if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI
4581 || thesaurus_func_complete(ctrl_x_mode))
4582 // restore did_ai, so that adding comment leader works
4583 did_ai = save_did_ai;
4584 return FAIL;
4585 }
4586 // If "line" was changed while getting completion info get it again.
4587 if (line_invalid)
4588 line = ml_get(curwin->w_cursor.lnum);
4589
4590 if (compl_cont_status & CONT_ADDING)
4591 {
4592 edit_submode_pre = (char_u *)_(" Adding");
4593 if (ctrl_x_mode_line_or_eval())
4594 {
4595 // Insert a new line, keep indentation but ignore 'comments'.
4596 char_u *old = curbuf->b_p_com;
4597
4598 curbuf->b_p_com = (char_u *)"";
4599 compl_startpos.lnum = curwin->w_cursor.lnum;
4600 compl_startpos.col = compl_col;
4601 ins_eol('\r');
4602 curbuf->b_p_com = old;
4603 compl_length = 0;
4604 compl_col = curwin->w_cursor.col;
4605 }
4606 }
4607 else
4608 {
4609 edit_submode_pre = NULL;
4610 compl_startpos.col = compl_col;
4611 }
4612
4613 if (compl_cont_status & CONT_LOCAL)
4614 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
4615 else
4616 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
4617
4618 // If any of the original typed text has been changed we need to fix
4619 // the redo buffer.
4620 ins_compl_fixRedoBufForLeader(NULL);
4621
4622 // Always add completion for the original text.
4623 vim_free(compl_orig_text);
4624 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
4625 if (p_ic)
4626 flags |= CP_ICASE;
4627 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
4628 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
4629 {
4630 VIM_CLEAR(compl_pattern);
4631 VIM_CLEAR(compl_orig_text);
4632 return FAIL;
4633 }
4634
4635 // showmode might reset the internal line pointers, so it must
4636 // be called before line = ml_get(), or when this address is no
4637 // longer needed. -- Acevedo.
4638 edit_submode_extra = (char_u *)_("-- Searching...");
4639 edit_submode_highl = HLF_COUNT;
4640 showmode();
4641 edit_submode_extra = NULL;
4642 out_flush();
4643
4644 return OK;
4645}
4646
4647/*
4648 * display the completion status message
4649 */
4650 static void
4651ins_compl_show_statusmsg(void)
4652{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004653 // we found no match if the list has only the "compl_orig_text"-entry
4654 if (compl_first_match == compl_first_match->cp_next)
4655 {
4656 edit_submode_extra = (compl_cont_status & CONT_ADDING)
4657 && compl_length > 1
4658 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
4659 edit_submode_highl = HLF_E;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004660 }
4661
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004662 if (edit_submode_extra == NULL)
4663 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004664 if (compl_curr_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004665 {
4666 edit_submode_extra = (char_u *)_("Back at original");
4667 edit_submode_highl = HLF_W;
4668 }
4669 else if (compl_cont_status & CONT_S_IPOS)
4670 {
4671 edit_submode_extra = (char_u *)_("Word from other line");
4672 edit_submode_highl = HLF_COUNT;
4673 }
4674 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
4675 {
4676 edit_submode_extra = (char_u *)_("The only match");
4677 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01004678 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004679 }
4680 else
4681 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01004682#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004683 // Update completion sequence number when needed.
4684 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01004685 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01004686#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004687 // The match should always have a sequence number now, this is
4688 // just a safety check.
4689 if (compl_curr_match->cp_number != -1)
4690 {
4691 // Space for 10 text chars. + 2x10-digit no.s = 31.
4692 // Translations may need more than twice that.
4693 static char_u match_ref[81];
4694
4695 if (compl_matches > 0)
4696 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004697 _("match %d of %d"),
4698 compl_curr_match->cp_number, compl_matches);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004699 else
4700 vim_snprintf((char *)match_ref, sizeof(match_ref),
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004701 _("match %d"),
4702 compl_curr_match->cp_number);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004703 edit_submode_extra = match_ref;
4704 edit_submode_highl = HLF_R;
4705 if (dollar_vcol >= 0)
4706 curs_columns(FALSE);
4707 }
4708 }
4709 }
4710
4711 // Show a message about what (completion) mode we're in.
4712 if (!compl_opt_suppress_empty)
4713 {
4714 showmode();
4715 if (!shortmess(SHM_COMPLETIONMENU))
4716 {
4717 if (edit_submode_extra != NULL)
4718 {
4719 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01004720 {
4721 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004722 msg_attr((char *)edit_submode_extra,
4723 edit_submode_highl < HLF_COUNT
4724 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01004725 msg_hist_off = FALSE;
4726 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004727 }
4728 else
4729 msg_clr_cmdline(); // necessary for "noshowmode"
4730 }
4731 }
Yegappan Lakshmanan5d2e0072021-12-30 11:40:53 +00004732}
4733
4734/*
4735 * Do Insert mode completion.
4736 * Called when character "c" was typed, which has a meaning for completion.
4737 * Returns OK if completion was done, FAIL if something failed (out of mem).
4738 */
4739 int
4740ins_complete(int c, int enable_pum)
4741{
4742 int n;
4743 int save_w_wrow;
4744 int save_w_leftcol;
4745 int insert_match;
4746
4747 compl_direction = ins_compl_key2dir(c);
4748 insert_match = ins_compl_use_match(c);
4749
4750 if (!compl_started)
4751 {
4752 if (ins_compl_start() == FAIL)
4753 return FAIL;
4754 }
4755 else if (insert_match && stop_arrow() == FAIL)
4756 return FAIL;
4757
4758 compl_shown_match = compl_curr_match;
4759 compl_shows_dir = compl_direction;
4760
4761 // Find next match (and following matches).
4762 save_w_wrow = curwin->w_wrow;
4763 save_w_leftcol = curwin->w_leftcol;
4764 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
4765
4766 // may undisplay the popup menu
4767 ins_compl_upd_pum();
4768
4769 if (n > 1) // all matches have been found
4770 compl_matches = n;
4771 compl_curr_match = compl_shown_match;
4772 compl_direction = compl_shows_dir;
4773
4774 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
4775 // mode.
4776 if (got_int && !global_busy)
4777 {
4778 (void)vgetc();
4779 got_int = FALSE;
4780 }
4781
4782 // we found no match if the list has only the "compl_orig_text"-entry
4783 if (compl_first_match == compl_first_match->cp_next)
4784 {
4785 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
4786 // because we couldn't expand anything at first place, but if we used
4787 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
4788 // (such as M in M'exico) if not tried already. -- Acevedo
4789 if (compl_length > 1
4790 || (compl_cont_status & CONT_ADDING)
4791 || (ctrl_x_mode != CTRL_X_NORMAL
4792 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
4793 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
4794 compl_cont_status &= ~CONT_N_ADDS;
4795 }
4796
4797 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
4798 compl_cont_status |= CONT_S_IPOS;
4799 else
4800 compl_cont_status &= ~CONT_S_IPOS;
4801
4802 ins_compl_show_statusmsg();
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004803
4804 // Show the popup menu, unless we got interrupted.
4805 if (enable_pum && !compl_interrupted)
4806 show_pum(save_w_wrow, save_w_leftcol);
4807
4808 compl_was_interrupted = compl_interrupted;
4809 compl_interrupted = FALSE;
4810
4811 return OK;
4812}
4813
4814 static void
4815show_pum(int prev_w_wrow, int prev_w_leftcol)
4816{
4817 // RedrawingDisabled may be set when invoked through complete().
4818 int n = RedrawingDisabled;
4819
4820 RedrawingDisabled = 0;
4821
4822 // If the cursor moved or the display scrolled we need to remove the pum
4823 // first.
4824 setcursor();
4825 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
4826 ins_compl_del_pum();
4827
4828 ins_compl_show_pum();
4829 setcursor();
4830 RedrawingDisabled = n;
4831}
4832
4833/*
4834 * Looks in the first "len" chars. of "src" for search-metachars.
4835 * If dest is not NULL the chars. are copied there quoting (with
4836 * a backslash) the metachars, and dest would be NUL terminated.
4837 * Returns the length (needed) of dest
4838 */
4839 static unsigned
4840quote_meta(char_u *dest, char_u *src, int len)
4841{
4842 unsigned m = (unsigned)len + 1; // one extra for the NUL
4843
4844 for ( ; --len >= 0; src++)
4845 {
4846 switch (*src)
4847 {
4848 case '.':
4849 case '*':
4850 case '[':
4851 if (ctrl_x_mode == CTRL_X_DICTIONARY
4852 || ctrl_x_mode == CTRL_X_THESAURUS)
4853 break;
4854 // FALLTHROUGH
4855 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01004856 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004857 break;
4858 // FALLTHROUGH
4859 case '\\':
4860 if (ctrl_x_mode == CTRL_X_DICTIONARY
4861 || ctrl_x_mode == CTRL_X_THESAURUS)
4862 break;
4863 // FALLTHROUGH
4864 case '^': // currently it's not needed.
4865 case '$':
4866 m++;
4867 if (dest != NULL)
4868 *dest++ = '\\';
4869 break;
4870 }
4871 if (dest != NULL)
4872 *dest++ = *src;
4873 // Copy remaining bytes of a multibyte character.
4874 if (has_mbyte)
4875 {
4876 int i, mb_len;
4877
4878 mb_len = (*mb_ptr2len)(src) - 1;
4879 if (mb_len > 0 && len >= mb_len)
4880 for (i = 0; i < mb_len; ++i)
4881 {
4882 --len;
4883 ++src;
4884 if (dest != NULL)
4885 *dest++ = *src;
4886 }
4887 }
4888 }
4889 if (dest != NULL)
4890 *dest = NUL;
4891
4892 return m;
4893}
4894
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004895#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004896 void
4897free_insexpand_stuff(void)
4898{
4899 VIM_CLEAR(compl_orig_text);
Yegappan Lakshmanan8658c752021-12-03 11:09:29 +00004900# ifdef FEAT_EVAL
4901 free_callback(&cfu_cb);
4902 free_callback(&ofu_cb);
4903 free_callback(&tsrfu_cb);
4904# endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004905}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004906#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004907
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004908#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004909/*
4910 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
4911 * spelled word, if there is one.
4912 */
4913 static void
4914spell_back_to_badword(void)
4915{
4916 pos_T tpos = curwin->w_cursor;
4917
4918 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
4919 if (curwin->w_cursor.col != tpos.col)
4920 start_arrow(&tpos);
4921}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004922#endif