blob: 1cada4fd10240cf7b343c2d9a6465ca31ca51ac1 [file] [log] [blame]
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * insexpand.c: functions for Insert mode completion
12 */
13
14#include "vim.h"
15
Bram Moolenaar7591bb32019-03-30 13:53:47 +010016/*
17 * Definitions used for CTRL-X submode.
18 * Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] and
19 * ctrl_x_mode_names[] below.
20 */
21# define CTRL_X_WANT_IDENT 0x100
22
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010023# define CTRL_X_NORMAL 0 // CTRL-N CTRL-P completion, default
Bram Moolenaar7591bb32019-03-30 13:53:47 +010024# define CTRL_X_NOT_DEFINED_YET 1
25# define CTRL_X_SCROLL 2
26# define CTRL_X_WHOLE_LINE 3
27# define CTRL_X_FILES 4
28# define CTRL_X_TAGS (5 + CTRL_X_WANT_IDENT)
29# define CTRL_X_PATH_PATTERNS (6 + CTRL_X_WANT_IDENT)
30# define CTRL_X_PATH_DEFINES (7 + CTRL_X_WANT_IDENT)
31# define CTRL_X_FINISHED 8
32# define CTRL_X_DICTIONARY (9 + CTRL_X_WANT_IDENT)
33# define CTRL_X_THESAURUS (10 + CTRL_X_WANT_IDENT)
34# define CTRL_X_CMDLINE 11
Bram Moolenaar9810cfb2019-12-11 21:23:00 +010035# define CTRL_X_FUNCTION 12
Bram Moolenaar7591bb32019-03-30 13:53:47 +010036# define CTRL_X_OMNI 13
37# define CTRL_X_SPELL 14
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +010038# define CTRL_X_LOCAL_MSG 15 // only used in "ctrl_x_msgs"
39# define CTRL_X_EVAL 16 // for builtin function complete()
Bram Moolenaar7591bb32019-03-30 13:53:47 +010040
41# define CTRL_X_MSG(i) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT]
42
43// Message for CTRL-X mode, index is ctrl_x_mode.
44static char *ctrl_x_msgs[] =
45{
46 N_(" Keyword completion (^N^P)"), // CTRL_X_NORMAL, ^P/^N compl.
47 N_(" ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)"),
48 NULL, // CTRL_X_SCROLL: depends on state
49 N_(" Whole line completion (^L^N^P)"),
50 N_(" File name completion (^F^N^P)"),
51 N_(" Tag completion (^]^N^P)"),
52 N_(" Path pattern completion (^N^P)"),
53 N_(" Definition completion (^D^N^P)"),
54 NULL, // CTRL_X_FINISHED
55 N_(" Dictionary completion (^K^N^P)"),
56 N_(" Thesaurus completion (^T^N^P)"),
57 N_(" Command-line completion (^V^N^P)"),
58 N_(" User defined completion (^U^N^P)"),
59 N_(" Omni completion (^O^N^P)"),
60 N_(" Spelling suggestion (s^N^P)"),
61 N_(" Keyword Local completion (^N^P)"),
62 NULL, // CTRL_X_EVAL doesn't use msg.
63};
64
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020065#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +010066static char *ctrl_x_mode_names[] = {
67 "keyword",
68 "ctrl_x",
69 "unknown", // CTRL_X_SCROLL
70 "whole_line",
71 "files",
72 "tags",
73 "path_patterns",
74 "path_defines",
75 "unknown", // CTRL_X_FINISHED
76 "dictionary",
77 "thesaurus",
78 "cmdline",
79 "function",
80 "omni",
81 "spell",
82 NULL, // CTRL_X_LOCAL_MSG only used in "ctrl_x_msgs"
83 "eval"
84};
Bram Moolenaar9cb698d2019-08-21 15:30:45 +020085#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +010086
87/*
88 * Array indexes used for cp_text[].
89 */
90#define CPT_ABBR 0 // "abbr"
91#define CPT_MENU 1 // "menu"
92#define CPT_KIND 2 // "kind"
93#define CPT_INFO 3 // "info"
94#define CPT_USER_DATA 4 // "user data"
95#define CPT_COUNT 5 // Number of entries
96
97/*
98 * Structure used to store one match for insert completion.
99 */
100typedef struct compl_S compl_T;
101struct compl_S
102{
103 compl_T *cp_next;
104 compl_T *cp_prev;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200105 char_u *cp_str; // matched text
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200106 char_u *(cp_text[CPT_COUNT]); // text for the menu
107 char_u *cp_fname; // file containing the match, allocated when
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200108 // cp_flags has CP_FREE_FNAME
109 int cp_flags; // CP_ values
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200110 int cp_number; // sequence number
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100111};
112
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200113// values for cp_flags
114# define CP_ORIGINAL_TEXT 1 // the original text when the expansion begun
115# define CP_FREE_FNAME 2 // cp_fname is allocated
116# define CP_CONT_S_IPOS 4 // use CONT_S_IPOS for compl_cont_status
117# define CP_EQUAL 8 // ins_compl_equal() always returns TRUE
118# define CP_ICASE 16 // ins_compl_equal() ignores case
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100119
120static char e_hitend[] = N_("Hit end of paragraph");
121# ifdef FEAT_COMPL_FUNC
122static char e_complwin[] = N_("E839: Completion function changed window");
123static char e_compldel[] = N_("E840: Completion function deleted text");
124# endif
125
126/*
127 * All the current matches are stored in a list.
128 * "compl_first_match" points to the start of the list.
129 * "compl_curr_match" points to the currently selected entry.
130 * "compl_shown_match" is different from compl_curr_match during
131 * ins_compl_get_exp().
132 */
133static compl_T *compl_first_match = NULL;
134static compl_T *compl_curr_match = NULL;
135static compl_T *compl_shown_match = NULL;
136static compl_T *compl_old_match = NULL;
137
138// After using a cursor key <Enter> selects a match in the popup menu,
139// otherwise it inserts a line break.
140static int compl_enter_selects = FALSE;
141
142// When "compl_leader" is not NULL only matches that start with this string
143// are used.
144static char_u *compl_leader = NULL;
145
146static int compl_get_longest = FALSE; // put longest common string
147 // in compl_leader
148
149static int compl_no_insert = FALSE; // FALSE: select & insert
150 // TRUE: noinsert
151static int compl_no_select = FALSE; // FALSE: select & insert
152 // TRUE: noselect
153
154// Selected one of the matches. When FALSE the match was edited or using the
155// longest common string.
156static int compl_used_match;
157
158// didn't finish finding completions.
159static int compl_was_interrupted = FALSE;
160
161// Set when character typed while looking for matches and it means we should
162// stop looking for matches.
163static int compl_interrupted = FALSE;
164
165static int compl_restarting = FALSE; // don't insert match
166
167// When the first completion is done "compl_started" is set. When it's
168// FALSE the word to be completed must be located.
169static int compl_started = FALSE;
170
171// Which Ctrl-X mode are we in?
172static int ctrl_x_mode = CTRL_X_NORMAL;
173
174static int compl_matches = 0;
175static char_u *compl_pattern = NULL;
176static int compl_direction = FORWARD;
177static int compl_shows_dir = FORWARD;
178static int compl_pending = 0; // > 1 for postponed CTRL-N
179static pos_T compl_startpos;
180static colnr_T compl_col = 0; // column where the text starts
181 // that is being completed
182static char_u *compl_orig_text = NULL; // text as it was before
183 // completion started
184static int compl_cont_mode = 0;
185static expand_T compl_xp;
186
187static int compl_opt_refresh_always = FALSE;
188static int compl_opt_suppress_empty = FALSE;
189
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200190static 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 +0100191static void ins_compl_longest_match(compl_T *match);
192static void ins_compl_del_pum(void);
193static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
194static char_u *find_line_end(char_u *ptr);
195static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100196static int ins_compl_need_restart(void);
197static void ins_compl_new_leader(void);
198static int ins_compl_len(void);
199static void ins_compl_restart(void);
200static void ins_compl_set_original_text(char_u *str);
201static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
202# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
203static void ins_compl_add_list(list_T *list);
204static void ins_compl_add_dict(dict_T *dict);
205# endif
206static 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
Bram Moolenaareda1da02019-11-17 17:06:33 +0100307 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100308 }
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
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100854
855// "compl_match_array" points the currently displayed list of entries in the
856// popup menu. It is NULL when there is no popup menu.
857static pumitem_T *compl_match_array = NULL;
858static int compl_match_arraysize;
859
860/*
861 * Update the screen and when there is any scrolling remove the popup menu.
862 */
863 static void
864ins_compl_upd_pum(void)
865{
866 int h;
867
868 if (compl_match_array != NULL)
869 {
870 h = curwin->w_cline_height;
871 // Update the screen later, before drawing the popup menu over it.
872 pum_call_update_screen();
873 if (h != curwin->w_cline_height)
874 ins_compl_del_pum();
875 }
876}
877
878/*
879 * Remove any popup menu.
880 */
881 static void
882ins_compl_del_pum(void)
883{
884 if (compl_match_array != NULL)
885 {
886 pum_undisplay();
887 VIM_CLEAR(compl_match_array);
888 }
889}
890
891/*
892 * Return TRUE if the popup menu should be displayed.
893 */
894 int
895pum_wanted(void)
896{
897 // 'completeopt' must contain "menu" or "menuone"
898 if (vim_strchr(p_cot, 'm') == NULL)
899 return FALSE;
900
901 // The display looks bad on a B&W display.
902 if (t_colors < 8
903#ifdef FEAT_GUI
904 && !gui.in_use
905#endif
906 )
907 return FALSE;
908 return TRUE;
909}
910
911/*
912 * Return TRUE if there are two or more matches to be shown in the popup menu.
913 * One if 'completopt' contains "menuone".
914 */
915 static int
916pum_enough_matches(void)
917{
918 compl_T *compl;
919 int i;
920
921 // Don't display the popup menu if there are no matches or there is only
922 // one (ignoring the original text).
923 compl = compl_first_match;
924 i = 0;
925 do
926 {
927 if (compl == NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200928 || ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0 && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100929 break;
930 compl = compl->cp_next;
931 } while (compl != compl_first_match);
932
933 if (strstr((char *)p_cot, "menuone") != NULL)
934 return (i >= 1);
935 return (i >= 2);
936}
937
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200938#ifdef FEAT_EVAL
939/*
940 * Allocate Dict for the completed item.
941 * { word, abbr, menu, kind, info }
942 */
943 static dict_T *
944ins_compl_dict_alloc(compl_T *match)
945{
946 dict_T *dict = dict_alloc_lock(VAR_FIXED);
947
948 if (dict != NULL)
949 {
950 dict_add_string(dict, "word", match->cp_str);
951 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
952 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
953 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
954 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
955 dict_add_string(dict, "user_data", match->cp_text[CPT_USER_DATA]);
956 }
957 return dict;
958}
959
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200960 static void
961trigger_complete_changed_event(int cur)
962{
963 dict_T *v_event;
964 dict_T *item;
965 static int recursive = FALSE;
966
967 if (recursive)
968 return;
969
970 v_event = get_vim_var_dict(VV_EVENT);
971 if (cur < 0)
972 item = dict_alloc();
973 else
974 item = ins_compl_dict_alloc(compl_curr_match);
975 if (item == NULL)
976 return;
977 dict_add_dict(v_event, "completed_item", item);
978 pum_set_event_info(v_event);
979 dict_set_items_ro(v_event);
980
981 recursive = TRUE;
982 textlock++;
983 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
984 textlock--;
985 recursive = FALSE;
986
987 dict_free_contents(v_event);
988 hash_init(&v_event->dv_hashtab);
989}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200990#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200991
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100992/*
993 * Show the popup menu for the list of matches.
994 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
995 */
996 void
997ins_compl_show_pum(void)
998{
999 compl_T *compl;
1000 compl_T *shown_compl = NULL;
1001 int did_find_shown_match = FALSE;
1002 int shown_match_ok = FALSE;
1003 int i;
1004 int cur = -1;
1005 colnr_T col;
1006 int lead_len = 0;
1007
1008 if (!pum_wanted() || !pum_enough_matches())
1009 return;
1010
1011#if defined(FEAT_EVAL)
1012 // Dirty hard-coded hack: remove any matchparen highlighting.
1013 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|3match none|endif");
1014#endif
1015
1016 // Update the screen later, before drawing the popup menu over it.
1017 pum_call_update_screen();
1018
1019 if (compl_match_array == NULL)
1020 {
1021 // Need to build the popup menu list.
1022 compl_match_arraysize = 0;
1023 compl = compl_first_match;
1024 if (compl_leader != NULL)
1025 lead_len = (int)STRLEN(compl_leader);
1026 do
1027 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001028 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001029 && (compl_leader == NULL
1030 || ins_compl_equal(compl, compl_leader, lead_len)))
1031 ++compl_match_arraysize;
1032 compl = compl->cp_next;
1033 } while (compl != NULL && compl != compl_first_match);
1034 if (compl_match_arraysize == 0)
1035 return;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001036 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001037 if (compl_match_array != NULL)
1038 {
1039 // If the current match is the original text don't find the first
1040 // match after it, don't highlight anything.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001041 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001042 shown_match_ok = TRUE;
1043
1044 i = 0;
1045 compl = compl_first_match;
1046 do
1047 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001048 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001049 && (compl_leader == NULL
1050 || ins_compl_equal(compl, compl_leader, lead_len)))
1051 {
1052 if (!shown_match_ok)
1053 {
1054 if (compl == compl_shown_match || did_find_shown_match)
1055 {
1056 // This item is the shown match or this is the
1057 // first displayed item after the shown match.
1058 compl_shown_match = compl;
1059 did_find_shown_match = TRUE;
1060 shown_match_ok = TRUE;
1061 }
1062 else
1063 // Remember this displayed match for when the
1064 // shown match is just below it.
1065 shown_compl = compl;
1066 cur = i;
1067 }
1068
1069 if (compl->cp_text[CPT_ABBR] != NULL)
1070 compl_match_array[i].pum_text =
1071 compl->cp_text[CPT_ABBR];
1072 else
1073 compl_match_array[i].pum_text = compl->cp_str;
1074 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1075 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1076 if (compl->cp_text[CPT_MENU] != NULL)
1077 compl_match_array[i++].pum_extra =
1078 compl->cp_text[CPT_MENU];
1079 else
1080 compl_match_array[i++].pum_extra = compl->cp_fname;
1081 }
1082
1083 if (compl == compl_shown_match)
1084 {
1085 did_find_shown_match = TRUE;
1086
1087 // When the original text is the shown match don't set
1088 // compl_shown_match.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001089 if (compl->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001090 shown_match_ok = TRUE;
1091
1092 if (!shown_match_ok && shown_compl != NULL)
1093 {
1094 // The shown match isn't displayed, set it to the
1095 // previously displayed match.
1096 compl_shown_match = shown_compl;
1097 shown_match_ok = TRUE;
1098 }
1099 }
1100 compl = compl->cp_next;
1101 } while (compl != NULL && compl != compl_first_match);
1102
1103 if (!shown_match_ok) // no displayed match at all
1104 cur = -1;
1105 }
1106 }
1107 else
1108 {
1109 // popup menu already exists, only need to find the current item.
1110 for (i = 0; i < compl_match_arraysize; ++i)
1111 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1112 || compl_match_array[i].pum_text
1113 == compl_shown_match->cp_text[CPT_ABBR])
1114 {
1115 cur = i;
1116 break;
1117 }
1118 }
1119
1120 if (compl_match_array != NULL)
1121 {
1122 // In Replace mode when a $ is displayed at the end of the line only
1123 // part of the screen would be updated. We do need to redraw here.
1124 dollar_vcol = -1;
1125
1126 // Compute the screen column of the start of the completed text.
1127 // Use the cursor to get all wrapping and other settings right.
1128 col = curwin->w_cursor.col;
1129 curwin->w_cursor.col = compl_col;
1130 pum_display(compl_match_array, compl_match_arraysize, cur);
1131 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001132
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001133#ifdef FEAT_EVAL
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001134 if (has_completechanged())
1135 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001136#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001137 }
1138}
1139
1140#define DICT_FIRST (1) // use just first element in "dict"
1141#define DICT_EXACT (2) // "dict" is the exact name of a file
1142
1143/*
1144 * Add any identifiers that match the given pattern in the list of dictionary
1145 * files "dict_start" to the list of completions.
1146 */
1147 static void
1148ins_compl_dictionaries(
1149 char_u *dict_start,
1150 char_u *pat,
1151 int flags, // DICT_FIRST and/or DICT_EXACT
1152 int thesaurus) // Thesaurus completion
1153{
1154 char_u *dict = dict_start;
1155 char_u *ptr;
1156 char_u *buf;
1157 regmatch_T regmatch;
1158 char_u **files;
1159 int count;
1160 int save_p_scs;
1161 int dir = compl_direction;
1162
1163 if (*dict == NUL)
1164 {
1165#ifdef FEAT_SPELL
1166 // When 'dictionary' is empty and spell checking is enabled use
1167 // "spell".
1168 if (!thesaurus && curwin->w_p_spell)
1169 dict = (char_u *)"spell";
1170 else
1171#endif
1172 return;
1173 }
1174
1175 buf = alloc(LSIZE);
1176 if (buf == NULL)
1177 return;
1178 regmatch.regprog = NULL; // so that we can goto theend
1179
1180 // If 'infercase' is set, don't use 'smartcase' here
1181 save_p_scs = p_scs;
1182 if (curbuf->b_p_inf)
1183 p_scs = FALSE;
1184
1185 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1186 // to only match at the start of a line. Otherwise just match the
1187 // pattern. Also need to double backslashes.
1188 if (ctrl_x_mode_line_or_eval())
1189 {
1190 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1191 size_t len;
1192
1193 if (pat_esc == NULL)
1194 goto theend;
1195 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001196 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001197 if (ptr == NULL)
1198 {
1199 vim_free(pat_esc);
1200 goto theend;
1201 }
1202 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1203 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1204 vim_free(pat_esc);
1205 vim_free(ptr);
1206 }
1207 else
1208 {
1209 regmatch.regprog = vim_regcomp(pat, p_magic ? RE_MAGIC : 0);
1210 if (regmatch.regprog == NULL)
1211 goto theend;
1212 }
1213
1214 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1215 regmatch.rm_ic = ignorecase(pat);
1216 while (*dict != NUL && !got_int && !compl_interrupted)
1217 {
1218 // copy one dictionary file name into buf
1219 if (flags == DICT_EXACT)
1220 {
1221 count = 1;
1222 files = &dict;
1223 }
1224 else
1225 {
1226 // Expand wildcards in the dictionary name, but do not allow
1227 // backticks (for security, the 'dict' option may have been set in
1228 // a modeline).
1229 copy_option_part(&dict, buf, LSIZE, ",");
1230# ifdef FEAT_SPELL
1231 if (!thesaurus && STRCMP(buf, "spell") == 0)
1232 count = -1;
1233 else
1234# endif
1235 if (vim_strchr(buf, '`') != NULL
1236 || expand_wildcards(1, &buf, &count, &files,
1237 EW_FILE|EW_SILENT) != OK)
1238 count = 0;
1239 }
1240
1241# ifdef FEAT_SPELL
1242 if (count == -1)
1243 {
1244 // Complete from active spelling. Skip "\<" in the pattern, we
1245 // don't use it as a RE.
1246 if (pat[0] == '\\' && pat[1] == '<')
1247 ptr = pat + 2;
1248 else
1249 ptr = pat;
1250 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1251 }
1252 else
1253# endif
1254 if (count > 0) // avoid warning for using "files" uninit
1255 {
1256 ins_compl_files(count, files, thesaurus, flags,
1257 &regmatch, buf, &dir);
1258 if (flags != DICT_EXACT)
1259 FreeWild(count, files);
1260 }
1261 if (flags != 0)
1262 break;
1263 }
1264
1265theend:
1266 p_scs = save_p_scs;
1267 vim_regfree(regmatch.regprog);
1268 vim_free(buf);
1269}
1270
1271 static void
1272ins_compl_files(
1273 int count,
1274 char_u **files,
1275 int thesaurus,
1276 int flags,
1277 regmatch_T *regmatch,
1278 char_u *buf,
1279 int *dir)
1280{
1281 char_u *ptr;
1282 int i;
1283 FILE *fp;
1284 int add_r;
1285
1286 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1287 {
1288 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
1289 if (flags != DICT_EXACT)
1290 {
1291 vim_snprintf((char *)IObuff, IOSIZE,
1292 _("Scanning dictionary: %s"), (char *)files[i]);
1293 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
1294 }
1295
1296 if (fp != NULL)
1297 {
1298 // Read dictionary file line by line.
1299 // Check each line for a match.
1300 while (!got_int && !compl_interrupted
1301 && !vim_fgets(buf, LSIZE, fp))
1302 {
1303 ptr = buf;
1304 while (vim_regexec(regmatch, buf, (colnr_T)(ptr - buf)))
1305 {
1306 ptr = regmatch->startp[0];
1307 if (ctrl_x_mode_line_or_eval())
1308 ptr = find_line_end(ptr);
1309 else
1310 ptr = find_word_end(ptr);
1311 add_r = ins_compl_add_infercase(regmatch->startp[0],
1312 (int)(ptr - regmatch->startp[0]),
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001313 p_ic, files[i], *dir, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001314 if (thesaurus)
1315 {
1316 char_u *wstart;
1317
1318 // Add the other matches on the line
1319 ptr = buf;
1320 while (!got_int)
1321 {
1322 // Find start of the next word. Skip white
1323 // space and punctuation.
1324 ptr = find_word_start(ptr);
1325 if (*ptr == NUL || *ptr == NL)
1326 break;
1327 wstart = ptr;
1328
1329 // Find end of the word.
1330 if (has_mbyte)
1331 // Japanese words may have characters in
1332 // different classes, only separate words
1333 // with single-byte non-word characters.
1334 while (*ptr != NUL)
1335 {
1336 int l = (*mb_ptr2len)(ptr);
1337
1338 if (l < 2 && !vim_iswordc(*ptr))
1339 break;
1340 ptr += l;
1341 }
1342 else
1343 ptr = find_word_end(ptr);
1344
1345 // Add the word. Skip the regexp match.
1346 if (wstart != regmatch->startp[0])
1347 add_r = ins_compl_add_infercase(wstart,
1348 (int)(ptr - wstart),
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001349 p_ic, files[i], *dir, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001350 }
1351 }
1352 if (add_r == OK)
1353 // if dir was BACKWARD then honor it just once
1354 *dir = FORWARD;
1355 else if (add_r == FAIL)
1356 break;
1357 // avoid expensive call to vim_regexec() when at end
1358 // of line
1359 if (*ptr == '\n' || got_int)
1360 break;
1361 }
1362 line_breakcheck();
1363 ins_compl_check_keys(50, FALSE);
1364 }
1365 fclose(fp);
1366 }
1367 }
1368}
1369
1370/*
1371 * Find the start of the next word.
1372 * Returns a pointer to the first char of the word. Also stops at a NUL.
1373 */
1374 char_u *
1375find_word_start(char_u *ptr)
1376{
1377 if (has_mbyte)
1378 while (*ptr != NUL && *ptr != '\n' && mb_get_class(ptr) <= 1)
1379 ptr += (*mb_ptr2len)(ptr);
1380 else
1381 while (*ptr != NUL && *ptr != '\n' && !vim_iswordc(*ptr))
1382 ++ptr;
1383 return ptr;
1384}
1385
1386/*
1387 * Find the end of the word. Assumes it starts inside a word.
1388 * Returns a pointer to just after the word.
1389 */
1390 char_u *
1391find_word_end(char_u *ptr)
1392{
1393 int start_class;
1394
1395 if (has_mbyte)
1396 {
1397 start_class = mb_get_class(ptr);
1398 if (start_class > 1)
1399 while (*ptr != NUL)
1400 {
1401 ptr += (*mb_ptr2len)(ptr);
1402 if (mb_get_class(ptr) != start_class)
1403 break;
1404 }
1405 }
1406 else
1407 while (vim_iswordc(*ptr))
1408 ++ptr;
1409 return ptr;
1410}
1411
1412/*
1413 * Find the end of the line, omitting CR and NL at the end.
1414 * Returns a pointer to just after the line.
1415 */
1416 static char_u *
1417find_line_end(char_u *ptr)
1418{
1419 char_u *s;
1420
1421 s = ptr + STRLEN(ptr);
1422 while (s > ptr && (s[-1] == CAR || s[-1] == NL))
1423 --s;
1424 return s;
1425}
1426
1427/*
1428 * Free the list of completions
1429 */
1430 static void
1431ins_compl_free(void)
1432{
1433 compl_T *match;
1434 int i;
1435
1436 VIM_CLEAR(compl_pattern);
1437 VIM_CLEAR(compl_leader);
1438
1439 if (compl_first_match == NULL)
1440 return;
1441
1442 ins_compl_del_pum();
1443 pum_clear();
1444
1445 compl_curr_match = compl_first_match;
1446 do
1447 {
1448 match = compl_curr_match;
1449 compl_curr_match = compl_curr_match->cp_next;
1450 vim_free(match->cp_str);
1451 // several entries may use the same fname, free it just once.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001452 if (match->cp_flags & CP_FREE_FNAME)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001453 vim_free(match->cp_fname);
1454 for (i = 0; i < CPT_COUNT; ++i)
1455 vim_free(match->cp_text[i]);
1456 vim_free(match);
1457 } while (compl_curr_match != NULL && compl_curr_match != compl_first_match);
1458 compl_first_match = compl_curr_match = NULL;
1459 compl_shown_match = NULL;
1460 compl_old_match = NULL;
1461}
1462
1463 void
1464ins_compl_clear(void)
1465{
1466 compl_cont_status = 0;
1467 compl_started = FALSE;
1468 compl_matches = 0;
1469 VIM_CLEAR(compl_pattern);
1470 VIM_CLEAR(compl_leader);
1471 edit_submode_extra = NULL;
1472 VIM_CLEAR(compl_orig_text);
1473 compl_enter_selects = FALSE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001474#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001475 // clear v:completed_item
1476 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001477#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001478}
1479
1480/*
1481 * Return TRUE when Insert completion is active.
1482 */
1483 int
1484ins_compl_active(void)
1485{
1486 return compl_started;
1487}
1488
1489/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001490 * Selected one of the matches. When FALSE the match was edited or using the
1491 * longest common string.
1492 */
1493 int
1494ins_compl_used_match(void)
1495{
1496 return compl_used_match;
1497}
1498
1499/*
1500 * Initialize get longest common string.
1501 */
1502 void
1503ins_compl_init_get_longest(void)
1504{
1505 compl_get_longest = FALSE;
1506}
1507
1508/*
1509 * Returns TRUE when insert completion is interrupted.
1510 */
1511 int
1512ins_compl_interrupted(void)
1513{
1514 return compl_interrupted;
1515}
1516
1517/*
1518 * Returns TRUE if the <Enter> key selects a match in the completion popup
1519 * menu.
1520 */
1521 int
1522ins_compl_enter_selects(void)
1523{
1524 return compl_enter_selects;
1525}
1526
1527/*
1528 * Return the column where the text starts that is being completed
1529 */
1530 colnr_T
1531ins_compl_col(void)
1532{
1533 return compl_col;
1534}
1535
1536/*
1537 * Delete one character before the cursor and show the subset of the matches
1538 * that match the word that is now before the cursor.
1539 * Returns the character to be used, NUL if the work is done and another char
1540 * to be got from the user.
1541 */
1542 int
1543ins_compl_bs(void)
1544{
1545 char_u *line;
1546 char_u *p;
1547
1548 line = ml_get_curline();
1549 p = line + curwin->w_cursor.col;
1550 MB_PTR_BACK(line, p);
1551
1552 // Stop completion when the whole word was deleted. For Omni completion
1553 // allow the word to be deleted, we won't match everything.
1554 // Respect the 'backspace' option.
1555 if ((int)(p - line) - (int)compl_col < 0
1556 || ((int)(p - line) - (int)compl_col == 0
1557 && ctrl_x_mode != CTRL_X_OMNI) || ctrl_x_mode == CTRL_X_EVAL
1558 || (!can_bs(BS_START) && (int)(p - line) - (int)compl_col
1559 - compl_length < 0))
1560 return K_BS;
1561
1562 // Deleted more than what was used to find matches or didn't finish
1563 // finding all matches: need to look for matches all over again.
1564 if (curwin->w_cursor.col <= compl_col + compl_length
1565 || ins_compl_need_restart())
1566 ins_compl_restart();
1567
1568 vim_free(compl_leader);
1569 compl_leader = vim_strnsave(line + compl_col, (int)(p - line) - compl_col);
1570 if (compl_leader != NULL)
1571 {
1572 ins_compl_new_leader();
1573 if (compl_shown_match != NULL)
1574 // Make sure current match is not a hidden item.
1575 compl_curr_match = compl_shown_match;
1576 return NUL;
1577 }
1578 return K_BS;
1579}
1580
1581/*
1582 * Return TRUE when we need to find matches again, ins_compl_restart() is to
1583 * be called.
1584 */
1585 static int
1586ins_compl_need_restart(void)
1587{
1588 // Return TRUE if we didn't complete finding matches or when the
1589 // 'completefunc' returned "always" in the "refresh" dictionary item.
1590 return compl_was_interrupted
1591 || ((ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
1592 && compl_opt_refresh_always);
1593}
1594
1595/*
1596 * Called after changing "compl_leader".
1597 * Show the popup menu with a different set of matches.
1598 * May also search for matches again if the previous search was interrupted.
1599 */
1600 static void
1601ins_compl_new_leader(void)
1602{
1603 ins_compl_del_pum();
1604 ins_compl_delete();
1605 ins_bytes(compl_leader + ins_compl_len());
1606 compl_used_match = FALSE;
1607
1608 if (compl_started)
1609 ins_compl_set_original_text(compl_leader);
1610 else
1611 {
1612#ifdef FEAT_SPELL
1613 spell_bad_len = 0; // need to redetect bad word
1614#endif
Bram Moolenaar32aa1022019-11-02 22:54:41 +01001615 // Matches were cleared, need to search for them now. Before drawing
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001616 // the popup menu display the changed text before the cursor. Set
1617 // "compl_restarting" to avoid that the first match is inserted.
1618 pum_call_update_screen();
1619#ifdef FEAT_GUI
1620 if (gui.in_use)
1621 {
1622 // Show the cursor after the match, not after the redrawn text.
1623 setcursor();
1624 out_flush_cursor(FALSE, FALSE);
1625 }
1626#endif
1627 compl_restarting = TRUE;
1628 if (ins_complete(Ctrl_N, TRUE) == FAIL)
1629 compl_cont_status = 0;
1630 compl_restarting = FALSE;
1631 }
1632
1633 compl_enter_selects = !compl_used_match;
1634
1635 // Show the popup menu with a different set of matches.
1636 ins_compl_show_pum();
1637
1638 // Don't let Enter select the original text when there is no popup menu.
1639 if (compl_match_array == NULL)
1640 compl_enter_selects = FALSE;
1641}
1642
1643/*
1644 * Return the length of the completion, from the completion start column to
1645 * the cursor column. Making sure it never goes below zero.
1646 */
1647 static int
1648ins_compl_len(void)
1649{
1650 int off = (int)curwin->w_cursor.col - (int)compl_col;
1651
1652 if (off < 0)
1653 return 0;
1654 return off;
1655}
1656
1657/*
1658 * Append one character to the match leader. May reduce the number of
1659 * matches.
1660 */
1661 void
1662ins_compl_addleader(int c)
1663{
1664 int cc;
1665
1666 if (stop_arrow() == FAIL)
1667 return;
1668 if (has_mbyte && (cc = (*mb_char2len)(c)) > 1)
1669 {
1670 char_u buf[MB_MAXBYTES + 1];
1671
1672 (*mb_char2bytes)(c, buf);
1673 buf[cc] = NUL;
1674 ins_char_bytes(buf, cc);
1675 if (compl_opt_refresh_always)
1676 AppendToRedobuff(buf);
1677 }
1678 else
1679 {
1680 ins_char(c);
1681 if (compl_opt_refresh_always)
1682 AppendCharToRedobuff(c);
1683 }
1684
1685 // If we didn't complete finding matches we must search again.
1686 if (ins_compl_need_restart())
1687 ins_compl_restart();
1688
1689 // When 'always' is set, don't reset compl_leader. While completing,
1690 // cursor doesn't point original position, changing compl_leader would
1691 // break redo.
1692 if (!compl_opt_refresh_always)
1693 {
1694 vim_free(compl_leader);
1695 compl_leader = vim_strnsave(ml_get_curline() + compl_col,
1696 (int)(curwin->w_cursor.col - compl_col));
1697 if (compl_leader != NULL)
1698 ins_compl_new_leader();
1699 }
1700}
1701
1702/*
1703 * Setup for finding completions again without leaving CTRL-X mode. Used when
1704 * BS or a key was typed while still searching for matches.
1705 */
1706 static void
1707ins_compl_restart(void)
1708{
1709 ins_compl_free();
1710 compl_started = FALSE;
1711 compl_matches = 0;
1712 compl_cont_status = 0;
1713 compl_cont_mode = 0;
1714}
1715
1716/*
1717 * Set the first match, the original text.
1718 */
1719 static void
1720ins_compl_set_original_text(char_u *str)
1721{
1722 char_u *p;
1723
1724 // Replace the original text entry.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001725 // The CP_ORIGINAL_TEXT flag is either at the first item or might possibly be
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001726 // at the last item for backward completion
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001727 if (compl_first_match->cp_flags & CP_ORIGINAL_TEXT) // safety check
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001728 {
1729 p = vim_strsave(str);
1730 if (p != NULL)
1731 {
1732 vim_free(compl_first_match->cp_str);
1733 compl_first_match->cp_str = p;
1734 }
1735 }
1736 else if (compl_first_match->cp_prev != NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001737 && (compl_first_match->cp_prev->cp_flags & CP_ORIGINAL_TEXT))
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001738 {
1739 p = vim_strsave(str);
1740 if (p != NULL)
1741 {
1742 vim_free(compl_first_match->cp_prev->cp_str);
1743 compl_first_match->cp_prev->cp_str = p;
1744 }
1745 }
1746}
1747
1748/*
1749 * Append one character to the match leader. May reduce the number of
1750 * matches.
1751 */
1752 void
1753ins_compl_addfrommatch(void)
1754{
1755 char_u *p;
1756 int len = (int)curwin->w_cursor.col - (int)compl_col;
1757 int c;
1758 compl_T *cp;
1759
1760 p = compl_shown_match->cp_str;
1761 if ((int)STRLEN(p) <= len) // the match is too short
1762 {
1763 // When still at the original match use the first entry that matches
1764 // the leader.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001765 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001766 {
1767 p = NULL;
1768 for (cp = compl_shown_match->cp_next; cp != NULL
1769 && cp != compl_first_match; cp = cp->cp_next)
1770 {
1771 if (compl_leader == NULL
1772 || ins_compl_equal(cp, compl_leader,
1773 (int)STRLEN(compl_leader)))
1774 {
1775 p = cp->cp_str;
1776 break;
1777 }
1778 }
1779 if (p == NULL || (int)STRLEN(p) <= len)
1780 return;
1781 }
1782 else
1783 return;
1784 }
1785 p += len;
1786 c = PTR2CHAR(p);
1787 ins_compl_addleader(c);
1788}
1789
1790/*
1791 * Prepare for Insert mode completion, or stop it.
1792 * Called just after typing a character in Insert mode.
1793 * Returns TRUE when the character is not to be inserted;
1794 */
1795 int
1796ins_compl_prep(int c)
1797{
1798 char_u *ptr;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001799#ifdef FEAT_CINDENT
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001800 int want_cindent;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001801#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001802 int retval = FALSE;
1803
1804 // Forget any previous 'special' messages if this is actually
1805 // a ^X mode key - bar ^R, in which case we wait to see what it gives us.
1806 if (c != Ctrl_R && vim_is_ctrl_x_key(c))
1807 edit_submode_extra = NULL;
1808
1809 // Ignore end of Select mode mapping and mouse scroll buttons.
1810 if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP
1811 || c == K_MOUSELEFT || c == K_MOUSERIGHT)
1812 return retval;
1813
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01001814#ifdef FEAT_PROP_POPUP
Bram Moolenaarf0bc15c2019-08-18 19:23:45 +02001815 // Ignore mouse events in a popup window
1816 if (is_mouse_key(c))
1817 {
1818 // Ignore drag and release events, the position does not need to be in
1819 // the popup and it may have just closed.
1820 if (c == K_LEFTRELEASE
1821 || c == K_LEFTRELEASE_NM
1822 || c == K_MIDDLERELEASE
1823 || c == K_RIGHTRELEASE
1824 || c == K_X1RELEASE
1825 || c == K_X2RELEASE
1826 || c == K_LEFTDRAG
1827 || c == K_MIDDLEDRAG
1828 || c == K_RIGHTDRAG
1829 || c == K_X1DRAG
1830 || c == K_X2DRAG)
1831 return retval;
1832 if (popup_visible)
1833 {
1834 int row = mouse_row;
1835 int col = mouse_col;
1836 win_T *wp = mouse_find_win(&row, &col, FIND_POPUP);
1837
1838 if (wp != NULL && WIN_IS_POPUP(wp))
1839 return retval;
1840 }
1841 }
1842#endif
1843
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001844 // Set "compl_get_longest" when finding the first matches.
1845 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET
1846 || (ctrl_x_mode == CTRL_X_NORMAL && !compl_started))
1847 {
1848 compl_get_longest = (strstr((char *)p_cot, "longest") != NULL);
1849 compl_used_match = TRUE;
1850
1851 }
1852
1853 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET)
1854 {
1855 // We have just typed CTRL-X and aren't quite sure which CTRL-X mode
1856 // it will be yet. Now we decide.
1857 switch (c)
1858 {
1859 case Ctrl_E:
1860 case Ctrl_Y:
1861 ctrl_x_mode = CTRL_X_SCROLL;
1862 if (!(State & REPLACE_FLAG))
1863 edit_submode = (char_u *)_(" (insert) Scroll (^E/^Y)");
1864 else
1865 edit_submode = (char_u *)_(" (replace) Scroll (^E/^Y)");
1866 edit_submode_pre = NULL;
1867 showmode();
1868 break;
1869 case Ctrl_L:
1870 ctrl_x_mode = CTRL_X_WHOLE_LINE;
1871 break;
1872 case Ctrl_F:
1873 ctrl_x_mode = CTRL_X_FILES;
1874 break;
1875 case Ctrl_K:
1876 ctrl_x_mode = CTRL_X_DICTIONARY;
1877 break;
1878 case Ctrl_R:
1879 // Simply allow ^R to happen without affecting ^X mode
1880 break;
1881 case Ctrl_T:
1882 ctrl_x_mode = CTRL_X_THESAURUS;
1883 break;
1884#ifdef FEAT_COMPL_FUNC
1885 case Ctrl_U:
1886 ctrl_x_mode = CTRL_X_FUNCTION;
1887 break;
1888 case Ctrl_O:
1889 ctrl_x_mode = CTRL_X_OMNI;
1890 break;
1891#endif
1892 case 's':
1893 case Ctrl_S:
1894 ctrl_x_mode = CTRL_X_SPELL;
1895#ifdef FEAT_SPELL
1896 ++emsg_off; // Avoid getting the E756 error twice.
1897 spell_back_to_badword();
1898 --emsg_off;
1899#endif
1900 break;
1901 case Ctrl_RSB:
1902 ctrl_x_mode = CTRL_X_TAGS;
1903 break;
1904#ifdef FEAT_FIND_ID
1905 case Ctrl_I:
1906 case K_S_TAB:
1907 ctrl_x_mode = CTRL_X_PATH_PATTERNS;
1908 break;
1909 case Ctrl_D:
1910 ctrl_x_mode = CTRL_X_PATH_DEFINES;
1911 break;
1912#endif
1913 case Ctrl_V:
1914 case Ctrl_Q:
1915 ctrl_x_mode = CTRL_X_CMDLINE;
1916 break;
1917 case Ctrl_P:
1918 case Ctrl_N:
1919 // ^X^P means LOCAL expansion if nothing interrupted (eg we
1920 // just started ^X mode, or there were enough ^X's to cancel
1921 // the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below)
1922 // do normal expansion when interrupting a different mode (say
1923 // ^X^F^X^P or ^P^X^X^P, see below)
1924 // nothing changes if interrupting mode 0, (eg, the flag
1925 // doesn't change when going to ADDING mode -- Acevedo
1926 if (!(compl_cont_status & CONT_INTRPT))
1927 compl_cont_status |= CONT_LOCAL;
1928 else if (compl_cont_mode != 0)
1929 compl_cont_status &= ~CONT_LOCAL;
1930 // FALLTHROUGH
1931 default:
1932 // If we have typed at least 2 ^X's... for modes != 0, we set
1933 // compl_cont_status = 0 (eg, as if we had just started ^X
1934 // mode).
1935 // For mode 0, we set "compl_cont_mode" to an impossible
1936 // value, in both cases ^X^X can be used to restart the same
1937 // mode (avoiding ADDING mode).
1938 // Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start
1939 // 'complete' and local ^P expansions respectively.
1940 // In mode 0 an extra ^X is needed since ^X^P goes to ADDING
1941 // mode -- Acevedo
1942 if (c == Ctrl_X)
1943 {
1944 if (compl_cont_mode != 0)
1945 compl_cont_status = 0;
1946 else
1947 compl_cont_mode = CTRL_X_NOT_DEFINED_YET;
1948 }
1949 ctrl_x_mode = CTRL_X_NORMAL;
1950 edit_submode = NULL;
1951 showmode();
1952 break;
1953 }
1954 }
1955 else if (ctrl_x_mode != CTRL_X_NORMAL)
1956 {
1957 // We're already in CTRL-X mode, do we stay in it?
1958 if (!vim_is_ctrl_x_key(c))
1959 {
1960 if (ctrl_x_mode == CTRL_X_SCROLL)
1961 ctrl_x_mode = CTRL_X_NORMAL;
1962 else
1963 ctrl_x_mode = CTRL_X_FINISHED;
1964 edit_submode = NULL;
1965 }
1966 showmode();
1967 }
1968
1969 if (compl_started || ctrl_x_mode == CTRL_X_FINISHED)
1970 {
1971 // Show error message from attempted keyword completion (probably
1972 // 'Pattern not found') until another key is hit, then go back to
1973 // showing what mode we are in.
1974 showmode();
1975 if ((ctrl_x_mode == CTRL_X_NORMAL && c != Ctrl_N && c != Ctrl_P
1976 && c != Ctrl_R && !ins_compl_pum_key(c))
1977 || ctrl_x_mode == CTRL_X_FINISHED)
1978 {
1979 // Get here when we have finished typing a sequence of ^N and
1980 // ^P or other completion characters in CTRL-X mode. Free up
1981 // memory that was used, and make sure we can redo the insert.
1982 if (compl_curr_match != NULL || compl_leader != NULL || c == Ctrl_E)
1983 {
1984 // If any of the original typed text has been changed, eg when
1985 // ignorecase is set, we must add back-spaces to the redo
1986 // buffer. We add as few as necessary to delete just the part
1987 // of the original text that has changed.
1988 // When using the longest match, edited the match or used
1989 // CTRL-E then don't use the current match.
1990 if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E)
1991 ptr = compl_curr_match->cp_str;
1992 else
1993 ptr = NULL;
1994 ins_compl_fixRedoBufForLeader(ptr);
1995 }
1996
1997#ifdef FEAT_CINDENT
Bram Moolenaarb20b9e12019-09-21 20:48:04 +02001998 want_cindent = (get_can_cindent() && cindent_on());
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001999#endif
2000 // When completing whole lines: fix indent for 'cindent'.
2001 // Otherwise, break line if it's too long.
2002 if (compl_cont_mode == CTRL_X_WHOLE_LINE)
2003 {
2004#ifdef FEAT_CINDENT
2005 // re-indent the current line
2006 if (want_cindent)
2007 {
2008 do_c_expr_indent();
2009 want_cindent = FALSE; // don't do it again
2010 }
2011#endif
2012 }
2013 else
2014 {
2015 int prev_col = curwin->w_cursor.col;
2016
2017 // put the cursor on the last char, for 'tw' formatting
2018 if (prev_col > 0)
2019 dec_cursor();
2020 // only format when something was inserted
2021 if (!arrow_used && !ins_need_undo_get() && c != Ctrl_E)
2022 insertchar(NUL, 0, -1);
2023 if (prev_col > 0
2024 && ml_get_curline()[curwin->w_cursor.col] != NUL)
2025 inc_cursor();
2026 }
2027
2028 // If the popup menu is displayed pressing CTRL-Y means accepting
2029 // the selection without inserting anything. When
2030 // compl_enter_selects is set the Enter key does the same.
2031 if ((c == Ctrl_Y || (compl_enter_selects
2032 && (c == CAR || c == K_KENTER || c == NL)))
2033 && pum_visible())
2034 retval = TRUE;
2035
2036 // CTRL-E means completion is Ended, go back to the typed text.
2037 // but only do this, if the Popup is still visible
2038 if (c == Ctrl_E)
2039 {
2040 ins_compl_delete();
2041 if (compl_leader != NULL)
2042 ins_bytes(compl_leader + ins_compl_len());
2043 else if (compl_first_match != NULL)
2044 ins_bytes(compl_orig_text + ins_compl_len());
2045 retval = TRUE;
2046 }
2047
2048 auto_format(FALSE, TRUE);
2049
2050 ins_compl_free();
2051 compl_started = FALSE;
2052 compl_matches = 0;
2053 if (!shortmess(SHM_COMPLETIONMENU))
2054 msg_clr_cmdline(); // necessary for "noshowmode"
2055 ctrl_x_mode = CTRL_X_NORMAL;
2056 compl_enter_selects = FALSE;
2057 if (edit_submode != NULL)
2058 {
2059 edit_submode = NULL;
2060 showmode();
2061 }
2062
2063#ifdef FEAT_CMDWIN
2064 if (c == Ctrl_C && cmdwin_type != 0)
2065 // Avoid the popup menu remains displayed when leaving the
2066 // command line window.
2067 update_screen(0);
2068#endif
2069#ifdef FEAT_CINDENT
2070 // Indent now if a key was typed that is in 'cinkeys'.
2071 if (want_cindent && in_cinkeys(KEY_COMPLETE, ' ', inindent(0)))
2072 do_c_expr_indent();
2073#endif
2074 // Trigger the CompleteDone event to give scripts a chance to act
2075 // upon the completion.
2076 ins_apply_autocmds(EVENT_COMPLETEDONE);
2077 }
2078 }
2079 else if (ctrl_x_mode == CTRL_X_LOCAL_MSG)
2080 // Trigger the CompleteDone event to give scripts a chance to act
2081 // upon the (possibly failed) completion.
2082 ins_apply_autocmds(EVENT_COMPLETEDONE);
2083
2084 // reset continue_* if we left expansion-mode, if we stay they'll be
2085 // (re)set properly in ins_complete()
2086 if (!vim_is_ctrl_x_key(c))
2087 {
2088 compl_cont_status = 0;
2089 compl_cont_mode = 0;
2090 }
2091
2092 return retval;
2093}
2094
2095/*
2096 * Fix the redo buffer for the completion leader replacing some of the typed
2097 * text. This inserts backspaces and appends the changed text.
2098 * "ptr" is the known leader text or NUL.
2099 */
2100 static void
2101ins_compl_fixRedoBufForLeader(char_u *ptr_arg)
2102{
2103 int len;
2104 char_u *p;
2105 char_u *ptr = ptr_arg;
2106
2107 if (ptr == NULL)
2108 {
2109 if (compl_leader != NULL)
2110 ptr = compl_leader;
2111 else
2112 return; // nothing to do
2113 }
2114 if (compl_orig_text != NULL)
2115 {
2116 p = compl_orig_text;
2117 for (len = 0; p[len] != NUL && p[len] == ptr[len]; ++len)
2118 ;
2119 if (len > 0)
2120 len -= (*mb_head_off)(p, p + len);
2121 for (p += len; *p != NUL; MB_PTR_ADV(p))
2122 AppendCharToRedobuff(K_BS);
2123 }
2124 else
2125 len = 0;
2126 if (ptr != NULL)
2127 AppendToRedobuffLit(ptr + len, -1);
2128}
2129
2130/*
2131 * Loops through the list of windows, loaded-buffers or non-loaded-buffers
2132 * (depending on flag) starting from buf and looking for a non-scanned
2133 * buffer (other than curbuf). curbuf is special, if it is called with
2134 * buf=curbuf then it has to be the first call for a given flag/expansion.
2135 *
2136 * Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo
2137 */
2138 static buf_T *
2139ins_compl_next_buf(buf_T *buf, int flag)
2140{
2141 static win_T *wp = NULL;
2142
2143 if (flag == 'w') // just windows
2144 {
2145 if (buf == curbuf || wp == NULL) // first call for this flag/expansion
2146 wp = curwin;
2147 while ((wp = (wp->w_next != NULL ? wp->w_next : firstwin)) != curwin
2148 && wp->w_buffer->b_scanned)
2149 ;
2150 buf = wp->w_buffer;
2151 }
2152 else
2153 // 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U'
2154 // (unlisted buffers)
2155 // When completing whole lines skip unloaded buffers.
2156 while ((buf = (buf->b_next != NULL ? buf->b_next : firstbuf)) != curbuf
2157 && ((flag == 'U'
2158 ? buf->b_p_bl
2159 : (!buf->b_p_bl
2160 || (buf->b_ml.ml_mfp == NULL) != (flag == 'u')))
2161 || buf->b_scanned))
2162 ;
2163 return buf;
2164}
2165
2166#ifdef FEAT_COMPL_FUNC
2167/*
2168 * Execute user defined complete function 'completefunc' or 'omnifunc', and
2169 * get matches in "matches".
2170 */
2171 static void
2172expand_by_function(
2173 int type, // CTRL_X_OMNI or CTRL_X_FUNCTION
2174 char_u *base)
2175{
2176 list_T *matchlist = NULL;
2177 dict_T *matchdict = NULL;
2178 typval_T args[3];
2179 char_u *funcname;
2180 pos_T pos;
2181 win_T *curwin_save;
2182 buf_T *curbuf_save;
2183 typval_T rettv;
2184 int save_State = State;
2185
2186 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
2187 if (*funcname == NUL)
2188 return;
2189
2190 // Call 'completefunc' to obtain the list of matches.
2191 args[0].v_type = VAR_NUMBER;
2192 args[0].vval.v_number = 0;
2193 args[1].v_type = VAR_STRING;
2194 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2195 args[2].v_type = VAR_UNKNOWN;
2196
2197 pos = curwin->w_cursor;
2198 curwin_save = curwin;
2199 curbuf_save = curbuf;
2200
2201 // Call a function, which returns a list or dict.
2202 if (call_vim_function(funcname, 2, args, &rettv) == OK)
2203 {
2204 switch (rettv.v_type)
2205 {
2206 case VAR_LIST:
2207 matchlist = rettv.vval.v_list;
2208 break;
2209 case VAR_DICT:
2210 matchdict = rettv.vval.v_dict;
2211 break;
2212 case VAR_SPECIAL:
2213 if (rettv.vval.v_number == VVAL_NONE)
2214 compl_opt_suppress_empty = TRUE;
2215 // FALLTHROUGH
2216 default:
2217 // TODO: Give error message?
2218 clear_tv(&rettv);
2219 break;
2220 }
2221 }
2222
2223 if (curwin_save != curwin || curbuf_save != curbuf)
2224 {
2225 emsg(_(e_complwin));
2226 goto theend;
2227 }
2228 curwin->w_cursor = pos; // restore the cursor position
2229 validate_cursor();
2230 if (!EQUAL_POS(curwin->w_cursor, pos))
2231 {
2232 emsg(_(e_compldel));
2233 goto theend;
2234 }
2235
2236 if (matchlist != NULL)
2237 ins_compl_add_list(matchlist);
2238 else if (matchdict != NULL)
2239 ins_compl_add_dict(matchdict);
2240
2241theend:
2242 // Restore State, it might have been changed.
2243 State = save_State;
2244
2245 if (matchdict != NULL)
2246 dict_unref(matchdict);
2247 if (matchlist != NULL)
2248 list_unref(matchlist);
2249}
2250#endif // FEAT_COMPL_FUNC
2251
2252#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2253/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002254 * Add a match to the list of matches from a typeval_T.
2255 * If the given string is already in the list of completions, then return
2256 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2257 * maybe because alloc() returns NULL, then FAIL is returned.
2258 */
2259 static int
2260ins_compl_add_tv(typval_T *tv, int dir)
2261{
2262 char_u *word;
2263 int dup = FALSE;
2264 int empty = FALSE;
2265 int flags = 0;
2266 char_u *(cptext[CPT_COUNT]);
2267
2268 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2269 {
2270 word = dict_get_string(tv->vval.v_dict, (char_u *)"word", FALSE);
2271 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict,
2272 (char_u *)"abbr", FALSE);
2273 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict,
2274 (char_u *)"menu", FALSE);
2275 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict,
2276 (char_u *)"kind", FALSE);
2277 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict,
2278 (char_u *)"info", FALSE);
2279 cptext[CPT_USER_DATA] = dict_get_string(tv->vval.v_dict,
2280 (char_u *)"user_data", FALSE);
2281 if (dict_get_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL
2282 && dict_get_number(tv->vval.v_dict, (char_u *)"icase"))
2283 flags |= CP_ICASE;
2284 if (dict_get_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
2285 dup = dict_get_number(tv->vval.v_dict, (char_u *)"dup");
2286 if (dict_get_string(tv->vval.v_dict, (char_u *)"empty", FALSE) != NULL)
2287 empty = dict_get_number(tv->vval.v_dict, (char_u *)"empty");
2288 if (dict_get_string(tv->vval.v_dict, (char_u *)"equal", FALSE) != NULL
2289 && dict_get_number(tv->vval.v_dict, (char_u *)"equal"))
2290 flags |= CP_EQUAL;
2291 }
2292 else
2293 {
2294 word = tv_get_string_chk(tv);
2295 vim_memset(cptext, 0, sizeof(cptext));
2296 }
2297 if (word == NULL || (!empty && *word == NUL))
2298 return FAIL;
2299 return ins_compl_add(word, -1, NULL, cptext, dir, flags, dup);
2300}
2301
2302/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002303 * Add completions from a list.
2304 */
2305 static void
2306ins_compl_add_list(list_T *list)
2307{
2308 listitem_T *li;
2309 int dir = compl_direction;
2310
2311 // Go through the List with matches and add each of them.
2312 for (li = list->lv_first; li != NULL; li = li->li_next)
2313 {
2314 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
2315 // if dir was BACKWARD then honor it just once
2316 dir = FORWARD;
2317 else if (did_emsg)
2318 break;
2319 }
2320}
2321
2322/*
2323 * Add completions from a dict.
2324 */
2325 static void
2326ins_compl_add_dict(dict_T *dict)
2327{
2328 dictitem_T *di_refresh;
2329 dictitem_T *di_words;
2330
2331 // Check for optional "refresh" item.
2332 compl_opt_refresh_always = FALSE;
2333 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2334 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2335 {
2336 char_u *v = di_refresh->di_tv.vval.v_string;
2337
2338 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2339 compl_opt_refresh_always = TRUE;
2340 }
2341
2342 // Add completions from a "words" list.
2343 di_words = dict_find(dict, (char_u *)"words", 5);
2344 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2345 ins_compl_add_list(di_words->di_tv.vval.v_list);
2346}
2347
2348/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002349 * Start completion for the complete() function.
2350 * "startcol" is where the matched text starts (1 is first column).
2351 * "list" is the list of matches.
2352 */
2353 static void
2354set_completion(colnr_T startcol, list_T *list)
2355{
2356 int save_w_wrow = curwin->w_wrow;
2357 int save_w_leftcol = curwin->w_leftcol;
2358 int flags = CP_ORIGINAL_TEXT;
2359
2360 // If already doing completions stop it.
2361 if (ctrl_x_mode != CTRL_X_NORMAL)
2362 ins_compl_prep(' ');
2363 ins_compl_clear();
2364 ins_compl_free();
2365
2366 compl_direction = FORWARD;
2367 if (startcol > curwin->w_cursor.col)
2368 startcol = curwin->w_cursor.col;
2369 compl_col = startcol;
2370 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2371 // compl_pattern doesn't need to be set
2372 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2373 if (p_ic)
2374 flags |= CP_ICASE;
2375 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
2376 -1, NULL, NULL, 0, flags, FALSE) != OK)
2377 return;
2378
2379 ctrl_x_mode = CTRL_X_EVAL;
2380
2381 ins_compl_add_list(list);
2382 compl_matches = ins_compl_make_cyclic();
2383 compl_started = TRUE;
2384 compl_used_match = TRUE;
2385 compl_cont_status = 0;
2386
2387 compl_curr_match = compl_first_match;
2388 if (compl_no_insert || compl_no_select)
2389 {
2390 ins_complete(K_DOWN, FALSE);
2391 if (compl_no_select)
2392 // Down/Up has no real effect.
2393 ins_complete(K_UP, FALSE);
2394 }
2395 else
2396 ins_complete(Ctrl_N, FALSE);
2397 compl_enter_selects = compl_no_insert;
2398
2399 // Lazily show the popup menu, unless we got interrupted.
2400 if (!compl_interrupted)
2401 show_pum(save_w_wrow, save_w_leftcol);
2402 out_flush();
2403}
2404
2405/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002406 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002407 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002408 void
2409f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002410{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002411 int startcol;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002412
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002413 if ((State & INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002414 {
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002415 emsg(_("E785: complete() can only be used in Insert mode"));
2416 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002417 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002418
2419 // Check for undo allowed here, because if something was already inserted
2420 // the line was already saved for undo and this check isn't done.
2421 if (!undo_allowed())
2422 return;
2423
2424 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002425 {
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002426 emsg(_(e_invarg));
2427 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002428 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002429
2430 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
2431 if (startcol <= 0)
2432 return;
2433
2434 set_completion(startcol - 1, argvars[1].vval.v_list);
2435}
2436
2437/*
2438 * "complete_add()" function
2439 */
2440 void
2441f_complete_add(typval_T *argvars, typval_T *rettv)
2442{
2443 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
2444}
2445
2446/*
2447 * "complete_check()" function
2448 */
2449 void
2450f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
2451{
2452 int saved = RedrawingDisabled;
2453
2454 RedrawingDisabled = 0;
2455 ins_compl_check_keys(0, TRUE);
2456 rettv->vval.v_number = ins_compl_interrupted();
2457 RedrawingDisabled = saved;
2458}
2459
2460/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002461 * Return Insert completion mode name string
2462 */
2463 static char_u *
2464ins_compl_mode(void)
2465{
2466 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || compl_started)
2467 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
2468
2469 return (char_u *)"";
2470}
2471
2472/*
2473 * Get complete information
2474 */
2475 static void
2476get_complete_info(list_T *what_list, dict_T *retdict)
2477{
2478 int ret = OK;
2479 listitem_T *item;
2480#define CI_WHAT_MODE 0x01
2481#define CI_WHAT_PUM_VISIBLE 0x02
2482#define CI_WHAT_ITEMS 0x04
2483#define CI_WHAT_SELECTED 0x08
2484#define CI_WHAT_INSERTED 0x10
2485#define CI_WHAT_ALL 0xff
2486 int what_flag;
2487
2488 if (what_list == NULL)
2489 what_flag = CI_WHAT_ALL;
2490 else
2491 {
2492 what_flag = 0;
2493 for (item = what_list->lv_first; item != NULL; item = item->li_next)
2494 {
2495 char_u *what = tv_get_string(&item->li_tv);
2496
2497 if (STRCMP(what, "mode") == 0)
2498 what_flag |= CI_WHAT_MODE;
2499 else if (STRCMP(what, "pum_visible") == 0)
2500 what_flag |= CI_WHAT_PUM_VISIBLE;
2501 else if (STRCMP(what, "items") == 0)
2502 what_flag |= CI_WHAT_ITEMS;
2503 else if (STRCMP(what, "selected") == 0)
2504 what_flag |= CI_WHAT_SELECTED;
2505 else if (STRCMP(what, "inserted") == 0)
2506 what_flag |= CI_WHAT_INSERTED;
2507 }
2508 }
2509
2510 if (ret == OK && (what_flag & CI_WHAT_MODE))
2511 ret = dict_add_string(retdict, "mode", ins_compl_mode());
2512
2513 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
2514 ret = dict_add_number(retdict, "pum_visible", pum_visible());
2515
2516 if (ret == OK && (what_flag & CI_WHAT_ITEMS))
2517 {
2518 list_T *li;
2519 dict_T *di;
2520 compl_T *match;
2521
2522 li = list_alloc();
2523 if (li == NULL)
2524 return;
2525 ret = dict_add_list(retdict, "items", li);
2526 if (ret == OK && compl_first_match != NULL)
2527 {
2528 match = compl_first_match;
2529 do
2530 {
2531 if (!(match->cp_flags & CP_ORIGINAL_TEXT))
2532 {
2533 di = dict_alloc();
2534 if (di == NULL)
2535 return;
2536 ret = list_append_dict(li, di);
2537 if (ret != OK)
2538 return;
2539 dict_add_string(di, "word", match->cp_str);
2540 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
2541 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
2542 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
2543 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
2544 dict_add_string(di, "user_data",
2545 match->cp_text[CPT_USER_DATA]);
2546 }
2547 match = match->cp_next;
2548 }
2549 while (match != NULL && match != compl_first_match);
2550 }
2551 }
2552
2553 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
2554 ret = dict_add_number(retdict, "selected", (compl_curr_match != NULL) ?
2555 compl_curr_match->cp_number - 1 : -1);
2556
2557 // TODO
2558 // if (ret == OK && (what_flag & CI_WHAT_INSERTED))
2559}
2560
2561/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002562 * "complete_info()" function
2563 */
2564 void
2565f_complete_info(typval_T *argvars, typval_T *rettv)
2566{
2567 list_T *what_list = NULL;
2568
2569 if (rettv_dict_alloc(rettv) != OK)
2570 return;
2571
2572 if (argvars[0].v_type != VAR_UNKNOWN)
2573 {
2574 if (argvars[0].v_type != VAR_LIST)
2575 {
2576 emsg(_(e_listreq));
2577 return;
2578 }
2579 what_list = argvars[0].vval.v_list;
2580 }
2581 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002582}
2583#endif
2584
2585/*
2586 * Get the next expansion(s), using "compl_pattern".
2587 * The search starts at position "ini" in curbuf and in the direction
2588 * compl_direction.
2589 * When "compl_started" is FALSE start at that position, otherwise continue
2590 * where we stopped searching before.
2591 * This may return before finding all the matches.
2592 * Return the total number of matches or -1 if still unknown -- Acevedo
2593 */
2594 static int
2595ins_compl_get_exp(pos_T *ini)
2596{
2597 static pos_T first_match_pos;
2598 static pos_T last_match_pos;
2599 static char_u *e_cpt = (char_u *)""; // curr. entry in 'complete'
2600 static int found_all = FALSE; // Found all matches of a
2601 // certain type.
2602 static buf_T *ins_buf = NULL; // buffer being scanned
2603
2604 pos_T *pos;
2605 char_u **matches;
2606 int save_p_scs;
2607 int save_p_ws;
2608 int save_p_ic;
2609 int i;
2610 int num_matches;
2611 int len;
2612 int found_new_match;
2613 int type = ctrl_x_mode;
2614 char_u *ptr;
2615 char_u *dict = NULL;
2616 int dict_f = 0;
2617 int set_match_pos;
2618
2619 if (!compl_started)
2620 {
2621 FOR_ALL_BUFFERS(ins_buf)
2622 ins_buf->b_scanned = 0;
2623 found_all = FALSE;
2624 ins_buf = curbuf;
2625 e_cpt = (compl_cont_status & CONT_LOCAL)
2626 ? (char_u *)"." : curbuf->b_p_cpt;
2627 last_match_pos = first_match_pos = *ini;
2628 }
2629 else if (ins_buf != curbuf && !buf_valid(ins_buf))
2630 ins_buf = curbuf; // In case the buffer was wiped out.
2631
2632 compl_old_match = compl_curr_match; // remember the last current match
2633 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
2634
2635 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
2636 for (;;)
2637 {
2638 found_new_match = FAIL;
2639 set_match_pos = FALSE;
2640
2641 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
2642 // or if found_all says this entry is done. For ^X^L only use the
2643 // entries from 'complete' that look in loaded buffers.
2644 if ((ctrl_x_mode == CTRL_X_NORMAL
2645 || ctrl_x_mode_line_or_eval())
2646 && (!compl_started || found_all))
2647 {
2648 found_all = FALSE;
2649 while (*e_cpt == ',' || *e_cpt == ' ')
2650 e_cpt++;
2651 if (*e_cpt == '.' && !curbuf->b_scanned)
2652 {
2653 ins_buf = curbuf;
2654 first_match_pos = *ini;
2655 // Move the cursor back one character so that ^N can match the
2656 // word immediately after the cursor.
2657 if (ctrl_x_mode == CTRL_X_NORMAL && dec(&first_match_pos) < 0)
2658 {
2659 // Move the cursor to after the last character in the
2660 // buffer, so that word at start of buffer is found
2661 // correctly.
2662 first_match_pos.lnum = ins_buf->b_ml.ml_line_count;
2663 first_match_pos.col =
2664 (colnr_T)STRLEN(ml_get(first_match_pos.lnum));
2665 }
2666 last_match_pos = first_match_pos;
2667 type = 0;
2668
2669 // Remember the first match so that the loop stops when we
2670 // wrap and come back there a second time.
2671 set_match_pos = TRUE;
2672 }
2673 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
2674 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
2675 {
2676 // Scan a buffer, but not the current one.
2677 if (ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
2678 {
2679 compl_started = TRUE;
2680 first_match_pos.col = last_match_pos.col = 0;
2681 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
2682 last_match_pos.lnum = 0;
2683 type = 0;
2684 }
2685 else // unloaded buffer, scan like dictionary
2686 {
2687 found_all = TRUE;
2688 if (ins_buf->b_fname == NULL)
2689 continue;
2690 type = CTRL_X_DICTIONARY;
2691 dict = ins_buf->b_fname;
2692 dict_f = DICT_EXACT;
2693 }
2694 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
2695 ins_buf->b_fname == NULL
2696 ? buf_spname(ins_buf)
2697 : ins_buf->b_sfname == NULL
2698 ? ins_buf->b_fname
2699 : ins_buf->b_sfname);
2700 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2701 }
2702 else if (*e_cpt == NUL)
2703 break;
2704 else
2705 {
2706 if (ctrl_x_mode_line_or_eval())
2707 type = -1;
2708 else if (*e_cpt == 'k' || *e_cpt == 's')
2709 {
2710 if (*e_cpt == 'k')
2711 type = CTRL_X_DICTIONARY;
2712 else
2713 type = CTRL_X_THESAURUS;
2714 if (*++e_cpt != ',' && *e_cpt != NUL)
2715 {
2716 dict = e_cpt;
2717 dict_f = DICT_FIRST;
2718 }
2719 }
2720#ifdef FEAT_FIND_ID
2721 else if (*e_cpt == 'i')
2722 type = CTRL_X_PATH_PATTERNS;
2723 else if (*e_cpt == 'd')
2724 type = CTRL_X_PATH_DEFINES;
2725#endif
2726 else if (*e_cpt == ']' || *e_cpt == 't')
2727 {
2728 type = CTRL_X_TAGS;
2729 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
2730 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2731 }
2732 else
2733 type = -1;
2734
2735 // in any case e_cpt is advanced to the next entry
2736 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
2737
2738 found_all = TRUE;
2739 if (type == -1)
2740 continue;
2741 }
2742 }
2743
2744 // If complete() was called then compl_pattern has been reset. The
2745 // following won't work then, bail out.
2746 if (compl_pattern == NULL)
2747 break;
2748
2749 switch (type)
2750 {
2751 case -1:
2752 break;
2753#ifdef FEAT_FIND_ID
2754 case CTRL_X_PATH_PATTERNS:
2755 case CTRL_X_PATH_DEFINES:
2756 find_pattern_in_path(compl_pattern, compl_direction,
2757 (int)STRLEN(compl_pattern), FALSE, FALSE,
2758 (type == CTRL_X_PATH_DEFINES
2759 && !(compl_cont_status & CONT_SOL))
2760 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
2761 (linenr_T)1, (linenr_T)MAXLNUM);
2762 break;
2763#endif
2764
2765 case CTRL_X_DICTIONARY:
2766 case CTRL_X_THESAURUS:
2767 ins_compl_dictionaries(
2768 dict != NULL ? dict
2769 : (type == CTRL_X_THESAURUS
2770 ? (*curbuf->b_p_tsr == NUL
2771 ? p_tsr
2772 : curbuf->b_p_tsr)
2773 : (*curbuf->b_p_dict == NUL
2774 ? p_dict
2775 : curbuf->b_p_dict)),
2776 compl_pattern,
2777 dict != NULL ? dict_f
2778 : 0, type == CTRL_X_THESAURUS);
2779 dict = NULL;
2780 break;
2781
2782 case CTRL_X_TAGS:
2783 // set p_ic according to p_ic, p_scs and pat for find_tags().
2784 save_p_ic = p_ic;
2785 p_ic = ignorecase(compl_pattern);
2786
2787 // Find up to TAG_MANY matches. Avoids that an enormous number
2788 // of matches is found when compl_pattern is empty
Bram Moolenaar45e18cb2019-04-28 18:05:35 +02002789 g_tag_at_cursor = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002790 if (find_tags(compl_pattern, &num_matches, &matches,
2791 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
2792 | (ctrl_x_mode != CTRL_X_NORMAL ? TAG_VERBOSE : 0),
2793 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002794 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar45e18cb2019-04-28 18:05:35 +02002795 g_tag_at_cursor = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002796 p_ic = save_p_ic;
2797 break;
2798
2799 case CTRL_X_FILES:
2800 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
2801 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
2802 {
2803
2804 // May change home directory back to "~".
2805 tilde_replace(compl_pattern, num_matches, matches);
Bram Moolenaarac3150d2019-07-28 16:36:39 +02002806#ifdef BACKSLASH_IN_FILENAME
2807 if (curbuf->b_p_csl[0] != NUL)
2808 {
2809 int i;
2810
2811 for (i = 0; i < num_matches; ++i)
2812 {
2813 char_u *ptr = matches[i];
2814
2815 while (*ptr != NUL)
2816 {
2817 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
2818 *ptr = '/';
2819 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
2820 *ptr = '\\';
2821 ptr += (*mb_ptr2len)(ptr);
2822 }
2823 }
2824 }
2825#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002826 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
2827 }
2828 break;
2829
2830 case CTRL_X_CMDLINE:
2831 if (expand_cmdline(&compl_xp, compl_pattern,
2832 (int)STRLEN(compl_pattern),
2833 &num_matches, &matches) == EXPAND_OK)
2834 ins_compl_add_matches(num_matches, matches, FALSE);
2835 break;
2836
2837#ifdef FEAT_COMPL_FUNC
2838 case CTRL_X_FUNCTION:
2839 case CTRL_X_OMNI:
2840 expand_by_function(type, compl_pattern);
2841 break;
2842#endif
2843
2844 case CTRL_X_SPELL:
2845#ifdef FEAT_SPELL
2846 num_matches = expand_spelling(first_match_pos.lnum,
2847 compl_pattern, &matches);
2848 if (num_matches > 0)
2849 ins_compl_add_matches(num_matches, matches, p_ic);
2850#endif
2851 break;
2852
2853 default: // normal ^P/^N and ^X^L
2854 // If 'infercase' is set, don't use 'smartcase' here
2855 save_p_scs = p_scs;
2856 if (ins_buf->b_p_inf)
2857 p_scs = FALSE;
2858
2859 // Buffers other than curbuf are scanned from the beginning or the
2860 // end but never from the middle, thus setting nowrapscan in this
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002861 // buffer is a good idea, on the other hand, we always set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002862 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
2863 save_p_ws = p_ws;
2864 if (ins_buf != curbuf)
2865 p_ws = FALSE;
2866 else if (*e_cpt == '.')
2867 p_ws = TRUE;
2868 for (;;)
2869 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02002870 int cont_s_ipos = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002871
2872 ++msg_silent; // Don't want messages for wrapscan.
2873
2874 // ctrl_x_mode_line_or_eval() || word-wise search that
2875 // has added a word that was at the beginning of the line
2876 if (ctrl_x_mode_line_or_eval()
2877 || (compl_cont_status & CONT_SOL))
2878 found_new_match = search_for_exact_line(ins_buf, pos,
2879 compl_direction, compl_pattern);
2880 else
2881 found_new_match = searchit(NULL, ins_buf, pos, NULL,
2882 compl_direction,
2883 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
Bram Moolenaar92ea26b2019-10-18 20:53:34 +02002884 RE_LAST, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002885 --msg_silent;
2886 if (!compl_started || set_match_pos)
2887 {
2888 // set "compl_started" even on fail
2889 compl_started = TRUE;
2890 first_match_pos = *pos;
2891 last_match_pos = *pos;
2892 set_match_pos = FALSE;
2893 }
2894 else if (first_match_pos.lnum == last_match_pos.lnum
2895 && first_match_pos.col == last_match_pos.col)
2896 found_new_match = FAIL;
2897 if (found_new_match == FAIL)
2898 {
2899 if (ins_buf == curbuf)
2900 found_all = TRUE;
2901 break;
2902 }
2903
2904 // when ADDING, the text before the cursor matches, skip it
2905 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
2906 && ini->lnum == pos->lnum
2907 && ini->col == pos->col)
2908 continue;
2909 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
2910 if (ctrl_x_mode_line_or_eval())
2911 {
2912 if (compl_cont_status & CONT_ADDING)
2913 {
2914 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
2915 continue;
2916 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
2917 if (!p_paste)
2918 ptr = skipwhite(ptr);
2919 }
2920 len = (int)STRLEN(ptr);
2921 }
2922 else
2923 {
2924 char_u *tmp_ptr = ptr;
2925
2926 if (compl_cont_status & CONT_ADDING)
2927 {
2928 tmp_ptr += compl_length;
2929 // Skip if already inside a word.
2930 if (vim_iswordp(tmp_ptr))
2931 continue;
2932 // Find start of next word.
2933 tmp_ptr = find_word_start(tmp_ptr);
2934 }
2935 // Find end of this word.
2936 tmp_ptr = find_word_end(tmp_ptr);
2937 len = (int)(tmp_ptr - ptr);
2938
2939 if ((compl_cont_status & CONT_ADDING)
2940 && len == compl_length)
2941 {
2942 if (pos->lnum < ins_buf->b_ml.ml_line_count)
2943 {
2944 // Try next line, if any. the new word will be
2945 // "join" as if the normal command "J" was used.
2946 // IOSIZE is always greater than
2947 // compl_length, so the next STRNCPY always
2948 // works -- Acevedo
2949 STRNCPY(IObuff, ptr, len);
2950 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
2951 tmp_ptr = ptr = skipwhite(ptr);
2952 // Find start of next word.
2953 tmp_ptr = find_word_start(tmp_ptr);
2954 // Find end of next word.
2955 tmp_ptr = find_word_end(tmp_ptr);
2956 if (tmp_ptr > ptr)
2957 {
2958 if (*ptr != ')' && IObuff[len - 1] != TAB)
2959 {
2960 if (IObuff[len - 1] != ' ')
2961 IObuff[len++] = ' ';
2962 // IObuf =~ "\k.* ", thus len >= 2
2963 if (p_js
2964 && (IObuff[len - 2] == '.'
2965 || (vim_strchr(p_cpo, CPO_JOINSP)
2966 == NULL
2967 && (IObuff[len - 2] == '?'
2968 || IObuff[len - 2] == '!'))))
2969 IObuff[len++] = ' ';
2970 }
2971 // copy as much as possible of the new word
2972 if (tmp_ptr - ptr >= IOSIZE - len)
2973 tmp_ptr = ptr + IOSIZE - len - 1;
2974 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
2975 len += (int)(tmp_ptr - ptr);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02002976 cont_s_ipos = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002977 }
2978 IObuff[len] = NUL;
2979 ptr = IObuff;
2980 }
2981 if (len == compl_length)
2982 continue;
2983 }
2984 }
2985 if (ins_compl_add_infercase(ptr, len, p_ic,
2986 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
Bram Moolenaard9eefe32019-04-06 14:22:21 +02002987 0, cont_s_ipos) != NOTDONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002988 {
2989 found_new_match = OK;
2990 break;
2991 }
2992 }
2993 p_scs = save_p_scs;
2994 p_ws = save_p_ws;
2995 }
2996
2997 // check if compl_curr_match has changed, (e.g. other type of
2998 // expansion added something)
2999 if (type != 0 && compl_curr_match != compl_old_match)
3000 found_new_match = OK;
3001
3002 // break the loop for specialized modes (use 'complete' just for the
3003 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3004 // match
3005 if ((ctrl_x_mode != CTRL_X_NORMAL
3006 && !ctrl_x_mode_line_or_eval()) || found_new_match != FAIL)
3007 {
3008 if (got_int)
3009 break;
3010 // Fill the popup menu as soon as possible.
3011 if (type != -1)
3012 ins_compl_check_keys(0, FALSE);
3013
3014 if ((ctrl_x_mode != CTRL_X_NORMAL
3015 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3016 break;
3017 compl_started = TRUE;
3018 }
3019 else
3020 {
3021 // Mark a buffer scanned when it has been scanned completely
3022 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3023 ins_buf->b_scanned = TRUE;
3024
3025 compl_started = FALSE;
3026 }
3027 }
3028 compl_started = TRUE;
3029
3030 if ((ctrl_x_mode == CTRL_X_NORMAL || ctrl_x_mode_line_or_eval())
3031 && *e_cpt == NUL) // Got to end of 'complete'
3032 found_new_match = FAIL;
3033
3034 i = -1; // total of matches, unknown
3035 if (found_new_match == FAIL || (ctrl_x_mode != CTRL_X_NORMAL
3036 && !ctrl_x_mode_line_or_eval()))
3037 i = ins_compl_make_cyclic();
3038
3039 if (compl_old_match != NULL)
3040 {
3041 // If several matches were added (FORWARD) or the search failed and has
3042 // just been made cyclic then we have to move compl_curr_match to the
3043 // next or previous entry (if any) -- Acevedo
3044 compl_curr_match = compl_direction == FORWARD ? compl_old_match->cp_next
3045 : compl_old_match->cp_prev;
3046 if (compl_curr_match == NULL)
3047 compl_curr_match = compl_old_match;
3048 }
3049 return i;
3050}
3051
3052/*
3053 * Delete the old text being completed.
3054 */
3055 void
3056ins_compl_delete(void)
3057{
3058 int col;
3059
3060 // In insert mode: Delete the typed part.
3061 // In replace mode: Put the old characters back, if any.
3062 col = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
3063 if ((int)curwin->w_cursor.col > col)
3064 {
3065 if (stop_arrow() == FAIL)
3066 return;
3067 backspace_until_column(col);
3068 }
3069
3070 // TODO: is this sufficient for redrawing? Redrawing everything causes
3071 // flicker, thus we can't do that.
3072 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003073#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003074 // clear v:completed_item
3075 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003076#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003077}
3078
3079/*
3080 * Insert the new text being completed.
3081 * "in_compl_func" is TRUE when called from complete_check().
3082 */
3083 void
3084ins_compl_insert(int in_compl_func)
3085{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003086 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003087 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003088 compl_used_match = FALSE;
3089 else
3090 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003091#ifdef FEAT_EVAL
3092 {
3093 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
3094
3095 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
3096 }
3097#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003098 if (!in_compl_func)
3099 compl_curr_match = compl_shown_match;
3100}
3101
3102/*
3103 * Fill in the next completion in the current direction.
3104 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
3105 * get more completions. If it is FALSE, then we just do nothing when there
3106 * are no more completions in a given direction. The latter case is used when
3107 * we are still in the middle of finding completions, to allow browsing
3108 * through the ones found so far.
3109 * Return the total number of matches, or -1 if still unknown -- webb.
3110 *
3111 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
3112 * compl_shown_match here.
3113 *
3114 * Note that this function may be called recursively once only. First with
3115 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
3116 * calls this function with "allow_get_expansion" FALSE.
3117 */
3118 static int
3119ins_compl_next(
3120 int allow_get_expansion,
3121 int count, // repeat completion this many times; should
3122 // be at least 1
3123 int insert_match, // Insert the newly selected match
3124 int in_compl_func) // called from complete_check()
3125{
3126 int num_matches = -1;
3127 int todo = count;
3128 compl_T *found_compl = NULL;
3129 int found_end = FALSE;
3130 int advance;
3131 int started = compl_started;
3132
3133 // When user complete function return -1 for findstart which is next
3134 // time of 'always', compl_shown_match become NULL.
3135 if (compl_shown_match == NULL)
3136 return -1;
3137
3138 if (compl_leader != NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003139 && (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003140 {
3141 // Set "compl_shown_match" to the actually shown match, it may differ
3142 // when "compl_leader" is used to omit some of the matches.
3143 while (!ins_compl_equal(compl_shown_match,
3144 compl_leader, (int)STRLEN(compl_leader))
3145 && compl_shown_match->cp_next != NULL
3146 && compl_shown_match->cp_next != compl_first_match)
3147 compl_shown_match = compl_shown_match->cp_next;
3148
3149 // If we didn't find it searching forward, and compl_shows_dir is
3150 // backward, find the last match.
3151 if (compl_shows_dir == BACKWARD
3152 && !ins_compl_equal(compl_shown_match,
3153 compl_leader, (int)STRLEN(compl_leader))
3154 && (compl_shown_match->cp_next == NULL
3155 || compl_shown_match->cp_next == compl_first_match))
3156 {
3157 while (!ins_compl_equal(compl_shown_match,
3158 compl_leader, (int)STRLEN(compl_leader))
3159 && compl_shown_match->cp_prev != NULL
3160 && compl_shown_match->cp_prev != compl_first_match)
3161 compl_shown_match = compl_shown_match->cp_prev;
3162 }
3163 }
3164
3165 if (allow_get_expansion && insert_match
3166 && (!(compl_get_longest || compl_restarting) || compl_used_match))
3167 // Delete old text to be replaced
3168 ins_compl_delete();
3169
3170 // When finding the longest common text we stick at the original text,
3171 // don't let CTRL-N or CTRL-P move to the first match.
3172 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
3173
3174 // When restarting the search don't insert the first match either.
3175 if (compl_restarting)
3176 {
3177 advance = FALSE;
3178 compl_restarting = FALSE;
3179 }
3180
3181 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
3182 // around.
3183 while (--todo >= 0)
3184 {
3185 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
3186 {
3187 compl_shown_match = compl_shown_match->cp_next;
3188 found_end = (compl_first_match != NULL
3189 && (compl_shown_match->cp_next == compl_first_match
3190 || compl_shown_match == compl_first_match));
3191 }
3192 else if (compl_shows_dir == BACKWARD
3193 && compl_shown_match->cp_prev != NULL)
3194 {
3195 found_end = (compl_shown_match == compl_first_match);
3196 compl_shown_match = compl_shown_match->cp_prev;
3197 found_end |= (compl_shown_match == compl_first_match);
3198 }
3199 else
3200 {
3201 if (!allow_get_expansion)
3202 {
3203 if (advance)
3204 {
3205 if (compl_shows_dir == BACKWARD)
3206 compl_pending -= todo + 1;
3207 else
3208 compl_pending += todo + 1;
3209 }
3210 return -1;
3211 }
3212
3213 if (!compl_no_select && advance)
3214 {
3215 if (compl_shows_dir == BACKWARD)
3216 --compl_pending;
3217 else
3218 ++compl_pending;
3219 }
3220
3221 // Find matches.
3222 num_matches = ins_compl_get_exp(&compl_startpos);
3223
3224 // handle any pending completions
3225 while (compl_pending != 0 && compl_direction == compl_shows_dir
3226 && advance)
3227 {
3228 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
3229 {
3230 compl_shown_match = compl_shown_match->cp_next;
3231 --compl_pending;
3232 }
3233 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
3234 {
3235 compl_shown_match = compl_shown_match->cp_prev;
3236 ++compl_pending;
3237 }
3238 else
3239 break;
3240 }
3241 found_end = FALSE;
3242 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003243 if ((compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003244 && compl_leader != NULL
3245 && !ins_compl_equal(compl_shown_match,
3246 compl_leader, (int)STRLEN(compl_leader)))
3247 ++todo;
3248 else
3249 // Remember a matching item.
3250 found_compl = compl_shown_match;
3251
3252 // Stop at the end of the list when we found a usable match.
3253 if (found_end)
3254 {
3255 if (found_compl != NULL)
3256 {
3257 compl_shown_match = found_compl;
3258 break;
3259 }
3260 todo = 1; // use first usable match after wrapping around
3261 }
3262 }
3263
3264 // Insert the text of the new completion, or the compl_leader.
3265 if (compl_no_insert && !started)
3266 {
3267 ins_bytes(compl_orig_text + ins_compl_len());
3268 compl_used_match = FALSE;
3269 }
3270 else if (insert_match)
3271 {
3272 if (!compl_get_longest || compl_used_match)
3273 ins_compl_insert(in_compl_func);
3274 else
3275 ins_bytes(compl_leader + ins_compl_len());
3276 }
3277 else
3278 compl_used_match = FALSE;
3279
3280 if (!allow_get_expansion)
3281 {
3282 // may undisplay the popup menu first
3283 ins_compl_upd_pum();
3284
3285 if (pum_enough_matches())
3286 // Will display the popup menu, don't redraw yet to avoid flicker.
3287 pum_call_update_screen();
3288 else
3289 // Not showing the popup menu yet, redraw to show the user what was
3290 // inserted.
3291 update_screen(0);
3292
3293 // display the updated popup menu
3294 ins_compl_show_pum();
3295#ifdef FEAT_GUI
3296 if (gui.in_use)
3297 {
3298 // Show the cursor after the match, not after the redrawn text.
3299 setcursor();
3300 out_flush_cursor(FALSE, FALSE);
3301 }
3302#endif
3303
3304 // Delete old text to be replaced, since we're still searching and
3305 // don't want to match ourselves!
3306 ins_compl_delete();
3307 }
3308
3309 // Enter will select a match when the match wasn't inserted and the popup
3310 // menu is visible.
3311 if (compl_no_insert && !started)
3312 compl_enter_selects = TRUE;
3313 else
3314 compl_enter_selects = !insert_match && compl_match_array != NULL;
3315
3316 // Show the file name for the match (if any)
3317 // Truncate the file name to avoid a wait for return.
3318 if (compl_shown_match->cp_fname != NULL)
3319 {
3320 char *lead = _("match in file");
3321 int space = sc_col - vim_strsize((char_u *)lead) - 2;
3322 char_u *s;
3323 char_u *e;
3324
3325 if (space > 0)
3326 {
3327 // We need the tail that fits. With double-byte encoding going
3328 // back from the end is very slow, thus go from the start and keep
3329 // the text that fits in "space" between "s" and "e".
3330 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
3331 {
3332 space -= ptr2cells(e);
3333 while (space < 0)
3334 {
3335 space += ptr2cells(s);
3336 MB_PTR_ADV(s);
3337 }
3338 }
3339 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
3340 s > compl_shown_match->cp_fname ? "<" : "", s);
3341 msg((char *)IObuff);
3342 redraw_cmdline = FALSE; // don't overwrite!
3343 }
3344 }
3345
3346 return num_matches;
3347}
3348
3349/*
3350 * Call this while finding completions, to check whether the user has hit a key
3351 * that should change the currently displayed completion, or exit completion
3352 * mode. Also, when compl_pending is not zero, show a completion as soon as
3353 * possible. -- webb
3354 * "frequency" specifies out of how many calls we actually check.
3355 * "in_compl_func" is TRUE when called from complete_check(), don't set
3356 * compl_curr_match.
3357 */
3358 void
3359ins_compl_check_keys(int frequency, int in_compl_func)
3360{
3361 static int count = 0;
3362 int c;
3363
3364 // Don't check when reading keys from a script, :normal or feedkeys().
3365 // That would break the test scripts. But do check for keys when called
3366 // from complete_check().
3367 if (!in_compl_func && (using_script() || ex_normal_busy))
3368 return;
3369
3370 // Only do this at regular intervals
3371 if (++count < frequency)
3372 return;
3373 count = 0;
3374
3375 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
3376 // can't do its work correctly.
3377 c = vpeekc_any();
3378 if (c != NUL)
3379 {
3380 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
3381 {
3382 c = safe_vgetc(); // Eat the character
3383 compl_shows_dir = ins_compl_key2dir(c);
3384 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
3385 c != K_UP && c != K_DOWN, in_compl_func);
3386 }
3387 else
3388 {
3389 // Need to get the character to have KeyTyped set. We'll put it
3390 // back with vungetc() below. But skip K_IGNORE.
3391 c = safe_vgetc();
3392 if (c != K_IGNORE)
3393 {
3394 // Don't interrupt completion when the character wasn't typed,
3395 // e.g., when doing @q to replay keys.
3396 if (c != Ctrl_R && KeyTyped)
3397 compl_interrupted = TRUE;
3398
3399 vungetc(c);
3400 }
3401 }
3402 }
3403 if (compl_pending != 0 && !got_int && !compl_no_insert)
3404 {
3405 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
3406
3407 compl_pending = 0;
3408 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
3409 }
3410}
3411
3412/*
3413 * Decide the direction of Insert mode complete from the key typed.
3414 * Returns BACKWARD or FORWARD.
3415 */
3416 static int
3417ins_compl_key2dir(int c)
3418{
3419 if (c == Ctrl_P || c == Ctrl_L
3420 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
3421 return BACKWARD;
3422 return FORWARD;
3423}
3424
3425/*
3426 * Return TRUE for keys that are used for completion only when the popup menu
3427 * is visible.
3428 */
3429 static int
3430ins_compl_pum_key(int c)
3431{
3432 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
3433 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
3434 || c == K_UP || c == K_DOWN);
3435}
3436
3437/*
3438 * Decide the number of completions to move forward.
3439 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
3440 */
3441 static int
3442ins_compl_key2count(int c)
3443{
3444 int h;
3445
3446 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
3447 {
3448 h = pum_get_height();
3449 if (h > 3)
3450 h -= 2; // keep some context
3451 return h;
3452 }
3453 return 1;
3454}
3455
3456/*
3457 * Return TRUE if completion with "c" should insert the match, FALSE if only
3458 * to change the currently selected completion.
3459 */
3460 static int
3461ins_compl_use_match(int c)
3462{
3463 switch (c)
3464 {
3465 case K_UP:
3466 case K_DOWN:
3467 case K_PAGEDOWN:
3468 case K_KPAGEDOWN:
3469 case K_S_DOWN:
3470 case K_PAGEUP:
3471 case K_KPAGEUP:
3472 case K_S_UP:
3473 return FALSE;
3474 }
3475 return TRUE;
3476}
3477
3478/*
3479 * Do Insert mode completion.
3480 * Called when character "c" was typed, which has a meaning for completion.
3481 * Returns OK if completion was done, FAIL if something failed (out of mem).
3482 */
3483 int
3484ins_complete(int c, int enable_pum)
3485{
3486 char_u *line;
3487 int startcol = 0; // column where searched text starts
3488 colnr_T curs_col; // cursor column
3489 int n;
3490 int save_w_wrow;
3491 int save_w_leftcol;
3492 int insert_match;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003493#ifdef FEAT_COMPL_FUNC
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003494 int save_did_ai = did_ai;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003495#endif
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003496 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003497
3498 compl_direction = ins_compl_key2dir(c);
3499 insert_match = ins_compl_use_match(c);
3500
3501 if (!compl_started)
3502 {
3503 // First time we hit ^N or ^P (in a row, I mean)
3504
3505 did_ai = FALSE;
3506#ifdef FEAT_SMARTINDENT
3507 did_si = FALSE;
3508 can_si = FALSE;
3509 can_si_back = FALSE;
3510#endif
3511 if (stop_arrow() == FAIL)
3512 return FAIL;
3513
3514 line = ml_get(curwin->w_cursor.lnum);
3515 curs_col = curwin->w_cursor.col;
3516 compl_pending = 0;
3517
3518 // If this same ctrl_x_mode has been interrupted use the text from
3519 // "compl_startpos" to the cursor as a pattern to add a new word
3520 // instead of expand the one before the cursor, in word-wise if
3521 // "compl_startpos" is not in the same line as the cursor then fix it
3522 // (the line has been split because it was longer than 'tw'). if SOL
3523 // is set then skip the previous pattern, a word at the beginning of
3524 // the line has been inserted, we'll look for that -- Acevedo.
3525 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
3526 && compl_cont_mode == ctrl_x_mode)
3527 {
3528 // it is a continued search
3529 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
3530 if (ctrl_x_mode == CTRL_X_NORMAL
3531 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
3532 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3533 {
3534 if (compl_startpos.lnum != curwin->w_cursor.lnum)
3535 {
3536 // line (probably) wrapped, set compl_startpos to the
3537 // first non_blank in the line, if it is not a wordchar
3538 // include it to get a better pattern, but then we don't
3539 // want the "\\<" prefix, check it bellow
3540 compl_col = (colnr_T)getwhitecols(line);
3541 compl_startpos.col = compl_col;
3542 compl_startpos.lnum = curwin->w_cursor.lnum;
3543 compl_cont_status &= ~CONT_SOL; // clear SOL if present
3544 }
3545 else
3546 {
3547 // S_IPOS was set when we inserted a word that was at the
3548 // beginning of the line, which means that we'll go to SOL
3549 // mode but first we need to redefine compl_startpos
3550 if (compl_cont_status & CONT_S_IPOS)
3551 {
3552 compl_cont_status |= CONT_SOL;
3553 compl_startpos.col = (colnr_T)(skipwhite(
3554 line + compl_length
3555 + compl_startpos.col) - line);
3556 }
3557 compl_col = compl_startpos.col;
3558 }
3559 compl_length = curwin->w_cursor.col - (int)compl_col;
3560 // IObuff is used to add a "word from the next line" would we
3561 // have enough space? just being paranoid
3562#define MIN_SPACE 75
3563 if (compl_length > (IOSIZE - MIN_SPACE))
3564 {
3565 compl_cont_status &= ~CONT_SOL;
3566 compl_length = (IOSIZE - MIN_SPACE);
3567 compl_col = curwin->w_cursor.col - compl_length;
3568 }
3569 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
3570 if (compl_length < 1)
3571 compl_cont_status &= CONT_LOCAL;
3572 }
3573 else if (ctrl_x_mode_line_or_eval())
3574 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
3575 else
3576 compl_cont_status = 0;
3577 }
3578 else
3579 compl_cont_status &= CONT_LOCAL;
3580
3581 if (!(compl_cont_status & CONT_ADDING)) // normal expansion
3582 {
3583 compl_cont_mode = ctrl_x_mode;
3584 if (ctrl_x_mode != CTRL_X_NORMAL)
3585 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
3586 compl_cont_status = 0;
3587 compl_cont_status |= CONT_N_ADDS;
3588 compl_startpos = curwin->w_cursor;
3589 startcol = (int)curs_col;
3590 compl_col = 0;
3591 }
3592
3593 // Work out completion pattern and original text -- webb
3594 if (ctrl_x_mode == CTRL_X_NORMAL || (ctrl_x_mode & CTRL_X_WANT_IDENT))
3595 {
3596 if ((compl_cont_status & CONT_SOL)
3597 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3598 {
3599 if (!(compl_cont_status & CONT_ADDING))
3600 {
3601 while (--startcol >= 0 && vim_isIDc(line[startcol]))
3602 ;
3603 compl_col += ++startcol;
3604 compl_length = curs_col - startcol;
3605 }
3606 if (p_ic)
3607 compl_pattern = str_foldcase(line + compl_col,
3608 compl_length, NULL, 0);
3609 else
3610 compl_pattern = vim_strnsave(line + compl_col,
3611 compl_length);
3612 if (compl_pattern == NULL)
3613 return FAIL;
3614 }
3615 else if (compl_cont_status & CONT_ADDING)
3616 {
3617 char_u *prefix = (char_u *)"\\<";
3618
3619 // we need up to 2 extra chars for the prefix
3620 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3621 compl_length) + 2);
3622 if (compl_pattern == NULL)
3623 return FAIL;
3624 if (!vim_iswordp(line + compl_col)
3625 || (compl_col > 0
3626 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
3627 prefix = (char_u *)"";
3628 STRCPY((char *)compl_pattern, prefix);
3629 (void)quote_meta(compl_pattern + STRLEN(prefix),
3630 line + compl_col, compl_length);
3631 }
3632 else if (--startcol < 0
3633 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
3634 {
3635 // Match any word of at least two chars
3636 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
3637 if (compl_pattern == NULL)
3638 return FAIL;
3639 compl_col += curs_col;
3640 compl_length = 0;
3641 }
3642 else
3643 {
3644 // Search the point of change class of multibyte character
3645 // or not a word single byte character backward.
3646 if (has_mbyte)
3647 {
3648 int base_class;
3649 int head_off;
3650
3651 startcol -= (*mb_head_off)(line, line + startcol);
3652 base_class = mb_get_class(line + startcol);
3653 while (--startcol >= 0)
3654 {
3655 head_off = (*mb_head_off)(line, line + startcol);
3656 if (base_class != mb_get_class(line + startcol
3657 - head_off))
3658 break;
3659 startcol -= head_off;
3660 }
3661 }
3662 else
3663 while (--startcol >= 0 && vim_iswordc(line[startcol]))
3664 ;
3665 compl_col += ++startcol;
3666 compl_length = (int)curs_col - startcol;
3667 if (compl_length == 1)
3668 {
3669 // Only match word with at least two chars -- webb
3670 // there's no need to call quote_meta,
3671 // alloc(7) is enough -- Acevedo
3672 compl_pattern = alloc(7);
3673 if (compl_pattern == NULL)
3674 return FAIL;
3675 STRCPY((char *)compl_pattern, "\\<");
3676 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
3677 STRCAT((char *)compl_pattern, "\\k");
3678 }
3679 else
3680 {
3681 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3682 compl_length) + 2);
3683 if (compl_pattern == NULL)
3684 return FAIL;
3685 STRCPY((char *)compl_pattern, "\\<");
3686 (void)quote_meta(compl_pattern + 2, line + compl_col,
3687 compl_length);
3688 }
3689 }
3690 }
3691 else if (ctrl_x_mode_line_or_eval())
3692 {
3693 compl_col = (colnr_T)getwhitecols(line);
3694 compl_length = (int)curs_col - (int)compl_col;
3695 if (compl_length < 0) // cursor in indent: empty pattern
3696 compl_length = 0;
3697 if (p_ic)
3698 compl_pattern = str_foldcase(line + compl_col, compl_length,
3699 NULL, 0);
3700 else
3701 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3702 if (compl_pattern == NULL)
3703 return FAIL;
3704 }
3705 else if (ctrl_x_mode == CTRL_X_FILES)
3706 {
3707 // Go back to just before the first filename character.
3708 if (startcol > 0)
3709 {
3710 char_u *p = line + startcol;
3711
3712 MB_PTR_BACK(line, p);
3713 while (p > line && vim_isfilec(PTR2CHAR(p)))
3714 MB_PTR_BACK(line, p);
3715 if (p == line && vim_isfilec(PTR2CHAR(p)))
3716 startcol = 0;
3717 else
3718 startcol = (int)(p - line) + 1;
3719 }
3720
3721 compl_col += startcol;
3722 compl_length = (int)curs_col - startcol;
3723 compl_pattern = addstar(line + compl_col, compl_length,
3724 EXPAND_FILES);
3725 if (compl_pattern == NULL)
3726 return FAIL;
3727 }
3728 else if (ctrl_x_mode == CTRL_X_CMDLINE)
3729 {
3730 compl_pattern = vim_strnsave(line, curs_col);
3731 if (compl_pattern == NULL)
3732 return FAIL;
3733 set_cmd_context(&compl_xp, compl_pattern,
3734 (int)STRLEN(compl_pattern), curs_col, FALSE);
3735 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
3736 || compl_xp.xp_context == EXPAND_NOTHING)
3737 // No completion possible, use an empty pattern to get a
3738 // "pattern not found" message.
3739 compl_col = curs_col;
3740 else
3741 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
3742 compl_length = curs_col - compl_col;
3743 }
3744 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
3745 {
3746#ifdef FEAT_COMPL_FUNC
3747 // Call user defined function 'completefunc' with "a:findstart"
3748 // set to 1 to obtain the length of text to use for completion.
3749 typval_T args[3];
3750 int col;
3751 char_u *funcname;
3752 pos_T pos;
3753 win_T *curwin_save;
3754 buf_T *curbuf_save;
3755 int save_State = State;
3756
3757 // Call 'completefunc' or 'omnifunc' and get pattern length as a
3758 // string
3759 funcname = ctrl_x_mode == CTRL_X_FUNCTION
3760 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3761 if (*funcname == NUL)
3762 {
3763 semsg(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
3764 ? "completefunc" : "omnifunc");
3765 // restore did_ai, so that adding comment leader works
3766 did_ai = save_did_ai;
3767 return FAIL;
3768 }
3769
3770 args[0].v_type = VAR_NUMBER;
3771 args[0].vval.v_number = 1;
3772 args[1].v_type = VAR_STRING;
3773 args[1].vval.v_string = (char_u *)"";
3774 args[2].v_type = VAR_UNKNOWN;
3775 pos = curwin->w_cursor;
3776 curwin_save = curwin;
3777 curbuf_save = curbuf;
3778 col = call_func_retnr(funcname, 2, args);
3779
3780 State = save_State;
3781 if (curwin_save != curwin || curbuf_save != curbuf)
3782 {
3783 emsg(_(e_complwin));
3784 return FAIL;
3785 }
3786 curwin->w_cursor = pos; // restore the cursor position
3787 validate_cursor();
3788 if (!EQUAL_POS(curwin->w_cursor, pos))
3789 {
3790 emsg(_(e_compldel));
3791 return FAIL;
3792 }
3793
3794 // Return value -2 means the user complete function wants to
3795 // cancel the complete without an error.
3796 // Return value -3 does the same as -2 and leaves CTRL-X mode.
3797 if (col == -2)
3798 return FAIL;
3799 if (col == -3)
3800 {
3801 ctrl_x_mode = CTRL_X_NORMAL;
3802 edit_submode = NULL;
3803 if (!shortmess(SHM_COMPLETIONMENU))
3804 msg_clr_cmdline();
3805 return FAIL;
3806 }
3807
3808 // Reset extended parameters of completion, when start new
3809 // completion.
3810 compl_opt_refresh_always = FALSE;
3811 compl_opt_suppress_empty = FALSE;
3812
3813 if (col < 0)
3814 col = curs_col;
3815 compl_col = col;
3816 if (compl_col > curs_col)
3817 compl_col = curs_col;
3818
3819 // Setup variables for completion. Need to obtain "line" again,
3820 // it may have become invalid.
3821 line = ml_get(curwin->w_cursor.lnum);
3822 compl_length = curs_col - compl_col;
3823 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3824 if (compl_pattern == NULL)
3825#endif
3826 return FAIL;
3827 }
3828 else if (ctrl_x_mode == CTRL_X_SPELL)
3829 {
3830#ifdef FEAT_SPELL
3831 if (spell_bad_len > 0)
3832 compl_col = curs_col - spell_bad_len;
3833 else
3834 compl_col = spell_word_start(startcol);
3835 if (compl_col >= (colnr_T)startcol)
3836 {
3837 compl_length = 0;
3838 compl_col = curs_col;
3839 }
3840 else
3841 {
3842 spell_expand_check_cap(compl_col);
3843 compl_length = (int)curs_col - compl_col;
3844 }
3845 // Need to obtain "line" again, it may have become invalid.
3846 line = ml_get(curwin->w_cursor.lnum);
3847 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3848 if (compl_pattern == NULL)
3849#endif
3850 return FAIL;
3851 }
3852 else
3853 {
3854 internal_error("ins_complete()");
3855 return FAIL;
3856 }
3857
3858 if (compl_cont_status & CONT_ADDING)
3859 {
3860 edit_submode_pre = (char_u *)_(" Adding");
3861 if (ctrl_x_mode_line_or_eval())
3862 {
3863 // Insert a new line, keep indentation but ignore 'comments'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003864 char_u *old = curbuf->b_p_com;
3865
3866 curbuf->b_p_com = (char_u *)"";
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003867 compl_startpos.lnum = curwin->w_cursor.lnum;
3868 compl_startpos.col = compl_col;
3869 ins_eol('\r');
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003870 curbuf->b_p_com = old;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003871 compl_length = 0;
3872 compl_col = curwin->w_cursor.col;
3873 }
3874 }
3875 else
3876 {
3877 edit_submode_pre = NULL;
3878 compl_startpos.col = compl_col;
3879 }
3880
3881 if (compl_cont_status & CONT_LOCAL)
3882 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
3883 else
3884 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
3885
3886 // If any of the original typed text has been changed we need to fix
3887 // the redo buffer.
3888 ins_compl_fixRedoBufForLeader(NULL);
3889
3890 // Always add completion for the original text.
3891 vim_free(compl_orig_text);
3892 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003893 if (p_ic)
3894 flags |= CP_ICASE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003895 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003896 -1, NULL, NULL, 0, flags, FALSE) != OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003897 {
3898 VIM_CLEAR(compl_pattern);
3899 VIM_CLEAR(compl_orig_text);
3900 return FAIL;
3901 }
3902
3903 // showmode might reset the internal line pointers, so it must
3904 // be called before line = ml_get(), or when this address is no
3905 // longer needed. -- Acevedo.
3906 edit_submode_extra = (char_u *)_("-- Searching...");
3907 edit_submode_highl = HLF_COUNT;
3908 showmode();
3909 edit_submode_extra = NULL;
3910 out_flush();
3911 }
3912 else if (insert_match && stop_arrow() == FAIL)
3913 return FAIL;
3914
3915 compl_shown_match = compl_curr_match;
3916 compl_shows_dir = compl_direction;
3917
3918 // Find next match (and following matches).
3919 save_w_wrow = curwin->w_wrow;
3920 save_w_leftcol = curwin->w_leftcol;
3921 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
3922
3923 // may undisplay the popup menu
3924 ins_compl_upd_pum();
3925
3926 if (n > 1) // all matches have been found
3927 compl_matches = n;
3928 compl_curr_match = compl_shown_match;
3929 compl_direction = compl_shows_dir;
3930
3931 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
3932 // mode.
3933 if (got_int && !global_busy)
3934 {
3935 (void)vgetc();
3936 got_int = FALSE;
3937 }
3938
3939 // we found no match if the list has only the "compl_orig_text"-entry
3940 if (compl_first_match == compl_first_match->cp_next)
3941 {
3942 edit_submode_extra = (compl_cont_status & CONT_ADDING)
3943 && compl_length > 1
3944 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
3945 edit_submode_highl = HLF_E;
3946 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
3947 // because we couldn't expand anything at first place, but if we used
3948 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
3949 // (such as M in M'exico) if not tried already. -- Acevedo
3950 if ( compl_length > 1
3951 || (compl_cont_status & CONT_ADDING)
3952 || (ctrl_x_mode != CTRL_X_NORMAL
3953 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
3954 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
3955 compl_cont_status &= ~CONT_N_ADDS;
3956 }
3957
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003958 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003959 compl_cont_status |= CONT_S_IPOS;
3960 else
3961 compl_cont_status &= ~CONT_S_IPOS;
3962
3963 if (edit_submode_extra == NULL)
3964 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003965 if (compl_curr_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003966 {
3967 edit_submode_extra = (char_u *)_("Back at original");
3968 edit_submode_highl = HLF_W;
3969 }
3970 else if (compl_cont_status & CONT_S_IPOS)
3971 {
3972 edit_submode_extra = (char_u *)_("Word from other line");
3973 edit_submode_highl = HLF_COUNT;
3974 }
3975 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
3976 {
3977 edit_submode_extra = (char_u *)_("The only match");
3978 edit_submode_highl = HLF_COUNT;
3979 }
3980 else
3981 {
3982 // Update completion sequence number when needed.
3983 if (compl_curr_match->cp_number == -1)
3984 {
3985 int number = 0;
3986 compl_T *match;
3987
3988 if (compl_direction == FORWARD)
3989 {
3990 // search backwards for the first valid (!= -1) number.
3991 // This should normally succeed already at the first loop
3992 // cycle, so it's fast!
3993 for (match = compl_curr_match->cp_prev; match != NULL
3994 && match != compl_first_match;
3995 match = match->cp_prev)
3996 if (match->cp_number != -1)
3997 {
3998 number = match->cp_number;
3999 break;
4000 }
4001 if (match != NULL)
4002 // go up and assign all numbers which are not assigned
4003 // yet
4004 for (match = match->cp_next;
4005 match != NULL && match->cp_number == -1;
4006 match = match->cp_next)
4007 match->cp_number = ++number;
4008 }
4009 else // BACKWARD
4010 {
4011 // search forwards (upwards) for the first valid (!= -1)
4012 // number. This should normally succeed already at the
4013 // first loop cycle, so it's fast!
4014 for (match = compl_curr_match->cp_next; match != NULL
4015 && match != compl_first_match;
4016 match = match->cp_next)
4017 if (match->cp_number != -1)
4018 {
4019 number = match->cp_number;
4020 break;
4021 }
4022 if (match != NULL)
4023 // go down and assign all numbers which are not
4024 // assigned yet
4025 for (match = match->cp_prev; match
4026 && match->cp_number == -1;
4027 match = match->cp_prev)
4028 match->cp_number = ++number;
4029 }
4030 }
4031
4032 // The match should always have a sequence number now, this is
4033 // just a safety check.
4034 if (compl_curr_match->cp_number != -1)
4035 {
4036 // Space for 10 text chars. + 2x10-digit no.s = 31.
4037 // Translations may need more than twice that.
4038 static char_u match_ref[81];
4039
4040 if (compl_matches > 0)
4041 vim_snprintf((char *)match_ref, sizeof(match_ref),
4042 _("match %d of %d"),
4043 compl_curr_match->cp_number, compl_matches);
4044 else
4045 vim_snprintf((char *)match_ref, sizeof(match_ref),
4046 _("match %d"),
4047 compl_curr_match->cp_number);
4048 edit_submode_extra = match_ref;
4049 edit_submode_highl = HLF_R;
4050 if (dollar_vcol >= 0)
4051 curs_columns(FALSE);
4052 }
4053 }
4054 }
4055
4056 // Show a message about what (completion) mode we're in.
4057 if (!compl_opt_suppress_empty)
4058 {
4059 showmode();
4060 if (!shortmess(SHM_COMPLETIONMENU))
4061 {
4062 if (edit_submode_extra != NULL)
4063 {
4064 if (!p_smd)
4065 msg_attr((char *)edit_submode_extra,
4066 edit_submode_highl < HLF_COUNT
4067 ? HL_ATTR(edit_submode_highl) : 0);
4068 }
4069 else
4070 msg_clr_cmdline(); // necessary for "noshowmode"
4071 }
4072 }
4073
4074 // Show the popup menu, unless we got interrupted.
4075 if (enable_pum && !compl_interrupted)
4076 show_pum(save_w_wrow, save_w_leftcol);
4077
4078 compl_was_interrupted = compl_interrupted;
4079 compl_interrupted = FALSE;
4080
4081 return OK;
4082}
4083
4084 static void
4085show_pum(int prev_w_wrow, int prev_w_leftcol)
4086{
4087 // RedrawingDisabled may be set when invoked through complete().
4088 int n = RedrawingDisabled;
4089
4090 RedrawingDisabled = 0;
4091
4092 // If the cursor moved or the display scrolled we need to remove the pum
4093 // first.
4094 setcursor();
4095 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
4096 ins_compl_del_pum();
4097
4098 ins_compl_show_pum();
4099 setcursor();
4100 RedrawingDisabled = n;
4101}
4102
4103/*
4104 * Looks in the first "len" chars. of "src" for search-metachars.
4105 * If dest is not NULL the chars. are copied there quoting (with
4106 * a backslash) the metachars, and dest would be NUL terminated.
4107 * Returns the length (needed) of dest
4108 */
4109 static unsigned
4110quote_meta(char_u *dest, char_u *src, int len)
4111{
4112 unsigned m = (unsigned)len + 1; // one extra for the NUL
4113
4114 for ( ; --len >= 0; src++)
4115 {
4116 switch (*src)
4117 {
4118 case '.':
4119 case '*':
4120 case '[':
4121 if (ctrl_x_mode == CTRL_X_DICTIONARY
4122 || ctrl_x_mode == CTRL_X_THESAURUS)
4123 break;
4124 // FALLTHROUGH
4125 case '~':
4126 if (!p_magic) // quote these only if magic is set
4127 break;
4128 // FALLTHROUGH
4129 case '\\':
4130 if (ctrl_x_mode == CTRL_X_DICTIONARY
4131 || ctrl_x_mode == CTRL_X_THESAURUS)
4132 break;
4133 // FALLTHROUGH
4134 case '^': // currently it's not needed.
4135 case '$':
4136 m++;
4137 if (dest != NULL)
4138 *dest++ = '\\';
4139 break;
4140 }
4141 if (dest != NULL)
4142 *dest++ = *src;
4143 // Copy remaining bytes of a multibyte character.
4144 if (has_mbyte)
4145 {
4146 int i, mb_len;
4147
4148 mb_len = (*mb_ptr2len)(src) - 1;
4149 if (mb_len > 0 && len >= mb_len)
4150 for (i = 0; i < mb_len; ++i)
4151 {
4152 --len;
4153 ++src;
4154 if (dest != NULL)
4155 *dest++ = *src;
4156 }
4157 }
4158 }
4159 if (dest != NULL)
4160 *dest = NUL;
4161
4162 return m;
4163}
4164
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004165#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004166 void
4167free_insexpand_stuff(void)
4168{
4169 VIM_CLEAR(compl_orig_text);
4170}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004171#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004172
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004173#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004174/*
4175 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
4176 * spelled word, if there is one.
4177 */
4178 static void
4179spell_back_to_badword(void)
4180{
4181 pos_T tpos = curwin->w_cursor;
4182
4183 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
4184 if (curwin->w_cursor.col != tpos.col)
4185 start_arrow(&tpos);
4186}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004187#endif