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