blob: 73b2218e13bc90331c0f3d0184620fda86863c63 [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()
Bram Moolenaar7591bb32019-03-30 13:53:47 +010040
41# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
42
43// Message for CTRL-X mode, index is ctrl_x_mode.
44static char *ctrl_x_msgs[] =
45{
46 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
47 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
48 NULL, // CTRL_X_SCROLL: depends on state
49 N_(" Whole line completion (^L^N^P)"),
50 N_(" File name completion (^F^N^P)"),
51 N_(" Tag completion (^]^N^P)"),
52 N_(" Path pattern completion (^N^P)"),
53 N_(" Definition completion (^D^N^P)"),
54 NULL, // CTRL_X_FINISHED
55 N_(" Dictionary completion (^K^N^P)"),
56 N_(" Thesaurus completion (^T^N^P)"),
57 N_(" Command-line completion (^V^N^P)"),
58 N_(" User defined completion (^U^N^P)"),
59 N_(" Omni completion (^O^N^P)"),
60 N_(" Spelling suggestion (s^N^P)"),
61 N_(" Keyword Local completion (^N^P)"),
62 NULL, // CTRL_X_EVAL doesn't use msg.
63};
64
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020065#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010066static char *ctrl_x_mode_names[] = {
67 "keyword",
68 "ctrl_x",
69 "unknown", // CTRL_X_SCROLL
70 "whole_line",
71 "files",
72 "tags",
73 "path_patterns",
74 "path_defines",
75 "unknown", // CTRL_X_FINISHED
76 "dictionary",
77 "thesaurus",
78 "cmdline",
79 "function",
80 "omni",
81 "spell",
82 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
83 "eval"
84};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020085#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010086
87/*
88 * Array indexes used for cp_text[].
89 */
90#define CPT_ABBR 0 // "abbr"
91#define CPT_MENU 1 // "menu"
92#define CPT_KIND 2 // "kind"
93#define CPT_INFO 3 // "info"
Bram Moolenaar08928322020-01-04 14:32:48 +010094#define CPT_COUNT 4 // Number of entries
Bram Moolenaar7591bb32019-03-30 13:53:47 +010095
96/*
97 * Structure used to store one match for insert completion.
98 */
99typedef struct compl_S compl_T;
100struct compl_S
101{
102 compl_T *cp_next;
103 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200104 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200105 char_u *(cp_text[CPT_COUNT]); // text for the menu
Bram Moolenaarab782c52020-01-04 19:00:11 +0100106#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100107 typval_T cp_user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100108#endif
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200109 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200110 // cp_flags has CP_FREE_FNAME
111 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200112 int cp_number; // sequence number
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100113};
114
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200115// values for cp_flags
116# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
117# define CP_FREE_FNAME 2 // cp_fname is allocated
118# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
119# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
120# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100121
122static char e_hitend[] = N_("Hit end of paragraph");
123# ifdef FEAT_COMPL_FUNC
124static char e_complwin[] = N_("E839: Completion function changed window");
125static char e_compldel[] = N_("E840: Completion function deleted text");
126# endif
127
128/*
129 * All the current matches are stored in a list.
130 * "compl_first_match" points to the start of the list.
131 * "compl_curr_match" points to the currently selected entry.
132 * "compl_shown_match" is different from compl_curr_match during
133 * ins_compl_get_exp().
134 */
135static compl_T *compl_first_match = NULL;
136static compl_T *compl_curr_match = NULL;
137static compl_T *compl_shown_match = NULL;
138static compl_T *compl_old_match = NULL;
139
140// After using a cursor key <Enter> selects a match in the popup menu,
141// otherwise it inserts a line break.
142static int compl_enter_selects = FALSE;
143
144// When "compl_leader" is not NULL only matches that start with this string
145// are used.
146static char_u *compl_leader = NULL;
147
148static int compl_get_longest = FALSE; // put longest common string
149 // in compl_leader
150
151static int compl_no_insert = FALSE; // FALSE: select & insert
152 // TRUE: noinsert
153static int compl_no_select = FALSE; // FALSE: select & insert
154 // TRUE: noselect
155
156// Selected one of the matches. When FALSE the match was edited or using the
157// longest common string.
158static int compl_used_match;
159
160// didn't finish finding completions.
161static int compl_was_interrupted = FALSE;
162
163// Set when character typed while looking for matches and it means we should
164// stop looking for matches.
165static int compl_interrupted = FALSE;
166
167static int compl_restarting = FALSE; // don't insert match
168
169// When the first completion is done "compl_started" is set. When it's
170// FALSE the word to be completed must be located.
171static int compl_started = FALSE;
172
173// Which Ctrl-X mode are we in?
174static int ctrl_x_mode = CTRL_X_NORMAL;
175
176static int compl_matches = 0;
177static char_u *compl_pattern = NULL;
178static int compl_direction = FORWARD;
179static int compl_shows_dir = FORWARD;
180static int compl_pending = 0; // > 1 for postponed CTRL-N
181static pos_T compl_startpos;
182static colnr_T compl_col = 0; // column where the text starts
183 // that is being completed
184static char_u *compl_orig_text = NULL; // text as it was before
185 // completion started
186static int compl_cont_mode = 0;
187static expand_T compl_xp;
188
189static int compl_opt_refresh_always = FALSE;
190static int compl_opt_suppress_empty = FALSE;
191
Bram Moolenaar08928322020-01-04 14:32:48 +0100192static 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 +0100193static void ins_compl_longest_match(compl_T *match);
194static void ins_compl_del_pum(void);
195static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
196static char_u *find_line_end(char_u *ptr);
197static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100198static int ins_compl_need_restart(void);
199static void ins_compl_new_leader(void);
200static int ins_compl_len(void);
201static void ins_compl_restart(void);
202static void ins_compl_set_original_text(char_u *str);
203static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
204# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
205static void ins_compl_add_list(list_T *list);
206static void ins_compl_add_dict(dict_T *dict);
207# endif
208static int ins_compl_key2dir(int c);
209static int ins_compl_pum_key(int c);
210static int ins_compl_key2count(int c);
211static void show_pum(int prev_w_wrow, int prev_w_leftcol);
212static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100213
214#ifdef FEAT_SPELL
215static void spell_back_to_badword(void);
216static int spell_bad_len = 0; // length of located bad word
217#endif
218
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100219/*
220 * CTRL-X pressed in Insert mode.
221 */
222 void
223ins_ctrl_x(void)
224{
225 // CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
226 // CTRL-V works like CTRL-N
227 if (ctrl_x_mode != CTRL_X_CMDLINE)
228 {
229 // if the next ^X<> won't ADD nothing, then reset
230 // compl_cont_status
231 if (compl_cont_status & CONT_N_ADDS)
232 compl_cont_status |= CONT_INTRPT;
233 else
234 compl_cont_status = 0;
235 // We're not sure which CTRL-X mode it will be yet
236 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
237 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
238 edit_submode_pre = NULL;
239 showmode();
240 }
241}
242
243/*
244 * Functions to check the current CTRL-X mode.
245 */
246int ctrl_x_mode_none(void) { return ctrl_x_mode == 0; }
247int ctrl_x_mode_normal(void) { return ctrl_x_mode == CTRL_X_NORMAL; }
248int ctrl_x_mode_scroll(void) { return ctrl_x_mode == CTRL_X_SCROLL; }
249int ctrl_x_mode_whole_line(void) { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
250int ctrl_x_mode_files(void) { return ctrl_x_mode == CTRL_X_FILES; }
251int ctrl_x_mode_tags(void) { return ctrl_x_mode == CTRL_X_TAGS; }
252int ctrl_x_mode_path_patterns(void) {
253 return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
254int ctrl_x_mode_path_defines(void) {
255 return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
256int ctrl_x_mode_dictionary(void) { return ctrl_x_mode == CTRL_X_DICTIONARY; }
257int ctrl_x_mode_thesaurus(void) { return ctrl_x_mode == CTRL_X_THESAURUS; }
258int ctrl_x_mode_cmdline(void) { return ctrl_x_mode == CTRL_X_CMDLINE; }
259int ctrl_x_mode_function(void) { return ctrl_x_mode == CTRL_X_FUNCTION; }
260int ctrl_x_mode_omni(void) { return ctrl_x_mode == CTRL_X_OMNI; }
261int ctrl_x_mode_spell(void) { return ctrl_x_mode == CTRL_X_SPELL; }
262int ctrl_x_mode_line_or_eval(void) {
263 return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
264
265/*
266 * Whether other than default completion has been selected.
267 */
268 int
269ctrl_x_mode_not_default(void)
270{
271 return ctrl_x_mode != CTRL_X_NORMAL;
272}
273
274/*
275 * Whether CTRL-X was typed without a following character.
276 */
277 int
278ctrl_x_mode_not_defined_yet(void)
279{
280 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
281}
282
283/*
284 * Return TRUE if the 'dict' or 'tsr' option can be used.
285 */
286 int
287has_compl_option(int dict_opt)
288{
289 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200290#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100291 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200292#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100293 )
294 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
295 {
296 ctrl_x_mode = CTRL_X_NORMAL;
297 edit_submode = NULL;
298 msg_attr(dict_opt ? _("'dictionary' option is empty")
299 : _("'thesaurus' option is empty"),
300 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100301 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100302 {
303 vim_beep(BO_COMPL);
304 setcursor();
305 out_flush();
306#ifdef FEAT_EVAL
307 if (!get_vim_var_nr(VV_TESTING))
308#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100309 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100310 }
311 return FALSE;
312 }
313 return TRUE;
314}
315
316/*
317 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
318 * This depends on the current mode.
319 */
320 int
321vim_is_ctrl_x_key(int c)
322{
323 // Always allow ^R - let its results then be checked
324 if (c == Ctrl_R)
325 return TRUE;
326
327 // Accept <PageUp> and <PageDown> if the popup menu is visible.
328 if (ins_compl_pum_key(c))
329 return TRUE;
330
331 switch (ctrl_x_mode)
332 {
333 case 0: // Not in any CTRL-X mode
334 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
335 case CTRL_X_NOT_DEFINED_YET:
336 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
337 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
338 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
339 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
340 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
341 || c == Ctrl_S || c == Ctrl_K || c == 's');
342 case CTRL_X_SCROLL:
343 return (c == Ctrl_Y || c == Ctrl_E);
344 case CTRL_X_WHOLE_LINE:
345 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
346 case CTRL_X_FILES:
347 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
348 case CTRL_X_DICTIONARY:
349 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
350 case CTRL_X_THESAURUS:
351 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
352 case CTRL_X_TAGS:
353 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
354#ifdef FEAT_FIND_ID
355 case CTRL_X_PATH_PATTERNS:
356 return (c == Ctrl_P || c == Ctrl_N);
357 case CTRL_X_PATH_DEFINES:
358 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
359#endif
360 case CTRL_X_CMDLINE:
361 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
362 || c == Ctrl_X);
363#ifdef FEAT_COMPL_FUNC
364 case CTRL_X_FUNCTION:
365 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
366 case CTRL_X_OMNI:
367 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
368#endif
369 case CTRL_X_SPELL:
370 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
371 case CTRL_X_EVAL:
372 return (c == Ctrl_P || c == Ctrl_N);
373 }
374 internal_error("vim_is_ctrl_x_key()");
375 return FALSE;
376}
377
378/*
379 * Return TRUE when character "c" is part of the item currently being
380 * completed. Used to decide whether to abandon complete mode when the menu
381 * is visible.
382 */
383 int
384ins_compl_accept_char(int c)
385{
386 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
387 // When expanding an identifier only accept identifier chars.
388 return vim_isIDc(c);
389
390 switch (ctrl_x_mode)
391 {
392 case CTRL_X_FILES:
393 // When expanding file name only accept file name chars. But not
394 // path separators, so that "proto/<Tab>" expands files in
395 // "proto", not "proto/" as a whole
396 return vim_isfilec(c) && !vim_ispathsep(c);
397
398 case CTRL_X_CMDLINE:
399 case CTRL_X_OMNI:
400 // Command line and Omni completion can work with just about any
401 // printable character, but do stop at white space.
402 return vim_isprintc(c) && !VIM_ISWHITE(c);
403
404 case CTRL_X_WHOLE_LINE:
405 // For while line completion a space can be part of the line.
406 return vim_isprintc(c);
407 }
408 return vim_iswordc(c);
409}
410
411/*
412 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
413 * case of the originally typed text is used, and the case of the completed
414 * text is inferred, ie this tries to work out what case you probably wanted
415 * the rest of the word to be in -- webb
416 */
417 int
418ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200419 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100420 int len,
421 int icase,
422 char_u *fname,
423 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200424 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100425{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200426 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100427 char_u *p;
428 int i, c;
429 int actual_len; // Take multi-byte characters
430 int actual_compl_length; // into account.
431 int min_len;
432 int *wca; // Wide character array.
433 int has_lower = FALSE;
434 int was_letter = FALSE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200435 int flags = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100436
437 if (p_ic && curbuf->b_p_inf && len > 0)
438 {
439 // Infer case of completed part.
440
441 // Find actual length of completion.
442 if (has_mbyte)
443 {
444 p = str;
445 actual_len = 0;
446 while (*p != NUL)
447 {
448 MB_PTR_ADV(p);
449 ++actual_len;
450 }
451 }
452 else
453 actual_len = len;
454
455 // Find actual length of original text.
456 if (has_mbyte)
457 {
458 p = compl_orig_text;
459 actual_compl_length = 0;
460 while (*p != NUL)
461 {
462 MB_PTR_ADV(p);
463 ++actual_compl_length;
464 }
465 }
466 else
467 actual_compl_length = compl_length;
468
469 // "actual_len" may be smaller than "actual_compl_length" when using
470 // thesaurus, only use the minimum when comparing.
471 min_len = actual_len < actual_compl_length
472 ? actual_len : actual_compl_length;
473
474 // Allocate wide character array for the completion and fill it.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200475 wca = ALLOC_MULT(int, actual_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100476 if (wca != NULL)
477 {
478 p = str;
479 for (i = 0; i < actual_len; ++i)
480 if (has_mbyte)
481 wca[i] = mb_ptr2char_adv(&p);
482 else
483 wca[i] = *(p++);
484
485 // Rule 1: Were any chars converted to lower?
486 p = compl_orig_text;
487 for (i = 0; i < min_len; ++i)
488 {
489 if (has_mbyte)
490 c = mb_ptr2char_adv(&p);
491 else
492 c = *(p++);
493 if (MB_ISLOWER(c))
494 {
495 has_lower = TRUE;
496 if (MB_ISUPPER(wca[i]))
497 {
498 // Rule 1 is satisfied.
499 for (i = actual_compl_length; i < actual_len; ++i)
500 wca[i] = MB_TOLOWER(wca[i]);
501 break;
502 }
503 }
504 }
505
506 // Rule 2: No lower case, 2nd consecutive letter converted to
507 // upper case.
508 if (!has_lower)
509 {
510 p = compl_orig_text;
511 for (i = 0; i < min_len; ++i)
512 {
513 if (has_mbyte)
514 c = mb_ptr2char_adv(&p);
515 else
516 c = *(p++);
517 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
518 {
519 // Rule 2 is satisfied.
520 for (i = actual_compl_length; i < actual_len; ++i)
521 wca[i] = MB_TOUPPER(wca[i]);
522 break;
523 }
524 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
525 }
526 }
527
528 // Copy the original case of the part we typed.
529 p = compl_orig_text;
530 for (i = 0; i < min_len; ++i)
531 {
532 if (has_mbyte)
533 c = mb_ptr2char_adv(&p);
534 else
535 c = *(p++);
536 if (MB_ISLOWER(c))
537 wca[i] = MB_TOLOWER(wca[i]);
538 else if (MB_ISUPPER(c))
539 wca[i] = MB_TOUPPER(wca[i]);
540 }
541
542 // Generate encoding specific output from wide character array.
543 // Multi-byte characters can occupy up to five bytes more than
544 // ASCII characters, and we also need one byte for NUL, so stay
545 // six bytes away from the edge of IObuff.
546 p = IObuff;
547 i = 0;
548 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
549 if (has_mbyte)
550 p += (*mb_char2bytes)(wca[i++], p);
551 else
552 *(p++) = wca[i++];
553 *p = NUL;
554
555 vim_free(wca);
556 }
557
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200558 str = IObuff;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100559 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200560 if (cont_s_ipos)
561 flags |= CP_CONT_S_IPOS;
562 if (icase)
563 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200564
Bram Moolenaar08928322020-01-04 14:32:48 +0100565 return ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100566}
567
568/*
569 * Add a match to the list of matches.
570 * If the given string is already in the list of completions, then return
571 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
572 * maybe because alloc() returns NULL, then FAIL is returned.
573 */
574 static int
575ins_compl_add(
576 char_u *str,
577 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100578 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100579 char_u **cptext, // extra text for popup menu or NULL
580 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100581 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200582 int flags_arg,
Bram Moolenaar08928322020-01-04 14:32:48 +0100583 int adup) // accept duplicate match
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100584{
585 compl_T *match;
586 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200587 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100588
589 ui_breakcheck();
590 if (got_int)
591 return FAIL;
592 if (len < 0)
593 len = (int)STRLEN(str);
594
595 // If the same match is already present, don't add it.
596 if (compl_first_match != NULL && !adup)
597 {
598 match = compl_first_match;
599 do
600 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200601 if ( !(match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100602 && STRNCMP(match->cp_str, str, len) == 0
603 && match->cp_str[len] == NUL)
604 return NOTDONE;
605 match = match->cp_next;
606 } while (match != NULL && match != compl_first_match);
607 }
608
609 // Remove any popup menu before changing the list of matches.
610 ins_compl_del_pum();
611
612 // Allocate a new match structure.
613 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200614 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100615 if (match == NULL)
616 return FAIL;
617 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200618 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100619 match->cp_number = 0;
620 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
621 {
622 vim_free(match);
623 return FAIL;
624 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100625
626 // match-fname is:
627 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200628 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100629 // - NULL otherwise. --Acevedo
630 if (fname != NULL
631 && compl_curr_match != NULL
632 && compl_curr_match->cp_fname != NULL
633 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
634 match->cp_fname = compl_curr_match->cp_fname;
635 else if (fname != NULL)
636 {
637 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200638 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100639 }
640 else
641 match->cp_fname = NULL;
642 match->cp_flags = flags;
643
644 if (cptext != NULL)
645 {
646 int i;
647
648 for (i = 0; i < CPT_COUNT; ++i)
649 if (cptext[i] != NULL && *cptext[i] != NUL)
650 match->cp_text[i] = vim_strsave(cptext[i]);
651 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100652#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100653 if (user_data != NULL)
654 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100655#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100656
657 // Link the new match structure in the list of matches.
658 if (compl_first_match == NULL)
659 match->cp_next = match->cp_prev = NULL;
660 else if (dir == FORWARD)
661 {
662 match->cp_next = compl_curr_match->cp_next;
663 match->cp_prev = compl_curr_match;
664 }
665 else // BACKWARD
666 {
667 match->cp_next = compl_curr_match;
668 match->cp_prev = compl_curr_match->cp_prev;
669 }
670 if (match->cp_next)
671 match->cp_next->cp_prev = match;
672 if (match->cp_prev)
673 match->cp_prev->cp_next = match;
674 else // if there's nothing before, it is the first match
675 compl_first_match = match;
676 compl_curr_match = match;
677
678 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200679 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100680 ins_compl_longest_match(match);
681
682 return OK;
683}
684
685/*
686 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200687 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100688 */
689 static int
690ins_compl_equal(compl_T *match, char_u *str, int len)
691{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200692 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200693 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200694 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100695 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
696 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
697}
698
699/*
700 * Reduce the longest common string for match "match".
701 */
702 static void
703ins_compl_longest_match(compl_T *match)
704{
705 char_u *p, *s;
706 int c1, c2;
707 int had_match;
708
709 if (compl_leader == NULL)
710 {
711 // First match, use it as a whole.
712 compl_leader = vim_strsave(match->cp_str);
713 if (compl_leader != NULL)
714 {
715 had_match = (curwin->w_cursor.col > compl_col);
716 ins_compl_delete();
717 ins_bytes(compl_leader + ins_compl_len());
718 ins_redraw(FALSE);
719
720 // When the match isn't there (to avoid matching itself) remove it
721 // again after redrawing.
722 if (!had_match)
723 ins_compl_delete();
724 compl_used_match = FALSE;
725 }
726 }
727 else
728 {
729 // Reduce the text if this match differs from compl_leader.
730 p = compl_leader;
731 s = match->cp_str;
732 while (*p != NUL)
733 {
734 if (has_mbyte)
735 {
736 c1 = mb_ptr2char(p);
737 c2 = mb_ptr2char(s);
738 }
739 else
740 {
741 c1 = *p;
742 c2 = *s;
743 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200744 if ((match->cp_flags & CP_ICASE)
745 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100746 break;
747 if (has_mbyte)
748 {
749 MB_PTR_ADV(p);
750 MB_PTR_ADV(s);
751 }
752 else
753 {
754 ++p;
755 ++s;
756 }
757 }
758
759 if (*p != NUL)
760 {
761 // Leader was shortened, need to change the inserted text.
762 *p = NUL;
763 had_match = (curwin->w_cursor.col > compl_col);
764 ins_compl_delete();
765 ins_bytes(compl_leader + ins_compl_len());
766 ins_redraw(FALSE);
767
768 // When the match isn't there (to avoid matching itself) remove it
769 // again after redrawing.
770 if (!had_match)
771 ins_compl_delete();
772 }
773
774 compl_used_match = FALSE;
775 }
776}
777
778/*
779 * Add an array of matches to the list of matches.
780 * Frees matches[].
781 */
782 static void
783ins_compl_add_matches(
784 int num_matches,
785 char_u **matches,
786 int icase)
787{
788 int i;
789 int add_r = OK;
790 int dir = compl_direction;
791
792 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100793 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200794 icase ? CP_ICASE : 0, FALSE)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100795 // if dir was BACKWARD then honor it just once
796 dir = FORWARD;
797 FreeWild(num_matches, matches);
798}
799
800/*
801 * Make the completion list cyclic.
802 * Return the number of matches (excluding the original).
803 */
804 static int
805ins_compl_make_cyclic(void)
806{
807 compl_T *match;
808 int count = 0;
809
810 if (compl_first_match != NULL)
811 {
812 // Find the end of the list.
813 match = compl_first_match;
814 // there's always an entry for the compl_orig_text, it doesn't count.
815 while (match->cp_next != NULL && match->cp_next != compl_first_match)
816 {
817 match = match->cp_next;
818 ++count;
819 }
820 match->cp_next = compl_first_match;
821 compl_first_match->cp_prev = match;
822 }
823 return count;
824}
825
826/*
827 * Return whether there currently is a shown match.
828 */
829 int
830ins_compl_has_shown_match(void)
831{
832 return compl_shown_match == NULL
833 || compl_shown_match != compl_shown_match->cp_next;
834}
835
836/*
837 * Return whether the shown match is long enough.
838 */
839 int
840ins_compl_long_shown_match(void)
841{
842 return (int)STRLEN(compl_shown_match->cp_str)
843 > curwin->w_cursor.col - compl_col;
844}
845
846/*
847 * Set variables that store noselect and noinsert behavior from the
848 * 'completeopt' value.
849 */
850 void
851completeopt_was_set(void)
852{
853 compl_no_insert = FALSE;
854 compl_no_select = FALSE;
855 if (strstr((char *)p_cot, "noselect") != NULL)
856 compl_no_select = TRUE;
857 if (strstr((char *)p_cot, "noinsert") != NULL)
858 compl_no_insert = TRUE;
859}
860
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100861
862// "compl_match_array" points the currently displayed list of entries in the
863// popup menu. It is NULL when there is no popup menu.
864static pumitem_T *compl_match_array = NULL;
865static int compl_match_arraysize;
866
867/*
868 * Update the screen and when there is any scrolling remove the popup menu.
869 */
870 static void
871ins_compl_upd_pum(void)
872{
873 int h;
874
875 if (compl_match_array != NULL)
876 {
877 h = curwin->w_cline_height;
878 // Update the screen later, before drawing the popup menu over it.
879 pum_call_update_screen();
880 if (h != curwin->w_cline_height)
881 ins_compl_del_pum();
882 }
883}
884
885/*
886 * Remove any popup menu.
887 */
888 static void
889ins_compl_del_pum(void)
890{
891 if (compl_match_array != NULL)
892 {
893 pum_undisplay();
894 VIM_CLEAR(compl_match_array);
895 }
896}
897
898/*
899 * Return TRUE if the popup menu should be displayed.
900 */
901 int
902pum_wanted(void)
903{
904 // 'completeopt' must contain "menu" or "menuone"
905 if (vim_strchr(p_cot, 'm') == NULL)
906 return FALSE;
907
908 // The display looks bad on a B&W display.
909 if (t_colors < 8
910#ifdef FEAT_GUI
911 && !gui.in_use
912#endif
913 )
914 return FALSE;
915 return TRUE;
916}
917
918/*
919 * Return TRUE if there are two or more matches to be shown in the popup menu.
920 * One if 'completopt' contains "menuone".
921 */
922 static int
923pum_enough_matches(void)
924{
925 compl_T *compl;
926 int i;
927
928 // Don't display the popup menu if there are no matches or there is only
929 // one (ignoring the original text).
930 compl = compl_first_match;
931 i = 0;
932 do
933 {
934 if (compl == NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200935 || ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0 && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100936 break;
937 compl = compl->cp_next;
938 } while (compl != compl_first_match);
939
940 if (strstr((char *)p_cot, "menuone") != NULL)
941 return (i >= 1);
942 return (i >= 2);
943}
944
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200945#ifdef FEAT_EVAL
946/*
947 * Allocate Dict for the completed item.
948 * { word, abbr, menu, kind, info }
949 */
950 static dict_T *
951ins_compl_dict_alloc(compl_T *match)
952{
953 dict_T *dict = dict_alloc_lock(VAR_FIXED);
954
955 if (dict != NULL)
956 {
957 dict_add_string(dict, "word", match->cp_str);
958 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
959 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
960 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
961 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
Bram Moolenaar08928322020-01-04 14:32:48 +0100962 if (match->cp_user_data.v_type == VAR_UNKNOWN)
963 dict_add_string(dict, "user_data", (char_u *)"");
964 else
965 dict_add_tv(dict, "user_data", &match->cp_user_data);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200966 }
967 return dict;
968}
969
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200970 static void
971trigger_complete_changed_event(int cur)
972{
973 dict_T *v_event;
974 dict_T *item;
975 static int recursive = FALSE;
976
977 if (recursive)
978 return;
979
980 v_event = get_vim_var_dict(VV_EVENT);
981 if (cur < 0)
982 item = dict_alloc();
983 else
984 item = ins_compl_dict_alloc(compl_curr_match);
985 if (item == NULL)
986 return;
987 dict_add_dict(v_event, "completed_item", item);
988 pum_set_event_info(v_event);
989 dict_set_items_ro(v_event);
990
991 recursive = TRUE;
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +0200992 textwinlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200993 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +0200994 textwinlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200995 recursive = FALSE;
996
997 dict_free_contents(v_event);
998 hash_init(&v_event->dv_hashtab);
999}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001000#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001001
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001002/*
1003 * Show the popup menu for the list of matches.
1004 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1005 */
1006 void
1007ins_compl_show_pum(void)
1008{
1009 compl_T *compl;
1010 compl_T *shown_compl = NULL;
1011 int did_find_shown_match = FALSE;
1012 int shown_match_ok = FALSE;
1013 int i;
1014 int cur = -1;
1015 colnr_T col;
1016 int lead_len = 0;
1017
1018 if (!pum_wanted() || !pum_enough_matches())
1019 return;
1020
1021#if defined(FEAT_EVAL)
1022 // Dirty hard-coded hack: remove any matchparen highlighting.
1023 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
1024#endif
1025
1026 // Update the screen later, before drawing the popup menu over it.
1027 pum_call_update_screen();
1028
1029 if (compl_match_array == NULL)
1030 {
1031 // Need to build the popup menu list.
1032 compl_match_arraysize = 0;
1033 compl = compl_first_match;
1034 if (compl_leader != NULL)
1035 lead_len = (int)STRLEN(compl_leader);
1036 do
1037 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001038 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001039 && (compl_leader == NULL
1040 || ins_compl_equal(compl, compl_leader, lead_len)))
1041 ++compl_match_arraysize;
1042 compl = compl->cp_next;
1043 } while (compl != NULL && compl != compl_first_match);
1044 if (compl_match_arraysize == 0)
1045 return;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001046 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001047 if (compl_match_array != NULL)
1048 {
1049 // If the current match is the original text don't find the first
1050 // match after it, don't highlight anything.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001051 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001052 shown_match_ok = TRUE;
1053
1054 i = 0;
1055 compl = compl_first_match;
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 {
1062 if (!shown_match_ok)
1063 {
1064 if (compl == compl_shown_match || did_find_shown_match)
1065 {
1066 // This item is the shown match or this is the
1067 // first displayed item after the shown match.
1068 compl_shown_match = compl;
1069 did_find_shown_match = TRUE;
1070 shown_match_ok = TRUE;
1071 }
1072 else
1073 // Remember this displayed match for when the
1074 // shown match is just below it.
1075 shown_compl = compl;
1076 cur = i;
1077 }
1078
1079 if (compl->cp_text[CPT_ABBR] != NULL)
1080 compl_match_array[i].pum_text =
1081 compl->cp_text[CPT_ABBR];
1082 else
1083 compl_match_array[i].pum_text = compl->cp_str;
1084 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1085 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1086 if (compl->cp_text[CPT_MENU] != NULL)
1087 compl_match_array[i++].pum_extra =
1088 compl->cp_text[CPT_MENU];
1089 else
1090 compl_match_array[i++].pum_extra = compl->cp_fname;
1091 }
1092
1093 if (compl == compl_shown_match)
1094 {
1095 did_find_shown_match = TRUE;
1096
1097 // When the original text is the shown match don't set
1098 // compl_shown_match.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001099 if (compl->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001100 shown_match_ok = TRUE;
1101
1102 if (!shown_match_ok && shown_compl != NULL)
1103 {
1104 // The shown match isn't displayed, set it to the
1105 // previously displayed match.
1106 compl_shown_match = shown_compl;
1107 shown_match_ok = TRUE;
1108 }
1109 }
1110 compl = compl->cp_next;
1111 } while (compl != NULL && compl != compl_first_match);
1112
1113 if (!shown_match_ok) // no displayed match at all
1114 cur = -1;
1115 }
1116 }
1117 else
1118 {
1119 // popup menu already exists, only need to find the current item.
1120 for (i = 0; i < compl_match_arraysize; ++i)
1121 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1122 || compl_match_array[i].pum_text
1123 == compl_shown_match->cp_text[CPT_ABBR])
1124 {
1125 cur = i;
1126 break;
1127 }
1128 }
1129
1130 if (compl_match_array != NULL)
1131 {
1132 // In Replace mode when a $ is displayed at the end of the line only
1133 // part of the screen would be updated. We do need to redraw here.
1134 dollar_vcol = -1;
1135
1136 // Compute the screen column of the start of the completed text.
1137 // Use the cursor to get all wrapping and other settings right.
1138 col = curwin->w_cursor.col;
1139 curwin->w_cursor.col = compl_col;
1140 pum_display(compl_match_array, compl_match_arraysize, cur);
1141 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001142
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001143#ifdef FEAT_EVAL
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001144 if (has_completechanged())
1145 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001146#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001147 }
1148}
1149
1150#define DICT_FIRST (1) // use just first element in "dict"
1151#define DICT_EXACT (2) // "dict" is the exact name of a file
1152
1153/*
1154 * Add any identifiers that match the given pattern in the list of dictionary
1155 * files "dict_start" to the list of completions.
1156 */
1157 static void
1158ins_compl_dictionaries(
1159 char_u *dict_start,
1160 char_u *pat,
1161 int flags, // DICT_FIRST and/or DICT_EXACT
1162 int thesaurus) // Thesaurus completion
1163{
1164 char_u *dict = dict_start;
1165 char_u *ptr;
1166 char_u *buf;
1167 regmatch_T regmatch;
1168 char_u **files;
1169 int count;
1170 int save_p_scs;
1171 int dir = compl_direction;
1172
1173 if (*dict == NUL)
1174 {
1175#ifdef FEAT_SPELL
1176 // When 'dictionary' is empty and spell checking is enabled use
1177 // "spell".
1178 if (!thesaurus && curwin->w_p_spell)
1179 dict = (char_u *)"spell";
1180 else
1181#endif
1182 return;
1183 }
1184
1185 buf = alloc(LSIZE);
1186 if (buf == NULL)
1187 return;
1188 regmatch.regprog = NULL; // so that we can goto theend
1189
1190 // If 'infercase' is set, don't use 'smartcase' here
1191 save_p_scs = p_scs;
1192 if (curbuf->b_p_inf)
1193 p_scs = FALSE;
1194
1195 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1196 // to only match at the start of a line. Otherwise just match the
1197 // pattern. Also need to double backslashes.
1198 if (ctrl_x_mode_line_or_eval())
1199 {
1200 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1201 size_t len;
1202
1203 if (pat_esc == NULL)
1204 goto theend;
1205 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001206 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001207 if (ptr == NULL)
1208 {
1209 vim_free(pat_esc);
1210 goto theend;
1211 }
1212 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1213 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1214 vim_free(pat_esc);
1215 vim_free(ptr);
1216 }
1217 else
1218 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001219 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001220 if (regmatch.regprog == NULL)
1221 goto theend;
1222 }
1223
1224 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1225 regmatch.rm_ic = ignorecase(pat);
1226 while (*dict != NUL && !got_int && !compl_interrupted)
1227 {
1228 // copy one dictionary file name into buf
1229 if (flags == DICT_EXACT)
1230 {
1231 count = 1;
1232 files = &dict;
1233 }
1234 else
1235 {
1236 // Expand wildcards in the dictionary name, but do not allow
1237 // backticks (for security, the 'dict' option may have been set in
1238 // a modeline).
1239 copy_option_part(&dict, buf, LSIZE, ",");
1240# ifdef FEAT_SPELL
1241 if (!thesaurus && STRCMP(buf, "spell") == 0)
1242 count = -1;
1243 else
1244# endif
1245 if (vim_strchr(buf, '`') != NULL
1246 || expand_wildcards(1, &buf, &count, &files,
1247 EW_FILE|EW_SILENT) != OK)
1248 count = 0;
1249 }
1250
1251# ifdef FEAT_SPELL
1252 if (count == -1)
1253 {
1254 // Complete from active spelling. Skip "\<" in the pattern, we
1255 // don't use it as a RE.
1256 if (pat[0] == '\\' && pat[1] == '<')
1257 ptr = pat + 2;
1258 else
1259 ptr = pat;
1260 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1261 }
1262 else
1263# endif
1264 if (count > 0) // avoid warning for using "files" uninit
1265 {
1266 ins_compl_files(count, files, thesaurus, flags,
1267 &regmatch, buf, &dir);
1268 if (flags != DICT_EXACT)
1269 FreeWild(count, files);
1270 }
1271 if (flags != 0)
1272 break;
1273 }
1274
1275theend:
1276 p_scs = save_p_scs;
1277 vim_regfree(regmatch.regprog);
1278 vim_free(buf);
1279}
1280
1281 static void
1282ins_compl_files(
1283 int count,
1284 char_u **files,
1285 int thesaurus,
1286 int flags,
1287 regmatch_T *regmatch,
1288 char_u *buf,
1289 int *dir)
1290{
1291 char_u *ptr;
1292 int i;
1293 FILE *fp;
1294 int add_r;
1295
1296 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1297 {
1298 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
1299 if (flags != DICT_EXACT)
1300 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001301 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001302 vim_snprintf((char *)IObuff, IOSIZE,
1303 _("Scanning dictionary: %s"), (char *)files[i]);
1304 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1305 }
1306
1307 if (fp != NULL)
1308 {
1309 // Read dictionary file line by line.
1310 // Check each line for a match.
1311 while (!got_int && !compl_interrupted
1312 && !vim_fgets(buf, LSIZE, fp))
1313 {
1314 ptr = buf;
1315 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
1316 {
1317 ptr = regmatch->startp[0];
1318 if (ctrl_x_mode_line_or_eval())
1319 ptr = find_line_end(ptr);
1320 else
1321 ptr = find_word_end(ptr);
1322 add_r = ins_compl_add_infercase(regmatch->startp[0],
1323 (int)(ptr - regmatch->startp[0]),
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001324 p_ic, files[i], *dir, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001325 if (thesaurus)
1326 {
1327 char_u *wstart;
1328
1329 // Add the other matches on the line
1330 ptr = buf;
1331 while (!got_int)
1332 {
1333 // Find start of the next word. Skip white
1334 // space and punctuation.
1335 ptr = find_word_start(ptr);
1336 if (*ptr == NUL || *ptr == NL)
1337 break;
1338 wstart = ptr;
1339
1340 // Find end of the word.
1341 if (has_mbyte)
1342 // Japanese words may have characters in
1343 // different classes, only separate words
1344 // with single-byte non-word characters.
1345 while (*ptr != NUL)
1346 {
1347 int l = (*mb_ptr2len)(ptr);
1348
1349 if (l < 2 && !vim_iswordc(*ptr))
1350 break;
1351 ptr += l;
1352 }
1353 else
1354 ptr = find_word_end(ptr);
1355
1356 // Add the word. Skip the regexp match.
1357 if (wstart != regmatch->startp[0])
1358 add_r = ins_compl_add_infercase(wstart,
1359 (int)(ptr - wstart),
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001360 p_ic, files[i], *dir, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001361 }
1362 }
1363 if (add_r == OK)
1364 // if dir was BACKWARD then honor it just once
1365 *dir = FORWARD;
1366 else if (add_r == FAIL)
1367 break;
1368 // avoid expensive call to vim_regexec() when at end
1369 // of line
1370 if (*ptr == '\n' || got_int)
1371 break;
1372 }
1373 line_breakcheck();
1374 ins_compl_check_keys(50, FALSE);
1375 }
1376 fclose(fp);
1377 }
1378 }
1379}
1380
1381/*
1382 * Find the start of the next word.
1383 * Returns a pointer to the first char of the word. Also stops at a NUL.
1384 */
1385 char_u *
1386find_word_start(char_u *ptr)
1387{
1388 if (has_mbyte)
1389 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1390 ptr += (*mb_ptr2len)(ptr);
1391 else
1392 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1393 ++ptr;
1394 return ptr;
1395}
1396
1397/*
1398 * Find the end of the word. Assumes it starts inside a word.
1399 * Returns a pointer to just after the word.
1400 */
1401 char_u *
1402find_word_end(char_u *ptr)
1403{
1404 int start_class;
1405
1406 if (has_mbyte)
1407 {
1408 start_class = mb_get_class(ptr);
1409 if (start_class > 1)
1410 while (*ptr != NUL)
1411 {
1412 ptr += (*mb_ptr2len)(ptr);
1413 if (mb_get_class(ptr) != start_class)
1414 break;
1415 }
1416 }
1417 else
1418 while (vim_iswordc(*ptr))
1419 ++ptr;
1420 return ptr;
1421}
1422
1423/*
1424 * Find the end of the line, omitting CR and NL at the end.
1425 * Returns a pointer to just after the line.
1426 */
1427 static char_u *
1428find_line_end(char_u *ptr)
1429{
1430 char_u *s;
1431
1432 s = ptr + STRLEN(ptr);
1433 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1434 --s;
1435 return s;
1436}
1437
1438/*
1439 * Free the list of completions
1440 */
1441 static void
1442ins_compl_free(void)
1443{
1444 compl_T *match;
1445 int i;
1446
1447 VIM_CLEAR(compl_pattern);
1448 VIM_CLEAR(compl_leader);
1449
1450 if (compl_first_match == NULL)
1451 return;
1452
1453 ins_compl_del_pum();
1454 pum_clear();
1455
1456 compl_curr_match = compl_first_match;
1457 do
1458 {
1459 match = compl_curr_match;
1460 compl_curr_match = compl_curr_match->cp_next;
1461 vim_free(match->cp_str);
1462 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001463 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001464 vim_free(match->cp_fname);
1465 for (i = 0; i < CPT_COUNT; ++i)
1466 vim_free(match->cp_text[i]);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001467#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +01001468 clear_tv(&match->cp_user_data);
Bram Moolenaarab782c52020-01-04 19:00:11 +01001469#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001470 vim_free(match);
1471 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
1472 compl_first_match = compl_curr_match = NULL;
1473 compl_shown_match = NULL;
1474 compl_old_match = NULL;
1475}
1476
1477 void
1478ins_compl_clear(void)
1479{
1480 compl_cont_status = 0;
1481 compl_started = FALSE;
1482 compl_matches = 0;
1483 VIM_CLEAR(compl_pattern);
1484 VIM_CLEAR(compl_leader);
1485 edit_submode_extra = NULL;
1486 VIM_CLEAR(compl_orig_text);
1487 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001488#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001489 // clear v:completed_item
1490 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001491#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001492}
1493
1494/*
1495 * Return TRUE when Insert completion is active.
1496 */
1497 int
1498ins_compl_active(void)
1499{
1500 return compl_started;
1501}
1502
1503/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001504 * Selected one of the matches. When FALSE the match was edited or using the
1505 * longest common string.
1506 */
1507 int
1508ins_compl_used_match(void)
1509{
1510 return compl_used_match;
1511}
1512
1513/*
1514 * Initialize get longest common string.
1515 */
1516 void
1517ins_compl_init_get_longest(void)
1518{
1519 compl_get_longest = FALSE;
1520}
1521
1522/*
1523 * Returns TRUE when insert completion is interrupted.
1524 */
1525 int
1526ins_compl_interrupted(void)
1527{
1528 return compl_interrupted;
1529}
1530
1531/*
1532 * Returns TRUE if the <Enter> key selects a match in the completion popup
1533 * menu.
1534 */
1535 int
1536ins_compl_enter_selects(void)
1537{
1538 return compl_enter_selects;
1539}
1540
1541/*
1542 * Return the column where the text starts that is being completed
1543 */
1544 colnr_T
1545ins_compl_col(void)
1546{
1547 return compl_col;
1548}
1549
1550/*
1551 * Delete one character before the cursor and show the subset of the matches
1552 * that match the word that is now before the cursor.
1553 * Returns the character to be used, NUL if the work is done and another char
1554 * to be got from the user.
1555 */
1556 int
1557ins_compl_bs(void)
1558{
1559 char_u *line;
1560 char_u *p;
1561
1562 line = ml_get_curline();
1563 p = line + curwin->w_cursor.col;
1564 MB_PTR_BACK(line, p);
1565
1566 // Stop completion when the whole word was deleted. For Omni completion
1567 // allow the word to be deleted, we won't match everything.
1568 // Respect the 'backspace' option.
1569 if ((int)(p - line) - (int)compl_col < 0
1570 || ((int)(p - line) - (int)compl_col == 0
1571 && ctrl_x_mode != CTRL_X_OMNI) || ctrl_x_mode == CTRL_X_EVAL
1572 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1573 - compl_length < 0))
1574 return K_BS;
1575
1576 // Deleted more than what was used to find matches or didn't finish
1577 // finding all matches: need to look for matches all over again.
1578 if (curwin->w_cursor.col <= compl_col + compl_length
1579 || ins_compl_need_restart())
1580 ins_compl_restart();
1581
1582 vim_free(compl_leader);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001583 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001584 if (compl_leader != NULL)
1585 {
1586 ins_compl_new_leader();
1587 if (compl_shown_match != NULL)
1588 // Make sure current match is not a hidden item.
1589 compl_curr_match = compl_shown_match;
1590 return NUL;
1591 }
1592 return K_BS;
1593}
1594
1595/*
1596 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1597 * be called.
1598 */
1599 static int
1600ins_compl_need_restart(void)
1601{
1602 // Return TRUE if we didn't complete finding matches or when the
1603 // 'completefunc' returned "always" in the "refresh" dictionary item.
1604 return compl_was_interrupted
1605 || ((ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
1606 && compl_opt_refresh_always);
1607}
1608
1609/*
1610 * Called after changing "compl_leader".
1611 * Show the popup menu with a different set of matches.
1612 * May also search for matches again if the previous search was interrupted.
1613 */
1614 static void
1615ins_compl_new_leader(void)
1616{
1617 ins_compl_del_pum();
1618 ins_compl_delete();
1619 ins_bytes(compl_leader + ins_compl_len());
1620 compl_used_match = FALSE;
1621
1622 if (compl_started)
1623 ins_compl_set_original_text(compl_leader);
1624 else
1625 {
1626#ifdef FEAT_SPELL
1627 spell_bad_len = 0; // need to redetect bad word
1628#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001629 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001630 // the popup menu display the changed text before the cursor. Set
1631 // "compl_restarting" to avoid that the first match is inserted.
1632 pum_call_update_screen();
1633#ifdef FEAT_GUI
1634 if (gui.in_use)
1635 {
1636 // Show the cursor after the match, not after the redrawn text.
1637 setcursor();
1638 out_flush_cursor(FALSE, FALSE);
1639 }
1640#endif
1641 compl_restarting = TRUE;
1642 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1643 compl_cont_status = 0;
1644 compl_restarting = FALSE;
1645 }
1646
1647 compl_enter_selects = !compl_used_match;
1648
1649 // Show the popup menu with a different set of matches.
1650 ins_compl_show_pum();
1651
1652 // Don't let Enter select the original text when there is no popup menu.
1653 if (compl_match_array == NULL)
1654 compl_enter_selects = FALSE;
1655}
1656
1657/*
1658 * Return the length of the completion, from the completion start column to
1659 * the cursor column. Making sure it never goes below zero.
1660 */
1661 static int
1662ins_compl_len(void)
1663{
1664 int off = (int)curwin->w_cursor.col - (int)compl_col;
1665
1666 if (off < 0)
1667 return 0;
1668 return off;
1669}
1670
1671/*
1672 * Append one character to the match leader. May reduce the number of
1673 * matches.
1674 */
1675 void
1676ins_compl_addleader(int c)
1677{
1678 int cc;
1679
1680 if (stop_arrow() == FAIL)
1681 return;
1682 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
1683 {
1684 char_u buf[MB_MAXBYTES + 1];
1685
1686 (*mb_char2bytes)(c, buf);
1687 buf[cc] = NUL;
1688 ins_char_bytes(buf, cc);
1689 if (compl_opt_refresh_always)
1690 AppendToRedobuff(buf);
1691 }
1692 else
1693 {
1694 ins_char(c);
1695 if (compl_opt_refresh_always)
1696 AppendCharToRedobuff(c);
1697 }
1698
1699 // If we didn't complete finding matches we must search again.
1700 if (ins_compl_need_restart())
1701 ins_compl_restart();
1702
1703 // When 'always' is set, don't reset compl_leader. While completing,
1704 // cursor doesn't point original position, changing compl_leader would
1705 // break redo.
1706 if (!compl_opt_refresh_always)
1707 {
1708 vim_free(compl_leader);
1709 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001710 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001711 if (compl_leader != NULL)
1712 ins_compl_new_leader();
1713 }
1714}
1715
1716/*
1717 * Setup for finding completions again without leaving CTRL-X mode. Used when
1718 * BS or a key was typed while still searching for matches.
1719 */
1720 static void
1721ins_compl_restart(void)
1722{
1723 ins_compl_free();
1724 compl_started = FALSE;
1725 compl_matches = 0;
1726 compl_cont_status = 0;
1727 compl_cont_mode = 0;
1728}
1729
1730/*
1731 * Set the first match, the original text.
1732 */
1733 static void
1734ins_compl_set_original_text(char_u *str)
1735{
1736 char_u *p;
1737
1738 // Replace the original text entry.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001739 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly be
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001740 // at the last item for backward completion
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001741 if (compl_first_match->cp_flags & CP_ORIGINAL_TEXT) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001742 {
1743 p = vim_strsave(str);
1744 if (p != NULL)
1745 {
1746 vim_free(compl_first_match->cp_str);
1747 compl_first_match->cp_str = p;
1748 }
1749 }
1750 else if (compl_first_match->cp_prev != NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001751 && (compl_first_match->cp_prev->cp_flags & CP_ORIGINAL_TEXT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001752 {
1753 p = vim_strsave(str);
1754 if (p != NULL)
1755 {
1756 vim_free(compl_first_match->cp_prev->cp_str);
1757 compl_first_match->cp_prev->cp_str = p;
1758 }
1759 }
1760}
1761
1762/*
1763 * Append one character to the match leader. May reduce the number of
1764 * matches.
1765 */
1766 void
1767ins_compl_addfrommatch(void)
1768{
1769 char_u *p;
1770 int len = (int)curwin->w_cursor.col - (int)compl_col;
1771 int c;
1772 compl_T *cp;
1773
1774 p = compl_shown_match->cp_str;
1775 if ((int)STRLEN(p) <= len) // the match is too short
1776 {
1777 // When still at the original match use the first entry that matches
1778 // the leader.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001779 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001780 {
1781 p = NULL;
1782 for (cp = compl_shown_match->cp_next; cp != NULL
1783 && cp != compl_first_match; cp = cp->cp_next)
1784 {
1785 if (compl_leader == NULL
1786 || ins_compl_equal(cp, compl_leader,
1787 (int)STRLEN(compl_leader)))
1788 {
1789 p = cp->cp_str;
1790 break;
1791 }
1792 }
1793 if (p == NULL || (int)STRLEN(p) <= len)
1794 return;
1795 }
1796 else
1797 return;
1798 }
1799 p += len;
1800 c = PTR2CHAR(p);
1801 ins_compl_addleader(c);
1802}
1803
1804/*
1805 * Prepare for Insert mode completion, or stop it.
1806 * Called just after typing a character in Insert mode.
1807 * Returns TRUE when the character is not to be inserted;
1808 */
1809 int
1810ins_compl_prep(int c)
1811{
1812 char_u *ptr;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001813#ifdef FEAT_CINDENT
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001814 int want_cindent;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001815#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001816 int retval = FALSE;
Bram Moolenaar17e04782020-01-17 18:58:59 +01001817 int prev_mode = ctrl_x_mode;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001818
1819 // Forget any previous 'special' messages if this is actually
1820 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
1821 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
1822 edit_submode_extra = NULL;
1823
1824 // Ignore end of Select mode mapping and mouse scroll buttons.
1825 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
Bram Moolenaar957cf672020-11-12 14:21:06 +01001826 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001827 return retval;
1828
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01001829#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02001830 // Ignore mouse events in a popup window
1831 if (is_mouse_key(c))
1832 {
1833 // Ignore drag and release events, the position does not need to be in
1834 // the popup and it may have just closed.
1835 if (c == K_LEFTRELEASE
1836 || c == K_LEFTRELEASE_NM
1837 || c == K_MIDDLERELEASE
1838 || c == K_RIGHTRELEASE
1839 || c == K_X1RELEASE
1840 || c == K_X2RELEASE
1841 || c == K_LEFTDRAG
1842 || c == K_MIDDLEDRAG
1843 || c == K_RIGHTDRAG
1844 || c == K_X1DRAG
1845 || c == K_X2DRAG)
1846 return retval;
1847 if (popup_visible)
1848 {
1849 int row = mouse_row;
1850 int col = mouse_col;
1851 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
1852
1853 if (wp != NULL && WIN_IS_POPUP(wp))
1854 return retval;
1855 }
1856 }
1857#endif
1858
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001859 // Set "compl_get_longest" when finding the first matches.
1860 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
1861 || (ctrl_x_mode == CTRL_X_NORMAL && !compl_started))
1862 {
1863 compl_get_longest = (strstr((char *)p_cot, "longest") != NULL);
1864 compl_used_match = TRUE;
1865
1866 }
1867
1868 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
1869 {
1870 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
1871 // it will be yet. Now we decide.
1872 switch (c)
1873 {
1874 case Ctrl_E:
1875 case Ctrl_Y:
1876 ctrl_x_mode = CTRL_X_SCROLL;
1877 if (!(State & REPLACE_FLAG))
1878 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
1879 else
1880 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
1881 edit_submode_pre = NULL;
1882 showmode();
1883 break;
1884 case Ctrl_L:
1885 ctrl_x_mode = CTRL_X_WHOLE_LINE;
1886 break;
1887 case Ctrl_F:
1888 ctrl_x_mode = CTRL_X_FILES;
1889 break;
1890 case Ctrl_K:
1891 ctrl_x_mode = CTRL_X_DICTIONARY;
1892 break;
1893 case Ctrl_R:
1894 // Simply allow ^R to happen without affecting ^X mode
1895 break;
1896 case Ctrl_T:
1897 ctrl_x_mode = CTRL_X_THESAURUS;
1898 break;
1899#ifdef FEAT_COMPL_FUNC
1900 case Ctrl_U:
1901 ctrl_x_mode = CTRL_X_FUNCTION;
1902 break;
1903 case Ctrl_O:
1904 ctrl_x_mode = CTRL_X_OMNI;
1905 break;
1906#endif
1907 case 's':
1908 case Ctrl_S:
1909 ctrl_x_mode = CTRL_X_SPELL;
1910#ifdef FEAT_SPELL
1911 ++emsg_off; // Avoid getting the E756 error twice.
1912 spell_back_to_badword();
1913 --emsg_off;
1914#endif
1915 break;
1916 case Ctrl_RSB:
1917 ctrl_x_mode = CTRL_X_TAGS;
1918 break;
1919#ifdef FEAT_FIND_ID
1920 case Ctrl_I:
1921 case K_S_TAB:
1922 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
1923 break;
1924 case Ctrl_D:
1925 ctrl_x_mode = CTRL_X_PATH_DEFINES;
1926 break;
1927#endif
1928 case Ctrl_V:
1929 case Ctrl_Q:
1930 ctrl_x_mode = CTRL_X_CMDLINE;
1931 break;
1932 case Ctrl_P:
1933 case Ctrl_N:
1934 // ^X^P means LOCAL expansion if nothing interrupted (eg we
1935 // just started ^X mode, or there were enough ^X's to cancel
1936 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
1937 // do normal expansion when interrupting a different mode (say
1938 // ^X^F^X^P or ^P^X^X^P, see below)
1939 // nothing changes if interrupting mode 0, (eg, the flag
1940 // doesn't change when going to ADDING mode -- Acevedo
1941 if (!(compl_cont_status & CONT_INTRPT))
1942 compl_cont_status |= CONT_LOCAL;
1943 else if (compl_cont_mode != 0)
1944 compl_cont_status &= ~CONT_LOCAL;
1945 // FALLTHROUGH
1946 default:
1947 // If we have typed at least 2 ^X's... for modes != 0, we set
1948 // compl_cont_status = 0 (eg, as if we had just started ^X
1949 // mode).
1950 // For mode 0, we set "compl_cont_mode" to an impossible
1951 // value, in both cases ^X^X can be used to restart the same
1952 // mode (avoiding ADDING mode).
1953 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
1954 // 'complete' and local ^P expansions respectively.
1955 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
1956 // mode -- Acevedo
1957 if (c == Ctrl_X)
1958 {
1959 if (compl_cont_mode != 0)
1960 compl_cont_status = 0;
1961 else
1962 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
1963 }
1964 ctrl_x_mode = CTRL_X_NORMAL;
1965 edit_submode = NULL;
1966 showmode();
1967 break;
1968 }
1969 }
1970 else if (ctrl_x_mode != CTRL_X_NORMAL)
1971 {
1972 // We're already in CTRL-X mode, do we stay in it?
1973 if (!vim_is_ctrl_x_key(c))
1974 {
1975 if (ctrl_x_mode == CTRL_X_SCROLL)
1976 ctrl_x_mode = CTRL_X_NORMAL;
1977 else
1978 ctrl_x_mode = CTRL_X_FINISHED;
1979 edit_submode = NULL;
1980 }
1981 showmode();
1982 }
1983
1984 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
1985 {
1986 // Show error message from attempted keyword completion (probably
1987 // 'Pattern not found') until another key is hit, then go back to
1988 // showing what mode we are in.
1989 showmode();
1990 if ((ctrl_x_mode == CTRL_X_NORMAL && c != Ctrl_N && c != Ctrl_P
1991 && c != Ctrl_R && !ins_compl_pum_key(c))
1992 || ctrl_x_mode == CTRL_X_FINISHED)
1993 {
1994 // Get here when we have finished typing a sequence of ^N and
1995 // ^P or other completion characters in CTRL-X mode. Free up
1996 // memory that was used, and make sure we can redo the insert.
1997 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
1998 {
1999 // If any of the original typed text has been changed, eg when
2000 // ignorecase is set, we must add back-spaces to the redo
2001 // buffer. We add as few as necessary to delete just the part
2002 // of the original text that has changed.
2003 // When using the longest match, edited the match or used
2004 // CTRL-E then don't use the current match.
2005 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
2006 ptr = compl_curr_match->cp_str;
2007 else
2008 ptr = NULL;
2009 ins_compl_fixRedoBufForLeader(ptr);
2010 }
2011
2012#ifdef FEAT_CINDENT
Bram Moolenaarb20b9e12019-09-21 20:48:04 +02002013 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002014#endif
2015 // When completing whole lines: fix indent for 'cindent'.
2016 // Otherwise, break line if it's too long.
2017 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2018 {
2019#ifdef FEAT_CINDENT
2020 // re-indent the current line
2021 if (want_cindent)
2022 {
2023 do_c_expr_indent();
2024 want_cindent = FALSE; // don't do it again
2025 }
2026#endif
2027 }
2028 else
2029 {
2030 int prev_col = curwin->w_cursor.col;
2031
2032 // put the cursor on the last char, for 'tw' formatting
2033 if (prev_col > 0)
2034 dec_cursor();
2035 // only format when something was inserted
2036 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2037 insertchar(NUL, 0, -1);
2038 if (prev_col > 0
2039 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2040 inc_cursor();
2041 }
2042
2043 // If the popup menu is displayed pressing CTRL-Y means accepting
2044 // the selection without inserting anything. When
2045 // compl_enter_selects is set the Enter key does the same.
2046 if ((c == Ctrl_Y || (compl_enter_selects
2047 && (c == CAR || c == K_KENTER || c == NL)))
2048 && pum_visible())
2049 retval = TRUE;
2050
2051 // CTRL-E means completion is Ended, go back to the typed text.
2052 // but only do this, if the Popup is still visible
2053 if (c == Ctrl_E)
2054 {
2055 ins_compl_delete();
2056 if (compl_leader != NULL)
2057 ins_bytes(compl_leader + ins_compl_len());
2058 else if (compl_first_match != NULL)
2059 ins_bytes(compl_orig_text + ins_compl_len());
2060 retval = TRUE;
2061 }
2062
2063 auto_format(FALSE, TRUE);
2064
Bram Moolenaar3f169ce2020-01-26 22:43:31 +01002065 // Trigger the CompleteDonePre event to give scripts a chance to
2066 // act upon the completion before clearing the info, and restore
2067 // ctrl_x_mode, so that complete_info() can be used.
Bram Moolenaarda812e22020-01-26 18:35:31 +01002068 ctrl_x_mode = prev_mode;
Bram Moolenaar3f169ce2020-01-26 22:43:31 +01002069 ins_apply_autocmds(EVENT_COMPLETEDONEPRE);
Bram Moolenaar17e04782020-01-17 18:58:59 +01002070
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002071 ins_compl_free();
2072 compl_started = FALSE;
2073 compl_matches = 0;
2074 if (!shortmess(SHM_COMPLETIONMENU))
2075 msg_clr_cmdline(); // necessary for "noshowmode"
2076 ctrl_x_mode = CTRL_X_NORMAL;
2077 compl_enter_selects = FALSE;
2078 if (edit_submode != NULL)
2079 {
2080 edit_submode = NULL;
2081 showmode();
2082 }
2083
2084#ifdef FEAT_CMDWIN
2085 if (c == Ctrl_C && cmdwin_type != 0)
2086 // Avoid the popup menu remains displayed when leaving the
2087 // command line window.
2088 update_screen(0);
2089#endif
2090#ifdef FEAT_CINDENT
2091 // Indent now if a key was typed that is in 'cinkeys'.
2092 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2093 do_c_expr_indent();
2094#endif
Bram Moolenaar3f169ce2020-01-26 22:43:31 +01002095 // Trigger the CompleteDone event to give scripts a chance to act
2096 // upon the end of completion.
2097 ins_apply_autocmds(EVENT_COMPLETEDONE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002098 }
2099 }
2100 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2101 // Trigger the CompleteDone event to give scripts a chance to act
2102 // upon the (possibly failed) completion.
2103 ins_apply_autocmds(EVENT_COMPLETEDONE);
2104
2105 // reset continue_* if we left expansion-mode, if we stay they'll be
2106 // (re)set properly in ins_complete()
2107 if (!vim_is_ctrl_x_key(c))
2108 {
2109 compl_cont_status = 0;
2110 compl_cont_mode = 0;
2111 }
2112
2113 return retval;
2114}
2115
2116/*
2117 * Fix the redo buffer for the completion leader replacing some of the typed
2118 * text. This inserts backspaces and appends the changed text.
2119 * "ptr" is the known leader text or NUL.
2120 */
2121 static void
2122ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2123{
2124 int len;
2125 char_u *p;
2126 char_u *ptr = ptr_arg;
2127
2128 if (ptr == NULL)
2129 {
2130 if (compl_leader != NULL)
2131 ptr = compl_leader;
2132 else
2133 return; // nothing to do
2134 }
2135 if (compl_orig_text != NULL)
2136 {
2137 p = compl_orig_text;
2138 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2139 ;
2140 if (len > 0)
2141 len -= (*mb_head_off)(p, p + len);
2142 for (p += len; *p != NUL; MB_PTR_ADV(p))
2143 AppendCharToRedobuff(K_BS);
2144 }
2145 else
2146 len = 0;
2147 if (ptr != NULL)
2148 AppendToRedobuffLit(ptr + len, -1);
2149}
2150
2151/*
2152 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2153 * (depending on flag) starting from buf and looking for a non-scanned
2154 * buffer (other than curbuf). curbuf is special, if it is called with
2155 * buf=curbuf then it has to be the first call for a given flag/expansion.
2156 *
2157 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2158 */
2159 static buf_T *
2160ins_compl_next_buf(buf_T *buf, int flag)
2161{
2162 static win_T *wp = NULL;
2163
2164 if (flag == 'w') // just windows
2165 {
2166 if (buf == curbuf || wp == NULL) // first call for this flag/expansion
2167 wp = curwin;
2168 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2169 && wp->w_buffer->b_scanned)
2170 ;
2171 buf = wp->w_buffer;
2172 }
2173 else
2174 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2175 // (unlisted buffers)
2176 // When completing whole lines skip unloaded buffers.
2177 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2178 && ((flag == 'U'
2179 ? buf->b_p_bl
2180 : (!buf->b_p_bl
2181 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2182 || buf->b_scanned))
2183 ;
2184 return buf;
2185}
2186
2187#ifdef FEAT_COMPL_FUNC
2188/*
2189 * Execute user defined complete function 'completefunc' or 'omnifunc', and
2190 * get matches in "matches".
2191 */
2192 static void
2193expand_by_function(
2194 int type, // CTRL_X_OMNI or CTRL_X_FUNCTION
2195 char_u *base)
2196{
2197 list_T *matchlist = NULL;
2198 dict_T *matchdict = NULL;
2199 typval_T args[3];
2200 char_u *funcname;
2201 pos_T pos;
2202 win_T *curwin_save;
2203 buf_T *curbuf_save;
2204 typval_T rettv;
2205 int save_State = State;
2206
2207 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
2208 if (*funcname == NUL)
2209 return;
2210
2211 // Call 'completefunc' to obtain the list of matches.
2212 args[0].v_type = VAR_NUMBER;
2213 args[0].vval.v_number = 0;
2214 args[1].v_type = VAR_STRING;
2215 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2216 args[2].v_type = VAR_UNKNOWN;
2217
2218 pos = curwin->w_cursor;
2219 curwin_save = curwin;
2220 curbuf_save = curbuf;
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02002221 // Lock the text to avoid weird things from happening. Do allow switching
2222 // to another window temporarily.
Bram Moolenaarff06f282020-04-21 22:01:14 +02002223 ++textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002224
2225 // Call a function, which returns a list or dict.
2226 if (call_vim_function(funcname, 2, args, &rettv) == OK)
2227 {
2228 switch (rettv.v_type)
2229 {
2230 case VAR_LIST:
2231 matchlist = rettv.vval.v_list;
2232 break;
2233 case VAR_DICT:
2234 matchdict = rettv.vval.v_dict;
2235 break;
2236 case VAR_SPECIAL:
2237 if (rettv.vval.v_number == VVAL_NONE)
2238 compl_opt_suppress_empty = TRUE;
2239 // FALLTHROUGH
2240 default:
2241 // TODO: Give error message?
2242 clear_tv(&rettv);
2243 break;
2244 }
2245 }
Bram Moolenaarff06f282020-04-21 22:01:14 +02002246 --textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002247
2248 if (curwin_save != curwin || curbuf_save != curbuf)
2249 {
2250 emsg(_(e_complwin));
2251 goto theend;
2252 }
2253 curwin->w_cursor = pos; // restore the cursor position
2254 validate_cursor();
2255 if (!EQUAL_POS(curwin->w_cursor, pos))
2256 {
2257 emsg(_(e_compldel));
2258 goto theend;
2259 }
2260
2261 if (matchlist != NULL)
2262 ins_compl_add_list(matchlist);
2263 else if (matchdict != NULL)
2264 ins_compl_add_dict(matchdict);
2265
2266theend:
2267 // Restore State, it might have been changed.
2268 State = save_State;
2269
2270 if (matchdict != NULL)
2271 dict_unref(matchdict);
2272 if (matchlist != NULL)
2273 list_unref(matchlist);
2274}
2275#endif // FEAT_COMPL_FUNC
2276
2277#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2278/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002279 * Add a match to the list of matches from a typeval_T.
2280 * If the given string is already in the list of completions, then return
2281 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2282 * maybe because alloc() returns NULL, then FAIL is returned.
2283 */
2284 static int
2285ins_compl_add_tv(typval_T *tv, int dir)
2286{
2287 char_u *word;
2288 int dup = FALSE;
2289 int empty = FALSE;
2290 int flags = 0;
2291 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002292 typval_T user_data;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002293
Bram Moolenaar08928322020-01-04 14:32:48 +01002294 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002295 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2296 {
2297 word = dict_get_string(tv->vval.v_dict, (char_u *)"word", FALSE);
2298 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict,
2299 (char_u *)"abbr", FALSE);
2300 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict,
2301 (char_u *)"menu", FALSE);
2302 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict,
2303 (char_u *)"kind", FALSE);
2304 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict,
2305 (char_u *)"info", FALSE);
Bram Moolenaar08928322020-01-04 14:32:48 +01002306 dict_get_tv(tv->vval.v_dict, (char_u *)"user_data", &user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002307 if (dict_get_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL
2308 && dict_get_number(tv->vval.v_dict, (char_u *)"icase"))
2309 flags |= CP_ICASE;
2310 if (dict_get_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
2311 dup = dict_get_number(tv->vval.v_dict, (char_u *)"dup");
2312 if (dict_get_string(tv->vval.v_dict, (char_u *)"empty", FALSE) != NULL)
2313 empty = dict_get_number(tv->vval.v_dict, (char_u *)"empty");
2314 if (dict_get_string(tv->vval.v_dict, (char_u *)"equal", FALSE) != NULL
2315 && dict_get_number(tv->vval.v_dict, (char_u *)"equal"))
2316 flags |= CP_EQUAL;
2317 }
2318 else
2319 {
2320 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002321 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002322 }
2323 if (word == NULL || (!empty && *word == NUL))
2324 return FAIL;
Bram Moolenaar08928322020-01-04 14:32:48 +01002325 return ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002326}
2327
2328/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002329 * Add completions from a list.
2330 */
2331 static void
2332ins_compl_add_list(list_T *list)
2333{
2334 listitem_T *li;
2335 int dir = compl_direction;
2336
2337 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002338 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002339 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002340 {
2341 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
2342 // if dir was BACKWARD then honor it just once
2343 dir = FORWARD;
2344 else if (did_emsg)
2345 break;
2346 }
2347}
2348
2349/*
2350 * Add completions from a dict.
2351 */
2352 static void
2353ins_compl_add_dict(dict_T *dict)
2354{
2355 dictitem_T *di_refresh;
2356 dictitem_T *di_words;
2357
2358 // Check for optional "refresh" item.
2359 compl_opt_refresh_always = FALSE;
2360 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2361 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2362 {
2363 char_u *v = di_refresh->di_tv.vval.v_string;
2364
2365 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2366 compl_opt_refresh_always = TRUE;
2367 }
2368
2369 // Add completions from a "words" list.
2370 di_words = dict_find(dict, (char_u *)"words", 5);
2371 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2372 ins_compl_add_list(di_words->di_tv.vval.v_list);
2373}
2374
2375/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002376 * Start completion for the complete() function.
2377 * "startcol" is where the matched text starts (1 is first column).
2378 * "list" is the list of matches.
2379 */
2380 static void
2381set_completion(colnr_T startcol, list_T *list)
2382{
2383 int save_w_wrow = curwin->w_wrow;
2384 int save_w_leftcol = curwin->w_leftcol;
2385 int flags = CP_ORIGINAL_TEXT;
2386
2387 // If already doing completions stop it.
2388 if (ctrl_x_mode != CTRL_X_NORMAL)
2389 ins_compl_prep(' ');
2390 ins_compl_clear();
2391 ins_compl_free();
2392
2393 compl_direction = FORWARD;
2394 if (startcol > curwin->w_cursor.col)
2395 startcol = curwin->w_cursor.col;
2396 compl_col = startcol;
2397 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2398 // compl_pattern doesn't need to be set
2399 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2400 if (p_ic)
2401 flags |= CP_ICASE;
2402 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar08928322020-01-04 14:32:48 +01002403 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002404 return;
2405
2406 ctrl_x_mode = CTRL_X_EVAL;
2407
2408 ins_compl_add_list(list);
2409 compl_matches = ins_compl_make_cyclic();
2410 compl_started = TRUE;
2411 compl_used_match = TRUE;
2412 compl_cont_status = 0;
2413
2414 compl_curr_match = compl_first_match;
2415 if (compl_no_insert || compl_no_select)
2416 {
2417 ins_complete(K_DOWN, FALSE);
2418 if (compl_no_select)
2419 // Down/Up has no real effect.
2420 ins_complete(K_UP, FALSE);
2421 }
2422 else
2423 ins_complete(Ctrl_N, FALSE);
2424 compl_enter_selects = compl_no_insert;
2425
2426 // Lazily show the popup menu, unless we got interrupted.
2427 if (!compl_interrupted)
2428 show_pum(save_w_wrow, save_w_leftcol);
2429 out_flush();
2430}
2431
2432/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002433 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002434 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002435 void
2436f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002437{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002438 int startcol;
Bram Moolenaarff06f282020-04-21 22:01:14 +02002439 int save_textlock = textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002440
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002441 if ((State & INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002442 {
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002443 emsg(_("E785: complete() can only be used in Insert mode"));
2444 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002445 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002446
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02002447 // "textlock" is set when evaluating 'completefunc' but we can change
2448 // text here.
Bram Moolenaarff06f282020-04-21 22:01:14 +02002449 textlock = 0;
2450
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002451 // Check for undo allowed here, because if something was already inserted
2452 // the line was already saved for undo and this check isn't done.
2453 if (!undo_allowed())
2454 return;
2455
2456 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002457 emsg(_(e_invarg));
Bram Moolenaarff06f282020-04-21 22:01:14 +02002458 else
2459 {
2460 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
2461 if (startcol > 0)
2462 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002463 }
Bram Moolenaarff06f282020-04-21 22:01:14 +02002464 textlock = save_textlock;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002465}
2466
2467/*
2468 * "complete_add()" function
2469 */
2470 void
2471f_complete_add(typval_T *argvars, typval_T *rettv)
2472{
2473 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
2474}
2475
2476/*
2477 * "complete_check()" function
2478 */
2479 void
2480f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
2481{
2482 int saved = RedrawingDisabled;
2483
2484 RedrawingDisabled = 0;
2485 ins_compl_check_keys(0, TRUE);
2486 rettv->vval.v_number = ins_compl_interrupted();
2487 RedrawingDisabled = saved;
2488}
2489
2490/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002491 * Return Insert completion mode name string
2492 */
2493 static char_u *
2494ins_compl_mode(void)
2495{
2496 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || compl_started)
2497 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
2498
2499 return (char_u *)"";
2500}
2501
Bram Moolenaarf9d51352020-10-26 19:22:42 +01002502 static void
2503ins_compl_update_sequence_numbers()
2504{
2505 int number = 0;
2506 compl_T *match;
2507
2508 if (compl_direction == FORWARD)
2509 {
2510 // search backwards for the first valid (!= -1) number.
2511 // This should normally succeed already at the first loop
2512 // cycle, so it's fast!
2513 for (match = compl_curr_match->cp_prev; match != NULL
2514 && match != compl_first_match;
2515 match = match->cp_prev)
2516 if (match->cp_number != -1)
2517 {
2518 number = match->cp_number;
2519 break;
2520 }
2521 if (match != NULL)
2522 // go up and assign all numbers which are not assigned
2523 // yet
2524 for (match = match->cp_next;
2525 match != NULL && match->cp_number == -1;
2526 match = match->cp_next)
2527 match->cp_number = ++number;
2528 }
2529 else // BACKWARD
2530 {
2531 // search forwards (upwards) for the first valid (!= -1)
2532 // number. This should normally succeed already at the
2533 // first loop cycle, so it's fast!
2534 for (match = compl_curr_match->cp_next; match != NULL
2535 && match != compl_first_match;
2536 match = match->cp_next)
2537 if (match->cp_number != -1)
2538 {
2539 number = match->cp_number;
2540 break;
2541 }
2542 if (match != NULL)
2543 // go down and assign all numbers which are not
2544 // assigned yet
2545 for (match = match->cp_prev; match
2546 && match->cp_number == -1;
2547 match = match->cp_prev)
2548 match->cp_number = ++number;
2549 }
2550}
2551
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002552/*
2553 * Get complete information
2554 */
2555 static void
2556get_complete_info(list_T *what_list, dict_T *retdict)
2557{
2558 int ret = OK;
2559 listitem_T *item;
2560#define CI_WHAT_MODE 0x01
2561#define CI_WHAT_PUM_VISIBLE 0x02
2562#define CI_WHAT_ITEMS 0x04
2563#define CI_WHAT_SELECTED 0x08
2564#define CI_WHAT_INSERTED 0x10
2565#define CI_WHAT_ALL 0xff
2566 int what_flag;
2567
2568 if (what_list == NULL)
2569 what_flag = CI_WHAT_ALL;
2570 else
2571 {
2572 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002573 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002574 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002575 {
2576 char_u *what = tv_get_string(&item->li_tv);
2577
2578 if (STRCMP(what, "mode") == 0)
2579 what_flag |= CI_WHAT_MODE;
2580 else if (STRCMP(what, "pum_visible") == 0)
2581 what_flag |= CI_WHAT_PUM_VISIBLE;
2582 else if (STRCMP(what, "items") == 0)
2583 what_flag |= CI_WHAT_ITEMS;
2584 else if (STRCMP(what, "selected") == 0)
2585 what_flag |= CI_WHAT_SELECTED;
2586 else if (STRCMP(what, "inserted") == 0)
2587 what_flag |= CI_WHAT_INSERTED;
2588 }
2589 }
2590
2591 if (ret == OK && (what_flag & CI_WHAT_MODE))
2592 ret = dict_add_string(retdict, "mode", ins_compl_mode());
2593
2594 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
2595 ret = dict_add_number(retdict, "pum_visible", pum_visible());
2596
2597 if (ret == OK && (what_flag & CI_WHAT_ITEMS))
2598 {
2599 list_T *li;
2600 dict_T *di;
2601 compl_T *match;
2602
2603 li = list_alloc();
2604 if (li == NULL)
2605 return;
2606 ret = dict_add_list(retdict, "items", li);
2607 if (ret == OK && compl_first_match != NULL)
2608 {
2609 match = compl_first_match;
2610 do
2611 {
2612 if (!(match->cp_flags & CP_ORIGINAL_TEXT))
2613 {
2614 di = dict_alloc();
2615 if (di == NULL)
2616 return;
2617 ret = list_append_dict(li, di);
2618 if (ret != OK)
2619 return;
2620 dict_add_string(di, "word", match->cp_str);
2621 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
2622 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
2623 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
2624 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002625 if (match->cp_user_data.v_type == VAR_UNKNOWN)
2626 // Add an empty string for backwards compatibility
2627 dict_add_string(di, "user_data", (char_u *)"");
2628 else
2629 dict_add_tv(di, "user_data", &match->cp_user_data);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002630 }
2631 match = match->cp_next;
2632 }
2633 while (match != NULL && match != compl_first_match);
2634 }
2635 }
2636
2637 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
Bram Moolenaarf9d51352020-10-26 19:22:42 +01002638 {
2639 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
2640 ins_compl_update_sequence_numbers();
2641 ret = dict_add_number(retdict, "selected", compl_curr_match != NULL
2642 ? compl_curr_match->cp_number - 1 : -1);
2643 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002644
2645 // TODO
2646 // if (ret == OK && (what_flag & CI_WHAT_INSERTED))
2647}
2648
2649/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002650 * "complete_info()" function
2651 */
2652 void
2653f_complete_info(typval_T *argvars, typval_T *rettv)
2654{
2655 list_T *what_list = NULL;
2656
2657 if (rettv_dict_alloc(rettv) != OK)
2658 return;
2659
2660 if (argvars[0].v_type != VAR_UNKNOWN)
2661 {
2662 if (argvars[0].v_type != VAR_LIST)
2663 {
2664 emsg(_(e_listreq));
2665 return;
2666 }
2667 what_list = argvars[0].vval.v_list;
2668 }
2669 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002670}
2671#endif
2672
2673/*
2674 * Get the next expansion(s), using "compl_pattern".
2675 * The search starts at position "ini" in curbuf and in the direction
2676 * compl_direction.
2677 * When "compl_started" is FALSE start at that position, otherwise continue
2678 * where we stopped searching before.
2679 * This may return before finding all the matches.
2680 * Return the total number of matches or -1 if still unknown -- Acevedo
2681 */
2682 static int
2683ins_compl_get_exp(pos_T *ini)
2684{
2685 static pos_T first_match_pos;
2686 static pos_T last_match_pos;
2687 static char_u *e_cpt = (char_u *)""; // curr. entry in 'complete'
2688 static int found_all = FALSE; // Found all matches of a
2689 // certain type.
2690 static buf_T *ins_buf = NULL; // buffer being scanned
2691
2692 pos_T *pos;
2693 char_u **matches;
2694 int save_p_scs;
2695 int save_p_ws;
2696 int save_p_ic;
2697 int i;
2698 int num_matches;
2699 int len;
2700 int found_new_match;
2701 int type = ctrl_x_mode;
2702 char_u *ptr;
2703 char_u *dict = NULL;
2704 int dict_f = 0;
2705 int set_match_pos;
2706
2707 if (!compl_started)
2708 {
2709 FOR_ALL_BUFFERS(ins_buf)
2710 ins_buf->b_scanned = 0;
2711 found_all = FALSE;
2712 ins_buf = curbuf;
2713 e_cpt = (compl_cont_status & CONT_LOCAL)
2714 ? (char_u *)"." : curbuf->b_p_cpt;
2715 last_match_pos = first_match_pos = *ini;
2716 }
2717 else if (ins_buf != curbuf && !buf_valid(ins_buf))
2718 ins_buf = curbuf; // In case the buffer was wiped out.
2719
2720 compl_old_match = compl_curr_match; // remember the last current match
2721 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
2722
2723 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
2724 for (;;)
2725 {
2726 found_new_match = FAIL;
2727 set_match_pos = FALSE;
2728
2729 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
2730 // or if found_all says this entry is done. For ^X^L only use the
2731 // entries from 'complete' that look in loaded buffers.
2732 if ((ctrl_x_mode == CTRL_X_NORMAL
2733 || ctrl_x_mode_line_or_eval())
2734 && (!compl_started || found_all))
2735 {
2736 found_all = FALSE;
2737 while (*e_cpt == ',' || *e_cpt == ' ')
2738 e_cpt++;
2739 if (*e_cpt == '.' && !curbuf->b_scanned)
2740 {
2741 ins_buf = curbuf;
2742 first_match_pos = *ini;
2743 // Move the cursor back one character so that ^N can match the
2744 // word immediately after the cursor.
2745 if (ctrl_x_mode == CTRL_X_NORMAL && dec(&first_match_pos) < 0)
2746 {
2747 // Move the cursor to after the last character in the
2748 // buffer, so that word at start of buffer is found
2749 // correctly.
2750 first_match_pos.lnum = ins_buf->b_ml.ml_line_count;
2751 first_match_pos.col =
2752 (colnr_T)STRLEN(ml_get(first_match_pos.lnum));
2753 }
2754 last_match_pos = first_match_pos;
2755 type = 0;
2756
2757 // Remember the first match so that the loop stops when we
2758 // wrap and come back there a second time.
2759 set_match_pos = TRUE;
2760 }
2761 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
2762 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
2763 {
2764 // Scan a buffer, but not the current one.
2765 if (ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
2766 {
2767 compl_started = TRUE;
2768 first_match_pos.col = last_match_pos.col = 0;
2769 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
2770 last_match_pos.lnum = 0;
2771 type = 0;
2772 }
2773 else // unloaded buffer, scan like dictionary
2774 {
2775 found_all = TRUE;
2776 if (ins_buf->b_fname == NULL)
2777 continue;
2778 type = CTRL_X_DICTIONARY;
2779 dict = ins_buf->b_fname;
2780 dict_f = DICT_EXACT;
2781 }
Bram Moolenaarcc233582020-12-12 13:32:07 +01002782 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002783 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
2784 ins_buf->b_fname == NULL
2785 ? buf_spname(ins_buf)
2786 : ins_buf->b_sfname == NULL
2787 ? ins_buf->b_fname
2788 : ins_buf->b_sfname);
2789 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2790 }
2791 else if (*e_cpt == NUL)
2792 break;
2793 else
2794 {
2795 if (ctrl_x_mode_line_or_eval())
2796 type = -1;
2797 else if (*e_cpt == 'k' || *e_cpt == 's')
2798 {
2799 if (*e_cpt == 'k')
2800 type = CTRL_X_DICTIONARY;
2801 else
2802 type = CTRL_X_THESAURUS;
2803 if (*++e_cpt != ',' && *e_cpt != NUL)
2804 {
2805 dict = e_cpt;
2806 dict_f = DICT_FIRST;
2807 }
2808 }
2809#ifdef FEAT_FIND_ID
2810 else if (*e_cpt == 'i')
2811 type = CTRL_X_PATH_PATTERNS;
2812 else if (*e_cpt == 'd')
2813 type = CTRL_X_PATH_DEFINES;
2814#endif
2815 else if (*e_cpt == ']' || *e_cpt == 't')
2816 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01002817 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002818 type = CTRL_X_TAGS;
2819 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
2820 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2821 }
2822 else
2823 type = -1;
2824
2825 // in any case e_cpt is advanced to the next entry
2826 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
2827
2828 found_all = TRUE;
2829 if (type == -1)
2830 continue;
2831 }
2832 }
2833
2834 // If complete() was called then compl_pattern has been reset. The
2835 // following won't work then, bail out.
2836 if (compl_pattern == NULL)
2837 break;
2838
2839 switch (type)
2840 {
2841 case -1:
2842 break;
2843#ifdef FEAT_FIND_ID
2844 case CTRL_X_PATH_PATTERNS:
2845 case CTRL_X_PATH_DEFINES:
2846 find_pattern_in_path(compl_pattern, compl_direction,
2847 (int)STRLEN(compl_pattern), FALSE, FALSE,
2848 (type == CTRL_X_PATH_DEFINES
2849 && !(compl_cont_status & CONT_SOL))
2850 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
2851 (linenr_T)1, (linenr_T)MAXLNUM);
2852 break;
2853#endif
2854
2855 case CTRL_X_DICTIONARY:
2856 case CTRL_X_THESAURUS:
2857 ins_compl_dictionaries(
2858 dict != NULL ? dict
2859 : (type == CTRL_X_THESAURUS
2860 ? (*curbuf->b_p_tsr == NUL
2861 ? p_tsr
2862 : curbuf->b_p_tsr)
2863 : (*curbuf->b_p_dict == NUL
2864 ? p_dict
2865 : curbuf->b_p_dict)),
2866 compl_pattern,
2867 dict != NULL ? dict_f
2868 : 0, type == CTRL_X_THESAURUS);
2869 dict = NULL;
2870 break;
2871
2872 case CTRL_X_TAGS:
2873 // set p_ic according to p_ic, p_scs and pat for find_tags().
2874 save_p_ic = p_ic;
2875 p_ic = ignorecase(compl_pattern);
2876
2877 // Find up to TAG_MANY matches. Avoids that an enormous number
2878 // of matches is found when compl_pattern is empty
Bram Moolenaar45e18cb2019-04-28 18:05:35 +02002879 g_tag_at_cursor = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002880 if (find_tags(compl_pattern, &num_matches, &matches,
2881 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
2882 | (ctrl_x_mode != CTRL_X_NORMAL ? TAG_VERBOSE : 0),
2883 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002884 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar45e18cb2019-04-28 18:05:35 +02002885 g_tag_at_cursor = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002886 p_ic = save_p_ic;
2887 break;
2888
2889 case CTRL_X_FILES:
2890 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
2891 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
2892 {
2893
2894 // May change home directory back to "~".
2895 tilde_replace(compl_pattern, num_matches, matches);
Bram Moolenaarac3150d2019-07-28 16:36:39 +02002896#ifdef BACKSLASH_IN_FILENAME
2897 if (curbuf->b_p_csl[0] != NUL)
2898 {
2899 int i;
2900
2901 for (i = 0; i < num_matches; ++i)
2902 {
2903 char_u *ptr = matches[i];
2904
2905 while (*ptr != NUL)
2906 {
2907 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
2908 *ptr = '/';
2909 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
2910 *ptr = '\\';
2911 ptr += (*mb_ptr2len)(ptr);
2912 }
2913 }
2914 }
2915#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002916 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
2917 }
2918 break;
2919
2920 case CTRL_X_CMDLINE:
2921 if (expand_cmdline(&compl_xp, compl_pattern,
2922 (int)STRLEN(compl_pattern),
2923 &num_matches, &matches) == EXPAND_OK)
2924 ins_compl_add_matches(num_matches, matches, FALSE);
2925 break;
2926
2927#ifdef FEAT_COMPL_FUNC
2928 case CTRL_X_FUNCTION:
2929 case CTRL_X_OMNI:
2930 expand_by_function(type, compl_pattern);
2931 break;
2932#endif
2933
2934 case CTRL_X_SPELL:
2935#ifdef FEAT_SPELL
2936 num_matches = expand_spelling(first_match_pos.lnum,
2937 compl_pattern, &matches);
2938 if (num_matches > 0)
2939 ins_compl_add_matches(num_matches, matches, p_ic);
2940#endif
2941 break;
2942
2943 default: // normal ^P/^N and ^X^L
2944 // If 'infercase' is set, don't use 'smartcase' here
2945 save_p_scs = p_scs;
2946 if (ins_buf->b_p_inf)
2947 p_scs = FALSE;
2948
2949 // Buffers other than curbuf are scanned from the beginning or the
2950 // end but never from the middle, thus setting nowrapscan in this
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002951 // buffer is a good idea, on the other hand, we always set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002952 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
2953 save_p_ws = p_ws;
2954 if (ins_buf != curbuf)
2955 p_ws = FALSE;
2956 else if (*e_cpt == '.')
2957 p_ws = TRUE;
2958 for (;;)
2959 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02002960 int cont_s_ipos = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002961
2962 ++msg_silent; // Don't want messages for wrapscan.
2963
2964 // ctrl_x_mode_line_or_eval() || word-wise search that
2965 // has added a word that was at the beginning of the line
2966 if (ctrl_x_mode_line_or_eval()
2967 || (compl_cont_status & CONT_SOL))
2968 found_new_match = search_for_exact_line(ins_buf, pos,
2969 compl_direction, compl_pattern);
2970 else
2971 found_new_match = searchit(NULL, ins_buf, pos, NULL,
2972 compl_direction,
2973 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
Bram Moolenaar92ea26b2019-10-18 20:53:34 +02002974 RE_LAST, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002975 --msg_silent;
2976 if (!compl_started || set_match_pos)
2977 {
2978 // set "compl_started" even on fail
2979 compl_started = TRUE;
2980 first_match_pos = *pos;
2981 last_match_pos = *pos;
2982 set_match_pos = FALSE;
2983 }
2984 else if (first_match_pos.lnum == last_match_pos.lnum
2985 && first_match_pos.col == last_match_pos.col)
2986 found_new_match = FAIL;
2987 if (found_new_match == FAIL)
2988 {
2989 if (ins_buf == curbuf)
2990 found_all = TRUE;
2991 break;
2992 }
2993
2994 // when ADDING, the text before the cursor matches, skip it
2995 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
2996 && ini->lnum == pos->lnum
2997 && ini->col == pos->col)
2998 continue;
2999 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
3000 if (ctrl_x_mode_line_or_eval())
3001 {
3002 if (compl_cont_status & CONT_ADDING)
3003 {
3004 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
3005 continue;
3006 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3007 if (!p_paste)
3008 ptr = skipwhite(ptr);
3009 }
3010 len = (int)STRLEN(ptr);
3011 }
3012 else
3013 {
3014 char_u *tmp_ptr = ptr;
3015
3016 if (compl_cont_status & CONT_ADDING)
3017 {
3018 tmp_ptr += compl_length;
3019 // Skip if already inside a word.
3020 if (vim_iswordp(tmp_ptr))
3021 continue;
3022 // Find start of next word.
3023 tmp_ptr = find_word_start(tmp_ptr);
3024 }
3025 // Find end of this word.
3026 tmp_ptr = find_word_end(tmp_ptr);
3027 len = (int)(tmp_ptr - ptr);
3028
3029 if ((compl_cont_status & CONT_ADDING)
3030 && len == compl_length)
3031 {
3032 if (pos->lnum < ins_buf->b_ml.ml_line_count)
3033 {
3034 // Try next line, if any. the new word will be
3035 // "join" as if the normal command "J" was used.
3036 // IOSIZE is always greater than
3037 // compl_length, so the next STRNCPY always
3038 // works -- Acevedo
3039 STRNCPY(IObuff, ptr, len);
3040 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3041 tmp_ptr = ptr = skipwhite(ptr);
3042 // Find start of next word.
3043 tmp_ptr = find_word_start(tmp_ptr);
3044 // Find end of next word.
3045 tmp_ptr = find_word_end(tmp_ptr);
3046 if (tmp_ptr > ptr)
3047 {
3048 if (*ptr != ')' && IObuff[len - 1] != TAB)
3049 {
3050 if (IObuff[len - 1] != ' ')
3051 IObuff[len++] = ' ';
3052 // IObuf =~ "\k.* ", thus len >= 2
3053 if (p_js
3054 && (IObuff[len - 2] == '.'
3055 || (vim_strchr(p_cpo, CPO_JOINSP)
3056 == NULL
3057 && (IObuff[len - 2] == '?'
3058 || IObuff[len - 2] == '!'))))
3059 IObuff[len++] = ' ';
3060 }
3061 // copy as much as possible of the new word
3062 if (tmp_ptr - ptr >= IOSIZE - len)
3063 tmp_ptr = ptr + IOSIZE - len - 1;
3064 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3065 len += (int)(tmp_ptr - ptr);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003066 cont_s_ipos = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003067 }
3068 IObuff[len] = NUL;
3069 ptr = IObuff;
3070 }
3071 if (len == compl_length)
3072 continue;
3073 }
3074 }
3075 if (ins_compl_add_infercase(ptr, len, p_ic,
3076 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003077 0, cont_s_ipos) != NOTDONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003078 {
3079 found_new_match = OK;
3080 break;
3081 }
3082 }
3083 p_scs = save_p_scs;
3084 p_ws = save_p_ws;
3085 }
3086
3087 // check if compl_curr_match has changed, (e.g. other type of
3088 // expansion added something)
3089 if (type != 0 && compl_curr_match != compl_old_match)
3090 found_new_match = OK;
3091
3092 // break the loop for specialized modes (use 'complete' just for the
3093 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3094 // match
3095 if ((ctrl_x_mode != CTRL_X_NORMAL
3096 && !ctrl_x_mode_line_or_eval()) || found_new_match != FAIL)
3097 {
3098 if (got_int)
3099 break;
3100 // Fill the popup menu as soon as possible.
3101 if (type != -1)
3102 ins_compl_check_keys(0, FALSE);
3103
3104 if ((ctrl_x_mode != CTRL_X_NORMAL
3105 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3106 break;
3107 compl_started = TRUE;
3108 }
3109 else
3110 {
3111 // Mark a buffer scanned when it has been scanned completely
3112 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3113 ins_buf->b_scanned = TRUE;
3114
3115 compl_started = FALSE;
3116 }
3117 }
3118 compl_started = TRUE;
3119
3120 if ((ctrl_x_mode == CTRL_X_NORMAL || ctrl_x_mode_line_or_eval())
3121 && *e_cpt == NUL) // Got to end of 'complete'
3122 found_new_match = FAIL;
3123
3124 i = -1; // total of matches, unknown
3125 if (found_new_match == FAIL || (ctrl_x_mode != CTRL_X_NORMAL
3126 && !ctrl_x_mode_line_or_eval()))
3127 i = ins_compl_make_cyclic();
3128
3129 if (compl_old_match != NULL)
3130 {
3131 // If several matches were added (FORWARD) or the search failed and has
3132 // just been made cyclic then we have to move compl_curr_match to the
3133 // next or previous entry (if any) -- Acevedo
3134 compl_curr_match = compl_direction == FORWARD ? compl_old_match->cp_next
3135 : compl_old_match->cp_prev;
3136 if (compl_curr_match == NULL)
3137 compl_curr_match = compl_old_match;
3138 }
3139 return i;
3140}
3141
3142/*
3143 * Delete the old text being completed.
3144 */
3145 void
3146ins_compl_delete(void)
3147{
3148 int col;
3149
3150 // In insert mode: Delete the typed part.
3151 // In replace mode: Put the old characters back, if any.
3152 col = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
3153 if ((int)curwin->w_cursor.col > col)
3154 {
3155 if (stop_arrow() == FAIL)
3156 return;
3157 backspace_until_column(col);
3158 }
3159
3160 // TODO: is this sufficient for redrawing? Redrawing everything causes
3161 // flicker, thus we can't do that.
3162 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003163#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003164 // clear v:completed_item
3165 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003166#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003167}
3168
3169/*
3170 * Insert the new text being completed.
3171 * "in_compl_func" is TRUE when called from complete_check().
3172 */
3173 void
3174ins_compl_insert(int in_compl_func)
3175{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003176 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003177 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003178 compl_used_match = FALSE;
3179 else
3180 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003181#ifdef FEAT_EVAL
3182 {
3183 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
3184
3185 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
3186 }
3187#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003188 if (!in_compl_func)
3189 compl_curr_match = compl_shown_match;
3190}
3191
3192/*
3193 * Fill in the next completion in the current direction.
3194 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
3195 * get more completions. If it is FALSE, then we just do nothing when there
3196 * are no more completions in a given direction. The latter case is used when
3197 * we are still in the middle of finding completions, to allow browsing
3198 * through the ones found so far.
3199 * Return the total number of matches, or -1 if still unknown -- webb.
3200 *
3201 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
3202 * compl_shown_match here.
3203 *
3204 * Note that this function may be called recursively once only. First with
3205 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
3206 * calls this function with "allow_get_expansion" FALSE.
3207 */
3208 static int
3209ins_compl_next(
3210 int allow_get_expansion,
3211 int count, // repeat completion this many times; should
3212 // be at least 1
3213 int insert_match, // Insert the newly selected match
3214 int in_compl_func) // called from complete_check()
3215{
3216 int num_matches = -1;
3217 int todo = count;
3218 compl_T *found_compl = NULL;
3219 int found_end = FALSE;
3220 int advance;
3221 int started = compl_started;
3222
3223 // When user complete function return -1 for findstart which is next
3224 // time of 'always', compl_shown_match become NULL.
3225 if (compl_shown_match == NULL)
3226 return -1;
3227
3228 if (compl_leader != NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003229 && (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003230 {
3231 // Set "compl_shown_match" to the actually shown match, it may differ
3232 // when "compl_leader" is used to omit some of the matches.
3233 while (!ins_compl_equal(compl_shown_match,
3234 compl_leader, (int)STRLEN(compl_leader))
3235 && compl_shown_match->cp_next != NULL
3236 && compl_shown_match->cp_next != compl_first_match)
3237 compl_shown_match = compl_shown_match->cp_next;
3238
3239 // If we didn't find it searching forward, and compl_shows_dir is
3240 // backward, find the last match.
3241 if (compl_shows_dir == BACKWARD
3242 && !ins_compl_equal(compl_shown_match,
3243 compl_leader, (int)STRLEN(compl_leader))
3244 && (compl_shown_match->cp_next == NULL
3245 || compl_shown_match->cp_next == compl_first_match))
3246 {
3247 while (!ins_compl_equal(compl_shown_match,
3248 compl_leader, (int)STRLEN(compl_leader))
3249 && compl_shown_match->cp_prev != NULL
3250 && compl_shown_match->cp_prev != compl_first_match)
3251 compl_shown_match = compl_shown_match->cp_prev;
3252 }
3253 }
3254
3255 if (allow_get_expansion && insert_match
3256 && (!(compl_get_longest || compl_restarting) || compl_used_match))
3257 // Delete old text to be replaced
3258 ins_compl_delete();
3259
3260 // When finding the longest common text we stick at the original text,
3261 // don't let CTRL-N or CTRL-P move to the first match.
3262 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
3263
3264 // When restarting the search don't insert the first match either.
3265 if (compl_restarting)
3266 {
3267 advance = FALSE;
3268 compl_restarting = FALSE;
3269 }
3270
3271 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
3272 // around.
3273 while (--todo >= 0)
3274 {
3275 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
3276 {
3277 compl_shown_match = compl_shown_match->cp_next;
3278 found_end = (compl_first_match != NULL
3279 && (compl_shown_match->cp_next == compl_first_match
3280 || compl_shown_match == compl_first_match));
3281 }
3282 else if (compl_shows_dir == BACKWARD
3283 && compl_shown_match->cp_prev != NULL)
3284 {
3285 found_end = (compl_shown_match == compl_first_match);
3286 compl_shown_match = compl_shown_match->cp_prev;
3287 found_end |= (compl_shown_match == compl_first_match);
3288 }
3289 else
3290 {
3291 if (!allow_get_expansion)
3292 {
3293 if (advance)
3294 {
3295 if (compl_shows_dir == BACKWARD)
3296 compl_pending -= todo + 1;
3297 else
3298 compl_pending += todo + 1;
3299 }
3300 return -1;
3301 }
3302
3303 if (!compl_no_select && advance)
3304 {
3305 if (compl_shows_dir == BACKWARD)
3306 --compl_pending;
3307 else
3308 ++compl_pending;
3309 }
3310
3311 // Find matches.
3312 num_matches = ins_compl_get_exp(&compl_startpos);
3313
3314 // handle any pending completions
3315 while (compl_pending != 0 && compl_direction == compl_shows_dir
3316 && advance)
3317 {
3318 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
3319 {
3320 compl_shown_match = compl_shown_match->cp_next;
3321 --compl_pending;
3322 }
3323 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
3324 {
3325 compl_shown_match = compl_shown_match->cp_prev;
3326 ++compl_pending;
3327 }
3328 else
3329 break;
3330 }
3331 found_end = FALSE;
3332 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003333 if ((compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003334 && compl_leader != NULL
3335 && !ins_compl_equal(compl_shown_match,
3336 compl_leader, (int)STRLEN(compl_leader)))
3337 ++todo;
3338 else
3339 // Remember a matching item.
3340 found_compl = compl_shown_match;
3341
3342 // Stop at the end of the list when we found a usable match.
3343 if (found_end)
3344 {
3345 if (found_compl != NULL)
3346 {
3347 compl_shown_match = found_compl;
3348 break;
3349 }
3350 todo = 1; // use first usable match after wrapping around
3351 }
3352 }
3353
3354 // Insert the text of the new completion, or the compl_leader.
3355 if (compl_no_insert && !started)
3356 {
3357 ins_bytes(compl_orig_text + ins_compl_len());
3358 compl_used_match = FALSE;
3359 }
3360 else if (insert_match)
3361 {
3362 if (!compl_get_longest || compl_used_match)
3363 ins_compl_insert(in_compl_func);
3364 else
3365 ins_bytes(compl_leader + ins_compl_len());
3366 }
3367 else
3368 compl_used_match = FALSE;
3369
3370 if (!allow_get_expansion)
3371 {
3372 // may undisplay the popup menu first
3373 ins_compl_upd_pum();
3374
3375 if (pum_enough_matches())
3376 // Will display the popup menu, don't redraw yet to avoid flicker.
3377 pum_call_update_screen();
3378 else
3379 // Not showing the popup menu yet, redraw to show the user what was
3380 // inserted.
3381 update_screen(0);
3382
3383 // display the updated popup menu
3384 ins_compl_show_pum();
3385#ifdef FEAT_GUI
3386 if (gui.in_use)
3387 {
3388 // Show the cursor after the match, not after the redrawn text.
3389 setcursor();
3390 out_flush_cursor(FALSE, FALSE);
3391 }
3392#endif
3393
3394 // Delete old text to be replaced, since we're still searching and
3395 // don't want to match ourselves!
3396 ins_compl_delete();
3397 }
3398
3399 // Enter will select a match when the match wasn't inserted and the popup
3400 // menu is visible.
3401 if (compl_no_insert && !started)
3402 compl_enter_selects = TRUE;
3403 else
3404 compl_enter_selects = !insert_match && compl_match_array != NULL;
3405
3406 // Show the file name for the match (if any)
3407 // Truncate the file name to avoid a wait for return.
3408 if (compl_shown_match->cp_fname != NULL)
3409 {
3410 char *lead = _("match in file");
3411 int space = sc_col - vim_strsize((char_u *)lead) - 2;
3412 char_u *s;
3413 char_u *e;
3414
3415 if (space > 0)
3416 {
3417 // We need the tail that fits. With double-byte encoding going
3418 // back from the end is very slow, thus go from the start and keep
3419 // the text that fits in "space" between "s" and "e".
3420 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
3421 {
3422 space -= ptr2cells(e);
3423 while (space < 0)
3424 {
3425 space += ptr2cells(s);
3426 MB_PTR_ADV(s);
3427 }
3428 }
Bram Moolenaarcc233582020-12-12 13:32:07 +01003429 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003430 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
3431 s > compl_shown_match->cp_fname ? "<" : "", s);
3432 msg((char *)IObuff);
Bram Moolenaarcc233582020-12-12 13:32:07 +01003433 msg_hist_off = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003434 redraw_cmdline = FALSE; // don't overwrite!
3435 }
3436 }
3437
3438 return num_matches;
3439}
3440
3441/*
3442 * Call this while finding completions, to check whether the user has hit a key
3443 * that should change the currently displayed completion, or exit completion
3444 * mode. Also, when compl_pending is not zero, show a completion as soon as
3445 * possible. -- webb
3446 * "frequency" specifies out of how many calls we actually check.
3447 * "in_compl_func" is TRUE when called from complete_check(), don't set
3448 * compl_curr_match.
3449 */
3450 void
3451ins_compl_check_keys(int frequency, int in_compl_func)
3452{
3453 static int count = 0;
3454 int c;
3455
3456 // Don't check when reading keys from a script, :normal or feedkeys().
3457 // That would break the test scripts. But do check for keys when called
3458 // from complete_check().
3459 if (!in_compl_func && (using_script() || ex_normal_busy))
3460 return;
3461
3462 // Only do this at regular intervals
3463 if (++count < frequency)
3464 return;
3465 count = 0;
3466
3467 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
3468 // can't do its work correctly.
3469 c = vpeekc_any();
3470 if (c != NUL)
3471 {
3472 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
3473 {
3474 c = safe_vgetc(); // Eat the character
3475 compl_shows_dir = ins_compl_key2dir(c);
3476 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
3477 c != K_UP && c != K_DOWN, in_compl_func);
3478 }
3479 else
3480 {
3481 // Need to get the character to have KeyTyped set. We'll put it
3482 // back with vungetc() below. But skip K_IGNORE.
3483 c = safe_vgetc();
3484 if (c != K_IGNORE)
3485 {
3486 // Don't interrupt completion when the character wasn't typed,
3487 // e.g., when doing @q to replay keys.
3488 if (c != Ctrl_R && KeyTyped)
3489 compl_interrupted = TRUE;
3490
3491 vungetc(c);
3492 }
3493 }
3494 }
3495 if (compl_pending != 0 && !got_int && !compl_no_insert)
3496 {
3497 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
3498
3499 compl_pending = 0;
3500 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
3501 }
3502}
3503
3504/*
3505 * Decide the direction of Insert mode complete from the key typed.
3506 * Returns BACKWARD or FORWARD.
3507 */
3508 static int
3509ins_compl_key2dir(int c)
3510{
3511 if (c == Ctrl_P || c == Ctrl_L
3512 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
3513 return BACKWARD;
3514 return FORWARD;
3515}
3516
3517/*
3518 * Return TRUE for keys that are used for completion only when the popup menu
3519 * is visible.
3520 */
3521 static int
3522ins_compl_pum_key(int c)
3523{
3524 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
3525 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
3526 || c == K_UP || c == K_DOWN);
3527}
3528
3529/*
3530 * Decide the number of completions to move forward.
3531 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
3532 */
3533 static int
3534ins_compl_key2count(int c)
3535{
3536 int h;
3537
3538 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
3539 {
3540 h = pum_get_height();
3541 if (h > 3)
3542 h -= 2; // keep some context
3543 return h;
3544 }
3545 return 1;
3546}
3547
3548/*
3549 * Return TRUE if completion with "c" should insert the match, FALSE if only
3550 * to change the currently selected completion.
3551 */
3552 static int
3553ins_compl_use_match(int c)
3554{
3555 switch (c)
3556 {
3557 case K_UP:
3558 case K_DOWN:
3559 case K_PAGEDOWN:
3560 case K_KPAGEDOWN:
3561 case K_S_DOWN:
3562 case K_PAGEUP:
3563 case K_KPAGEUP:
3564 case K_S_UP:
3565 return FALSE;
3566 }
3567 return TRUE;
3568}
3569
3570/*
3571 * Do Insert mode completion.
3572 * Called when character "c" was typed, which has a meaning for completion.
3573 * Returns OK if completion was done, FAIL if something failed (out of mem).
3574 */
3575 int
3576ins_complete(int c, int enable_pum)
3577{
3578 char_u *line;
3579 int startcol = 0; // column where searched text starts
3580 colnr_T curs_col; // cursor column
3581 int n;
3582 int save_w_wrow;
3583 int save_w_leftcol;
3584 int insert_match;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003585#ifdef FEAT_COMPL_FUNC
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003586 int save_did_ai = did_ai;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003587#endif
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003588 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003589
3590 compl_direction = ins_compl_key2dir(c);
3591 insert_match = ins_compl_use_match(c);
3592
3593 if (!compl_started)
3594 {
3595 // First time we hit ^N or ^P (in a row, I mean)
3596
3597 did_ai = FALSE;
3598#ifdef FEAT_SMARTINDENT
3599 did_si = FALSE;
3600 can_si = FALSE;
3601 can_si_back = FALSE;
3602#endif
3603 if (stop_arrow() == FAIL)
3604 return FAIL;
3605
3606 line = ml_get(curwin->w_cursor.lnum);
3607 curs_col = curwin->w_cursor.col;
3608 compl_pending = 0;
3609
3610 // If this same ctrl_x_mode has been interrupted use the text from
3611 // "compl_startpos" to the cursor as a pattern to add a new word
3612 // instead of expand the one before the cursor, in word-wise if
3613 // "compl_startpos" is not in the same line as the cursor then fix it
3614 // (the line has been split because it was longer than 'tw'). if SOL
3615 // is set then skip the previous pattern, a word at the beginning of
3616 // the line has been inserted, we'll look for that -- Acevedo.
3617 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
3618 && compl_cont_mode == ctrl_x_mode)
3619 {
3620 // it is a continued search
3621 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
3622 if (ctrl_x_mode == CTRL_X_NORMAL
3623 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
3624 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3625 {
3626 if (compl_startpos.lnum != curwin->w_cursor.lnum)
3627 {
3628 // line (probably) wrapped, set compl_startpos to the
3629 // first non_blank in the line, if it is not a wordchar
3630 // include it to get a better pattern, but then we don't
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01003631 // want the "\\<" prefix, check it below
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003632 compl_col = (colnr_T)getwhitecols(line);
3633 compl_startpos.col = compl_col;
3634 compl_startpos.lnum = curwin->w_cursor.lnum;
3635 compl_cont_status &= ~CONT_SOL; // clear SOL if present
3636 }
3637 else
3638 {
3639 // S_IPOS was set when we inserted a word that was at the
3640 // beginning of the line, which means that we'll go to SOL
3641 // mode but first we need to redefine compl_startpos
3642 if (compl_cont_status & CONT_S_IPOS)
3643 {
3644 compl_cont_status |= CONT_SOL;
3645 compl_startpos.col = (colnr_T)(skipwhite(
3646 line + compl_length
3647 + compl_startpos.col) - line);
3648 }
3649 compl_col = compl_startpos.col;
3650 }
3651 compl_length = curwin->w_cursor.col - (int)compl_col;
3652 // IObuff is used to add a "word from the next line" would we
3653 // have enough space? just being paranoid
3654#define MIN_SPACE 75
3655 if (compl_length > (IOSIZE - MIN_SPACE))
3656 {
3657 compl_cont_status &= ~CONT_SOL;
3658 compl_length = (IOSIZE - MIN_SPACE);
3659 compl_col = curwin->w_cursor.col - compl_length;
3660 }
3661 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
3662 if (compl_length < 1)
3663 compl_cont_status &= CONT_LOCAL;
3664 }
3665 else if (ctrl_x_mode_line_or_eval())
3666 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
3667 else
3668 compl_cont_status = 0;
3669 }
3670 else
3671 compl_cont_status &= CONT_LOCAL;
3672
3673 if (!(compl_cont_status & CONT_ADDING)) // normal expansion
3674 {
3675 compl_cont_mode = ctrl_x_mode;
3676 if (ctrl_x_mode != CTRL_X_NORMAL)
3677 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
3678 compl_cont_status = 0;
3679 compl_cont_status |= CONT_N_ADDS;
3680 compl_startpos = curwin->w_cursor;
3681 startcol = (int)curs_col;
3682 compl_col = 0;
3683 }
3684
3685 // Work out completion pattern and original text -- webb
3686 if (ctrl_x_mode == CTRL_X_NORMAL || (ctrl_x_mode & CTRL_X_WANT_IDENT))
3687 {
3688 if ((compl_cont_status & CONT_SOL)
3689 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3690 {
3691 if (!(compl_cont_status & CONT_ADDING))
3692 {
3693 while (--startcol >= 0 && vim_isIDc(line[startcol]))
3694 ;
3695 compl_col += ++startcol;
3696 compl_length = curs_col - startcol;
3697 }
3698 if (p_ic)
3699 compl_pattern = str_foldcase(line + compl_col,
3700 compl_length, NULL, 0);
3701 else
3702 compl_pattern = vim_strnsave(line + compl_col,
3703 compl_length);
3704 if (compl_pattern == NULL)
3705 return FAIL;
3706 }
3707 else if (compl_cont_status & CONT_ADDING)
3708 {
3709 char_u *prefix = (char_u *)"\\<";
3710
3711 // we need up to 2 extra chars for the prefix
3712 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3713 compl_length) + 2);
3714 if (compl_pattern == NULL)
3715 return FAIL;
3716 if (!vim_iswordp(line + compl_col)
3717 || (compl_col > 0
3718 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
3719 prefix = (char_u *)"";
3720 STRCPY((char *)compl_pattern, prefix);
3721 (void)quote_meta(compl_pattern + STRLEN(prefix),
3722 line + compl_col, compl_length);
3723 }
3724 else if (--startcol < 0
3725 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
3726 {
3727 // Match any word of at least two chars
3728 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
3729 if (compl_pattern == NULL)
3730 return FAIL;
3731 compl_col += curs_col;
3732 compl_length = 0;
3733 }
3734 else
3735 {
3736 // Search the point of change class of multibyte character
3737 // or not a word single byte character backward.
3738 if (has_mbyte)
3739 {
3740 int base_class;
3741 int head_off;
3742
3743 startcol -= (*mb_head_off)(line, line + startcol);
3744 base_class = mb_get_class(line + startcol);
3745 while (--startcol >= 0)
3746 {
3747 head_off = (*mb_head_off)(line, line + startcol);
3748 if (base_class != mb_get_class(line + startcol
3749 - head_off))
3750 break;
3751 startcol -= head_off;
3752 }
3753 }
3754 else
3755 while (--startcol >= 0 && vim_iswordc(line[startcol]))
3756 ;
3757 compl_col += ++startcol;
3758 compl_length = (int)curs_col - startcol;
3759 if (compl_length == 1)
3760 {
3761 // Only match word with at least two chars -- webb
3762 // there's no need to call quote_meta,
3763 // alloc(7) is enough -- Acevedo
3764 compl_pattern = alloc(7);
3765 if (compl_pattern == NULL)
3766 return FAIL;
3767 STRCPY((char *)compl_pattern, "\\<");
3768 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
3769 STRCAT((char *)compl_pattern, "\\k");
3770 }
3771 else
3772 {
3773 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3774 compl_length) + 2);
3775 if (compl_pattern == NULL)
3776 return FAIL;
3777 STRCPY((char *)compl_pattern, "\\<");
3778 (void)quote_meta(compl_pattern + 2, line + compl_col,
3779 compl_length);
3780 }
3781 }
3782 }
3783 else if (ctrl_x_mode_line_or_eval())
3784 {
3785 compl_col = (colnr_T)getwhitecols(line);
3786 compl_length = (int)curs_col - (int)compl_col;
3787 if (compl_length < 0) // cursor in indent: empty pattern
3788 compl_length = 0;
3789 if (p_ic)
3790 compl_pattern = str_foldcase(line + compl_col, compl_length,
3791 NULL, 0);
3792 else
3793 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3794 if (compl_pattern == NULL)
3795 return FAIL;
3796 }
3797 else if (ctrl_x_mode == CTRL_X_FILES)
3798 {
3799 // Go back to just before the first filename character.
3800 if (startcol > 0)
3801 {
3802 char_u *p = line + startcol;
3803
3804 MB_PTR_BACK(line, p);
3805 while (p > line && vim_isfilec(PTR2CHAR(p)))
3806 MB_PTR_BACK(line, p);
3807 if (p == line && vim_isfilec(PTR2CHAR(p)))
3808 startcol = 0;
3809 else
3810 startcol = (int)(p - line) + 1;
3811 }
3812
3813 compl_col += startcol;
3814 compl_length = (int)curs_col - startcol;
3815 compl_pattern = addstar(line + compl_col, compl_length,
3816 EXPAND_FILES);
3817 if (compl_pattern == NULL)
3818 return FAIL;
3819 }
3820 else if (ctrl_x_mode == CTRL_X_CMDLINE)
3821 {
3822 compl_pattern = vim_strnsave(line, curs_col);
3823 if (compl_pattern == NULL)
3824 return FAIL;
3825 set_cmd_context(&compl_xp, compl_pattern,
3826 (int)STRLEN(compl_pattern), curs_col, FALSE);
3827 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
3828 || compl_xp.xp_context == EXPAND_NOTHING)
3829 // No completion possible, use an empty pattern to get a
3830 // "pattern not found" message.
3831 compl_col = curs_col;
3832 else
3833 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
3834 compl_length = curs_col - compl_col;
3835 }
3836 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
3837 {
3838#ifdef FEAT_COMPL_FUNC
3839 // Call user defined function 'completefunc' with "a:findstart"
3840 // set to 1 to obtain the length of text to use for completion.
3841 typval_T args[3];
3842 int col;
3843 char_u *funcname;
3844 pos_T pos;
3845 win_T *curwin_save;
3846 buf_T *curbuf_save;
3847 int save_State = State;
3848
3849 // Call 'completefunc' or 'omnifunc' and get pattern length as a
3850 // string
3851 funcname = ctrl_x_mode == CTRL_X_FUNCTION
3852 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3853 if (*funcname == NUL)
3854 {
3855 semsg(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
3856 ? "completefunc" : "omnifunc");
3857 // restore did_ai, so that adding comment leader works
3858 did_ai = save_did_ai;
3859 return FAIL;
3860 }
3861
3862 args[0].v_type = VAR_NUMBER;
3863 args[0].vval.v_number = 1;
3864 args[1].v_type = VAR_STRING;
3865 args[1].vval.v_string = (char_u *)"";
3866 args[2].v_type = VAR_UNKNOWN;
3867 pos = curwin->w_cursor;
3868 curwin_save = curwin;
3869 curbuf_save = curbuf;
3870 col = call_func_retnr(funcname, 2, args);
3871
3872 State = save_State;
3873 if (curwin_save != curwin || curbuf_save != curbuf)
3874 {
3875 emsg(_(e_complwin));
3876 return FAIL;
3877 }
3878 curwin->w_cursor = pos; // restore the cursor position
3879 validate_cursor();
3880 if (!EQUAL_POS(curwin->w_cursor, pos))
3881 {
3882 emsg(_(e_compldel));
3883 return FAIL;
3884 }
3885
3886 // Return value -2 means the user complete function wants to
3887 // cancel the complete without an error.
3888 // Return value -3 does the same as -2 and leaves CTRL-X mode.
3889 if (col == -2)
3890 return FAIL;
3891 if (col == -3)
3892 {
3893 ctrl_x_mode = CTRL_X_NORMAL;
3894 edit_submode = NULL;
3895 if (!shortmess(SHM_COMPLETIONMENU))
3896 msg_clr_cmdline();
3897 return FAIL;
3898 }
3899
3900 // Reset extended parameters of completion, when start new
3901 // completion.
3902 compl_opt_refresh_always = FALSE;
3903 compl_opt_suppress_empty = FALSE;
3904
3905 if (col < 0)
3906 col = curs_col;
3907 compl_col = col;
3908 if (compl_col > curs_col)
3909 compl_col = curs_col;
3910
3911 // Setup variables for completion. Need to obtain "line" again,
3912 // it may have become invalid.
3913 line = ml_get(curwin->w_cursor.lnum);
3914 compl_length = curs_col - compl_col;
3915 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3916 if (compl_pattern == NULL)
3917#endif
3918 return FAIL;
3919 }
3920 else if (ctrl_x_mode == CTRL_X_SPELL)
3921 {
3922#ifdef FEAT_SPELL
3923 if (spell_bad_len > 0)
3924 compl_col = curs_col - spell_bad_len;
3925 else
3926 compl_col = spell_word_start(startcol);
3927 if (compl_col >= (colnr_T)startcol)
3928 {
3929 compl_length = 0;
3930 compl_col = curs_col;
3931 }
3932 else
3933 {
3934 spell_expand_check_cap(compl_col);
3935 compl_length = (int)curs_col - compl_col;
3936 }
3937 // Need to obtain "line" again, it may have become invalid.
3938 line = ml_get(curwin->w_cursor.lnum);
3939 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3940 if (compl_pattern == NULL)
3941#endif
3942 return FAIL;
3943 }
3944 else
3945 {
3946 internal_error("ins_complete()");
3947 return FAIL;
3948 }
3949
3950 if (compl_cont_status & CONT_ADDING)
3951 {
3952 edit_submode_pre = (char_u *)_(" Adding");
3953 if (ctrl_x_mode_line_or_eval())
3954 {
3955 // Insert a new line, keep indentation but ignore 'comments'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003956 char_u *old = curbuf->b_p_com;
3957
3958 curbuf->b_p_com = (char_u *)"";
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003959 compl_startpos.lnum = curwin->w_cursor.lnum;
3960 compl_startpos.col = compl_col;
3961 ins_eol('\r');
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003962 curbuf->b_p_com = old;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003963 compl_length = 0;
3964 compl_col = curwin->w_cursor.col;
3965 }
3966 }
3967 else
3968 {
3969 edit_submode_pre = NULL;
3970 compl_startpos.col = compl_col;
3971 }
3972
3973 if (compl_cont_status & CONT_LOCAL)
3974 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
3975 else
3976 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
3977
3978 // If any of the original typed text has been changed we need to fix
3979 // the redo buffer.
3980 ins_compl_fixRedoBufForLeader(NULL);
3981
3982 // Always add completion for the original text.
3983 vim_free(compl_orig_text);
3984 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003985 if (p_ic)
3986 flags |= CP_ICASE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003987 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar08928322020-01-04 14:32:48 +01003988 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003989 {
3990 VIM_CLEAR(compl_pattern);
3991 VIM_CLEAR(compl_orig_text);
3992 return FAIL;
3993 }
3994
3995 // showmode might reset the internal line pointers, so it must
3996 // be called before line = ml_get(), or when this address is no
3997 // longer needed. -- Acevedo.
3998 edit_submode_extra = (char_u *)_("-- Searching...");
3999 edit_submode_highl = HLF_COUNT;
4000 showmode();
4001 edit_submode_extra = NULL;
4002 out_flush();
4003 }
4004 else if (insert_match && stop_arrow() == FAIL)
4005 return FAIL;
4006
4007 compl_shown_match = compl_curr_match;
4008 compl_shows_dir = compl_direction;
4009
4010 // Find next match (and following matches).
4011 save_w_wrow = curwin->w_wrow;
4012 save_w_leftcol = curwin->w_leftcol;
4013 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
4014
4015 // may undisplay the popup menu
4016 ins_compl_upd_pum();
4017
4018 if (n > 1) // all matches have been found
4019 compl_matches = n;
4020 compl_curr_match = compl_shown_match;
4021 compl_direction = compl_shows_dir;
4022
4023 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
4024 // mode.
4025 if (got_int && !global_busy)
4026 {
4027 (void)vgetc();
4028 got_int = FALSE;
4029 }
4030
4031 // we found no match if the list has only the "compl_orig_text"-entry
4032 if (compl_first_match == compl_first_match->cp_next)
4033 {
4034 edit_submode_extra = (compl_cont_status & CONT_ADDING)
4035 && compl_length > 1
4036 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
4037 edit_submode_highl = HLF_E;
4038 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
4039 // because we couldn't expand anything at first place, but if we used
4040 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
4041 // (such as M in M'exico) if not tried already. -- Acevedo
4042 if ( compl_length > 1
4043 || (compl_cont_status & CONT_ADDING)
4044 || (ctrl_x_mode != CTRL_X_NORMAL
4045 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
4046 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
4047 compl_cont_status &= ~CONT_N_ADDS;
4048 }
4049
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004050 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004051 compl_cont_status |= CONT_S_IPOS;
4052 else
4053 compl_cont_status &= ~CONT_S_IPOS;
4054
4055 if (edit_submode_extra == NULL)
4056 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004057 if (compl_curr_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004058 {
4059 edit_submode_extra = (char_u *)_("Back at original");
4060 edit_submode_highl = HLF_W;
4061 }
4062 else if (compl_cont_status & CONT_S_IPOS)
4063 {
4064 edit_submode_extra = (char_u *)_("Word from other line");
4065 edit_submode_highl = HLF_COUNT;
4066 }
4067 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
4068 {
4069 edit_submode_extra = (char_u *)_("The only match");
4070 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01004071 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004072 }
4073 else
4074 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01004075#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004076 // Update completion sequence number when needed.
4077 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01004078 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01004079#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004080 // The match should always have a sequence number now, this is
4081 // just a safety check.
4082 if (compl_curr_match->cp_number != -1)
4083 {
4084 // Space for 10 text chars. + 2x10-digit no.s = 31.
4085 // Translations may need more than twice that.
4086 static char_u match_ref[81];
4087
4088 if (compl_matches > 0)
4089 vim_snprintf((char *)match_ref, sizeof(match_ref),
4090 _("match %d of %d"),
4091 compl_curr_match->cp_number, compl_matches);
4092 else
4093 vim_snprintf((char *)match_ref, sizeof(match_ref),
4094 _("match %d"),
4095 compl_curr_match->cp_number);
4096 edit_submode_extra = match_ref;
4097 edit_submode_highl = HLF_R;
4098 if (dollar_vcol >= 0)
4099 curs_columns(FALSE);
4100 }
4101 }
4102 }
4103
4104 // Show a message about what (completion) mode we're in.
4105 if (!compl_opt_suppress_empty)
4106 {
4107 showmode();
4108 if (!shortmess(SHM_COMPLETIONMENU))
4109 {
4110 if (edit_submode_extra != NULL)
4111 {
4112 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01004113 {
4114 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004115 msg_attr((char *)edit_submode_extra,
4116 edit_submode_highl < HLF_COUNT
4117 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01004118 msg_hist_off = FALSE;
4119 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004120 }
4121 else
4122 msg_clr_cmdline(); // necessary for "noshowmode"
4123 }
4124 }
4125
4126 // Show the popup menu, unless we got interrupted.
4127 if (enable_pum && !compl_interrupted)
4128 show_pum(save_w_wrow, save_w_leftcol);
4129
4130 compl_was_interrupted = compl_interrupted;
4131 compl_interrupted = FALSE;
4132
4133 return OK;
4134}
4135
4136 static void
4137show_pum(int prev_w_wrow, int prev_w_leftcol)
4138{
4139 // RedrawingDisabled may be set when invoked through complete().
4140 int n = RedrawingDisabled;
4141
4142 RedrawingDisabled = 0;
4143
4144 // If the cursor moved or the display scrolled we need to remove the pum
4145 // first.
4146 setcursor();
4147 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
4148 ins_compl_del_pum();
4149
4150 ins_compl_show_pum();
4151 setcursor();
4152 RedrawingDisabled = n;
4153}
4154
4155/*
4156 * Looks in the first "len" chars. of "src" for search-metachars.
4157 * If dest is not NULL the chars. are copied there quoting (with
4158 * a backslash) the metachars, and dest would be NUL terminated.
4159 * Returns the length (needed) of dest
4160 */
4161 static unsigned
4162quote_meta(char_u *dest, char_u *src, int len)
4163{
4164 unsigned m = (unsigned)len + 1; // one extra for the NUL
4165
4166 for ( ; --len >= 0; src++)
4167 {
4168 switch (*src)
4169 {
4170 case '.':
4171 case '*':
4172 case '[':
4173 if (ctrl_x_mode == CTRL_X_DICTIONARY
4174 || ctrl_x_mode == CTRL_X_THESAURUS)
4175 break;
4176 // FALLTHROUGH
4177 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01004178 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004179 break;
4180 // FALLTHROUGH
4181 case '\\':
4182 if (ctrl_x_mode == CTRL_X_DICTIONARY
4183 || ctrl_x_mode == CTRL_X_THESAURUS)
4184 break;
4185 // FALLTHROUGH
4186 case '^': // currently it's not needed.
4187 case '$':
4188 m++;
4189 if (dest != NULL)
4190 *dest++ = '\\';
4191 break;
4192 }
4193 if (dest != NULL)
4194 *dest++ = *src;
4195 // Copy remaining bytes of a multibyte character.
4196 if (has_mbyte)
4197 {
4198 int i, mb_len;
4199
4200 mb_len = (*mb_ptr2len)(src) - 1;
4201 if (mb_len > 0 && len >= mb_len)
4202 for (i = 0; i < mb_len; ++i)
4203 {
4204 --len;
4205 ++src;
4206 if (dest != NULL)
4207 *dest++ = *src;
4208 }
4209 }
4210 }
4211 if (dest != NULL)
4212 *dest = NUL;
4213
4214 return m;
4215}
4216
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004217#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004218 void
4219free_insexpand_stuff(void)
4220{
4221 VIM_CLEAR(compl_orig_text);
4222}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004223#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004224
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004225#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004226/*
4227 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
4228 * spelled word, if there is one.
4229 */
4230 static void
4231spell_back_to_badword(void)
4232{
4233 pos_T tpos = curwin->w_cursor;
4234
4235 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
4236 if (curwin->w_cursor.col != tpos.col)
4237 start_arrow(&tpos);
4238}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004239#endif