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