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