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