blob: 8d76c686f5ff1304ae0458e661962333d515786a [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
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100124static char e_compldel[] = N_("E840: Completion function deleted text");
125# endif
126
127/*
128 * All the current matches are stored in a list.
129 * "compl_first_match" points to the start of the list.
130 * "compl_curr_match" points to the currently selected entry.
131 * "compl_shown_match" is different from compl_curr_match during
132 * ins_compl_get_exp().
133 */
134static compl_T *compl_first_match = NULL;
135static compl_T *compl_curr_match = NULL;
136static compl_T *compl_shown_match = NULL;
137static compl_T *compl_old_match = NULL;
138
139// After using a cursor key <Enter> selects a match in the popup menu,
140// otherwise it inserts a line break.
141static int compl_enter_selects = FALSE;
142
143// When "compl_leader" is not NULL only matches that start with this string
144// are used.
145static char_u *compl_leader = NULL;
146
147static int compl_get_longest = FALSE; // put longest common string
148 // in compl_leader
149
150static int compl_no_insert = FALSE; // FALSE: select & insert
151 // TRUE: noinsert
152static int compl_no_select = FALSE; // FALSE: select & insert
153 // TRUE: noselect
154
155// Selected one of the matches. When FALSE the match was edited or using the
156// longest common string.
157static int compl_used_match;
158
159// didn't finish finding completions.
160static int compl_was_interrupted = FALSE;
161
162// Set when character typed while looking for matches and it means we should
163// stop looking for matches.
164static int compl_interrupted = FALSE;
165
166static int compl_restarting = FALSE; // don't insert match
167
168// When the first completion is done "compl_started" is set. When it's
169// FALSE the word to be completed must be located.
170static int compl_started = FALSE;
171
172// Which Ctrl-X mode are we in?
173static int ctrl_x_mode = CTRL_X_NORMAL;
174
175static int compl_matches = 0;
176static char_u *compl_pattern = NULL;
177static int compl_direction = FORWARD;
178static int compl_shows_dir = FORWARD;
179static int compl_pending = 0; // > 1 for postponed CTRL-N
180static pos_T compl_startpos;
181static colnr_T compl_col = 0; // column where the text starts
182 // that is being completed
183static char_u *compl_orig_text = NULL; // text as it was before
184 // completion started
185static int compl_cont_mode = 0;
186static expand_T compl_xp;
187
188static int compl_opt_refresh_always = FALSE;
189static int compl_opt_suppress_empty = FALSE;
190
Bram Moolenaar08928322020-01-04 14:32:48 +0100191static 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 +0100192static void ins_compl_longest_match(compl_T *match);
193static void ins_compl_del_pum(void);
194static void ins_compl_files(int count, char_u **files, int thesaurus, int flags, regmatch_T *regmatch, char_u *buf, int *dir);
195static char_u *find_line_end(char_u *ptr);
196static void ins_compl_free(void);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100197static int ins_compl_need_restart(void);
198static void ins_compl_new_leader(void);
199static int ins_compl_len(void);
200static void ins_compl_restart(void);
201static void ins_compl_set_original_text(char_u *str);
202static void ins_compl_fixRedoBufForLeader(char_u *ptr_arg);
203# if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
204static void ins_compl_add_list(list_T *list);
205static void ins_compl_add_dict(dict_T *dict);
206# endif
207static int ins_compl_key2dir(int c);
208static int ins_compl_pum_key(int c);
209static int ins_compl_key2count(int c);
210static void show_pum(int prev_w_wrow, int prev_w_leftcol);
211static unsigned quote_meta(char_u *dest, char_u *str, int len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100212
213#ifdef FEAT_SPELL
214static void spell_back_to_badword(void);
215static int spell_bad_len = 0; // length of located bad word
216#endif
217
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100218/*
219 * CTRL-X pressed in Insert mode.
220 */
221 void
222ins_ctrl_x(void)
223{
224 // CTRL-X after CTRL-X CTRL-V doesn't do anything, so that CTRL-X
225 // CTRL-V works like CTRL-N
226 if (ctrl_x_mode != CTRL_X_CMDLINE)
227 {
228 // if the next ^X<> won't ADD nothing, then reset
229 // compl_cont_status
230 if (compl_cont_status & CONT_N_ADDS)
231 compl_cont_status |= CONT_INTRPT;
232 else
233 compl_cont_status = 0;
234 // We're not sure which CTRL-X mode it will be yet
235 ctrl_x_mode = CTRL_X_NOT_DEFINED_YET;
236 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
237 edit_submode_pre = NULL;
238 showmode();
239 }
240}
241
242/*
243 * Functions to check the current CTRL-X mode.
244 */
245int ctrl_x_mode_none(void) { return ctrl_x_mode == 0; }
246int ctrl_x_mode_normal(void) { return ctrl_x_mode == CTRL_X_NORMAL; }
247int ctrl_x_mode_scroll(void) { return ctrl_x_mode == CTRL_X_SCROLL; }
248int ctrl_x_mode_whole_line(void) { return ctrl_x_mode == CTRL_X_WHOLE_LINE; }
249int ctrl_x_mode_files(void) { return ctrl_x_mode == CTRL_X_FILES; }
250int ctrl_x_mode_tags(void) { return ctrl_x_mode == CTRL_X_TAGS; }
251int ctrl_x_mode_path_patterns(void) {
252 return ctrl_x_mode == CTRL_X_PATH_PATTERNS; }
253int ctrl_x_mode_path_defines(void) {
254 return ctrl_x_mode == CTRL_X_PATH_DEFINES; }
255int ctrl_x_mode_dictionary(void) { return ctrl_x_mode == CTRL_X_DICTIONARY; }
256int ctrl_x_mode_thesaurus(void) { return ctrl_x_mode == CTRL_X_THESAURUS; }
257int ctrl_x_mode_cmdline(void) { return ctrl_x_mode == CTRL_X_CMDLINE; }
258int ctrl_x_mode_function(void) { return ctrl_x_mode == CTRL_X_FUNCTION; }
259int ctrl_x_mode_omni(void) { return ctrl_x_mode == CTRL_X_OMNI; }
260int ctrl_x_mode_spell(void) { return ctrl_x_mode == CTRL_X_SPELL; }
261int ctrl_x_mode_line_or_eval(void) {
262 return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL; }
263
264/*
265 * Whether other than default completion has been selected.
266 */
267 int
268ctrl_x_mode_not_default(void)
269{
270 return ctrl_x_mode != CTRL_X_NORMAL;
271}
272
273/*
274 * Whether CTRL-X was typed without a following character.
275 */
276 int
277ctrl_x_mode_not_defined_yet(void)
278{
279 return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET;
280}
281
282/*
283 * Return TRUE if the 'dict' or 'tsr' option can be used.
284 */
285 int
286has_compl_option(int dict_opt)
287{
288 if (dict_opt ? (*curbuf->b_p_dict == NUL && *p_dict == NUL
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200289#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100290 && !curwin->w_p_spell
Bram Moolenaare2c453d2019-08-21 14:37:09 +0200291#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100292 )
293 : (*curbuf->b_p_tsr == NUL && *p_tsr == NUL))
294 {
295 ctrl_x_mode = CTRL_X_NORMAL;
296 edit_submode = NULL;
297 msg_attr(dict_opt ? _("'dictionary' option is empty")
298 : _("'thesaurus' option is empty"),
299 HL_ATTR(HLF_E));
Bram Moolenaar28ee8922020-10-28 20:20:00 +0100300 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100301 {
302 vim_beep(BO_COMPL);
303 setcursor();
304 out_flush();
305#ifdef FEAT_EVAL
306 if (!get_vim_var_nr(VV_TESTING))
307#endif
Bram Moolenaareda1da02019-11-17 17:06:33 +0100308 ui_delay(2004L, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100309 }
310 return FALSE;
311 }
312 return TRUE;
313}
314
315/*
316 * Is the character 'c' a valid key to go to or keep us in CTRL-X mode?
317 * This depends on the current mode.
318 */
319 int
320vim_is_ctrl_x_key(int c)
321{
322 // Always allow ^R - let its results then be checked
323 if (c == Ctrl_R)
324 return TRUE;
325
326 // Accept <PageUp> and <PageDown> if the popup menu is visible.
327 if (ins_compl_pum_key(c))
328 return TRUE;
329
330 switch (ctrl_x_mode)
331 {
332 case 0: // Not in any CTRL-X mode
333 return (c == Ctrl_N || c == Ctrl_P || c == Ctrl_X);
334 case CTRL_X_NOT_DEFINED_YET:
335 return ( c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E
336 || c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB
337 || c == Ctrl_I || c == Ctrl_D || c == Ctrl_P
338 || c == Ctrl_N || c == Ctrl_T || c == Ctrl_V
339 || c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O
340 || c == Ctrl_S || c == Ctrl_K || c == 's');
341 case CTRL_X_SCROLL:
342 return (c == Ctrl_Y || c == Ctrl_E);
343 case CTRL_X_WHOLE_LINE:
344 return (c == Ctrl_L || c == Ctrl_P || c == Ctrl_N);
345 case CTRL_X_FILES:
346 return (c == Ctrl_F || c == Ctrl_P || c == Ctrl_N);
347 case CTRL_X_DICTIONARY:
348 return (c == Ctrl_K || c == Ctrl_P || c == Ctrl_N);
349 case CTRL_X_THESAURUS:
350 return (c == Ctrl_T || c == Ctrl_P || c == Ctrl_N);
351 case CTRL_X_TAGS:
352 return (c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N);
353#ifdef FEAT_FIND_ID
354 case CTRL_X_PATH_PATTERNS:
355 return (c == Ctrl_P || c == Ctrl_N);
356 case CTRL_X_PATH_DEFINES:
357 return (c == Ctrl_D || c == Ctrl_P || c == Ctrl_N);
358#endif
359 case CTRL_X_CMDLINE:
360 return (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N
361 || c == Ctrl_X);
362#ifdef FEAT_COMPL_FUNC
363 case CTRL_X_FUNCTION:
364 return (c == Ctrl_U || c == Ctrl_P || c == Ctrl_N);
365 case CTRL_X_OMNI:
366 return (c == Ctrl_O || c == Ctrl_P || c == Ctrl_N);
367#endif
368 case CTRL_X_SPELL:
369 return (c == Ctrl_S || c == Ctrl_P || c == Ctrl_N);
370 case CTRL_X_EVAL:
371 return (c == Ctrl_P || c == Ctrl_N);
372 }
373 internal_error("vim_is_ctrl_x_key()");
374 return FALSE;
375}
376
377/*
378 * Return TRUE when character "c" is part of the item currently being
379 * completed. Used to decide whether to abandon complete mode when the menu
380 * is visible.
381 */
382 int
383ins_compl_accept_char(int c)
384{
385 if (ctrl_x_mode & CTRL_X_WANT_IDENT)
386 // When expanding an identifier only accept identifier chars.
387 return vim_isIDc(c);
388
389 switch (ctrl_x_mode)
390 {
391 case CTRL_X_FILES:
392 // When expanding file name only accept file name chars. But not
393 // path separators, so that "proto/<Tab>" expands files in
394 // "proto", not "proto/" as a whole
395 return vim_isfilec(c) && !vim_ispathsep(c);
396
397 case CTRL_X_CMDLINE:
398 case CTRL_X_OMNI:
399 // Command line and Omni completion can work with just about any
400 // printable character, but do stop at white space.
401 return vim_isprintc(c) && !VIM_ISWHITE(c);
402
403 case CTRL_X_WHOLE_LINE:
404 // For while line completion a space can be part of the line.
405 return vim_isprintc(c);
406 }
407 return vim_iswordc(c);
408}
409
410/*
411 * This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the
412 * case of the originally typed text is used, and the case of the completed
413 * text is inferred, ie this tries to work out what case you probably wanted
414 * the rest of the word to be in -- webb
415 */
416 int
417ins_compl_add_infercase(
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200418 char_u *str_arg,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100419 int len,
420 int icase,
421 char_u *fname,
422 int dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200423 int cont_s_ipos) // next ^X<> will set initial_pos
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100424{
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200425 char_u *str = str_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100426 char_u *p;
427 int i, c;
428 int actual_len; // Take multi-byte characters
429 int actual_compl_length; // into account.
430 int min_len;
431 int *wca; // Wide character array.
432 int has_lower = FALSE;
433 int was_letter = FALSE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200434 int flags = 0;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100435
436 if (p_ic && curbuf->b_p_inf && len > 0)
437 {
438 // Infer case of completed part.
439
440 // Find actual length of completion.
441 if (has_mbyte)
442 {
443 p = str;
444 actual_len = 0;
445 while (*p != NUL)
446 {
447 MB_PTR_ADV(p);
448 ++actual_len;
449 }
450 }
451 else
452 actual_len = len;
453
454 // Find actual length of original text.
455 if (has_mbyte)
456 {
457 p = compl_orig_text;
458 actual_compl_length = 0;
459 while (*p != NUL)
460 {
461 MB_PTR_ADV(p);
462 ++actual_compl_length;
463 }
464 }
465 else
466 actual_compl_length = compl_length;
467
468 // "actual_len" may be smaller than "actual_compl_length" when using
469 // thesaurus, only use the minimum when comparing.
470 min_len = actual_len < actual_compl_length
471 ? actual_len : actual_compl_length;
472
473 // Allocate wide character array for the completion and fill it.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200474 wca = ALLOC_MULT(int, actual_len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100475 if (wca != NULL)
476 {
477 p = str;
478 for (i = 0; i < actual_len; ++i)
479 if (has_mbyte)
480 wca[i] = mb_ptr2char_adv(&p);
481 else
482 wca[i] = *(p++);
483
484 // Rule 1: Were any chars converted to lower?
485 p = compl_orig_text;
486 for (i = 0; i < min_len; ++i)
487 {
488 if (has_mbyte)
489 c = mb_ptr2char_adv(&p);
490 else
491 c = *(p++);
492 if (MB_ISLOWER(c))
493 {
494 has_lower = TRUE;
495 if (MB_ISUPPER(wca[i]))
496 {
497 // Rule 1 is satisfied.
498 for (i = actual_compl_length; i < actual_len; ++i)
499 wca[i] = MB_TOLOWER(wca[i]);
500 break;
501 }
502 }
503 }
504
505 // Rule 2: No lower case, 2nd consecutive letter converted to
506 // upper case.
507 if (!has_lower)
508 {
509 p = compl_orig_text;
510 for (i = 0; i < min_len; ++i)
511 {
512 if (has_mbyte)
513 c = mb_ptr2char_adv(&p);
514 else
515 c = *(p++);
516 if (was_letter && MB_ISUPPER(c) && MB_ISLOWER(wca[i]))
517 {
518 // Rule 2 is satisfied.
519 for (i = actual_compl_length; i < actual_len; ++i)
520 wca[i] = MB_TOUPPER(wca[i]);
521 break;
522 }
523 was_letter = MB_ISLOWER(c) || MB_ISUPPER(c);
524 }
525 }
526
527 // Copy the original case of the part we typed.
528 p = compl_orig_text;
529 for (i = 0; i < min_len; ++i)
530 {
531 if (has_mbyte)
532 c = mb_ptr2char_adv(&p);
533 else
534 c = *(p++);
535 if (MB_ISLOWER(c))
536 wca[i] = MB_TOLOWER(wca[i]);
537 else if (MB_ISUPPER(c))
538 wca[i] = MB_TOUPPER(wca[i]);
539 }
540
541 // Generate encoding specific output from wide character array.
542 // Multi-byte characters can occupy up to five bytes more than
543 // ASCII characters, and we also need one byte for NUL, so stay
544 // six bytes away from the edge of IObuff.
545 p = IObuff;
546 i = 0;
547 while (i < actual_len && (p - IObuff + 6) < IOSIZE)
548 if (has_mbyte)
549 p += (*mb_char2bytes)(wca[i++], p);
550 else
551 *(p++) = wca[i++];
552 *p = NUL;
553
554 vim_free(wca);
555 }
556
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200557 str = IObuff;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100558 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200559 if (cont_s_ipos)
560 flags |= CP_CONT_S_IPOS;
561 if (icase)
562 flags |= CP_ICASE;
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200563
Bram Moolenaar08928322020-01-04 14:32:48 +0100564 return ins_compl_add(str, len, fname, NULL, NULL, dir, flags, FALSE);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100565}
566
567/*
568 * Add a match to the list of matches.
569 * If the given string is already in the list of completions, then return
570 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
571 * maybe because alloc() returns NULL, then FAIL is returned.
572 */
573 static int
574ins_compl_add(
575 char_u *str,
576 int len,
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100577 char_u *fname,
Bram Moolenaar8a7d6542020-01-26 15:56:19 +0100578 char_u **cptext, // extra text for popup menu or NULL
579 typval_T *user_data UNUSED, // "user_data" entry or NULL
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100580 int cdir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200581 int flags_arg,
Bram Moolenaar08928322020-01-04 14:32:48 +0100582 int adup) // accept duplicate match
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100583{
584 compl_T *match;
585 int dir = (cdir == 0 ? compl_direction : cdir);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200586 int flags = flags_arg;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100587
588 ui_breakcheck();
589 if (got_int)
590 return FAIL;
591 if (len < 0)
592 len = (int)STRLEN(str);
593
594 // If the same match is already present, don't add it.
595 if (compl_first_match != NULL && !adup)
596 {
597 match = compl_first_match;
598 do
599 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200600 if ( !(match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100601 && STRNCMP(match->cp_str, str, len) == 0
602 && match->cp_str[len] == NUL)
603 return NOTDONE;
604 match = match->cp_next;
605 } while (match != NULL && match != compl_first_match);
606 }
607
608 // Remove any popup menu before changing the list of matches.
609 ins_compl_del_pum();
610
611 // Allocate a new match structure.
612 // Copy the values to the new match structure.
Bram Moolenaarc799fe22019-05-28 23:08:19 +0200613 match = ALLOC_CLEAR_ONE(compl_T);
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100614 if (match == NULL)
615 return FAIL;
616 match->cp_number = -1;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200617 if (flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100618 match->cp_number = 0;
619 if ((match->cp_str = vim_strnsave(str, len)) == NULL)
620 {
621 vim_free(match);
622 return FAIL;
623 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100624
625 // match-fname is:
626 // - compl_curr_match->cp_fname if it is a string equal to fname.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200627 // - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100628 // - NULL otherwise. --Acevedo
629 if (fname != NULL
630 && compl_curr_match != NULL
631 && compl_curr_match->cp_fname != NULL
632 && STRCMP(fname, compl_curr_match->cp_fname) == 0)
633 match->cp_fname = compl_curr_match->cp_fname;
634 else if (fname != NULL)
635 {
636 match->cp_fname = vim_strsave(fname);
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200637 flags |= CP_FREE_FNAME;
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100638 }
639 else
640 match->cp_fname = NULL;
641 match->cp_flags = flags;
642
643 if (cptext != NULL)
644 {
645 int i;
646
647 for (i = 0; i < CPT_COUNT; ++i)
648 if (cptext[i] != NULL && *cptext[i] != NUL)
649 match->cp_text[i] = vim_strsave(cptext[i]);
650 }
Bram Moolenaarab782c52020-01-04 19:00:11 +0100651#ifdef FEAT_EVAL
Bram Moolenaar08928322020-01-04 14:32:48 +0100652 if (user_data != NULL)
653 match->cp_user_data = *user_data;
Bram Moolenaarab782c52020-01-04 19:00:11 +0100654#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100655
656 // Link the new match structure in the list of matches.
657 if (compl_first_match == NULL)
658 match->cp_next = match->cp_prev = NULL;
659 else if (dir == FORWARD)
660 {
661 match->cp_next = compl_curr_match->cp_next;
662 match->cp_prev = compl_curr_match;
663 }
664 else // BACKWARD
665 {
666 match->cp_next = compl_curr_match;
667 match->cp_prev = compl_curr_match->cp_prev;
668 }
669 if (match->cp_next)
670 match->cp_next->cp_prev = match;
671 if (match->cp_prev)
672 match->cp_prev->cp_next = match;
673 else // if there's nothing before, it is the first match
674 compl_first_match = match;
675 compl_curr_match = match;
676
677 // Find the longest common string if still doing that.
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200678 if (compl_get_longest && (flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100679 ins_compl_longest_match(match);
680
681 return OK;
682}
683
684/*
685 * Return TRUE if "str[len]" matches with match->cp_str, considering
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200686 * match->cp_flags.
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100687 */
688 static int
689ins_compl_equal(compl_T *match, char_u *str, int len)
690{
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200691 if (match->cp_flags & CP_EQUAL)
Bram Moolenaar73655cf2019-04-06 13:45:55 +0200692 return TRUE;
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200693 if (match->cp_flags & CP_ICASE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100694 return STRNICMP(match->cp_str, str, (size_t)len) == 0;
695 return STRNCMP(match->cp_str, str, (size_t)len) == 0;
696}
697
698/*
699 * Reduce the longest common string for match "match".
700 */
701 static void
702ins_compl_longest_match(compl_T *match)
703{
704 char_u *p, *s;
705 int c1, c2;
706 int had_match;
707
708 if (compl_leader == NULL)
709 {
710 // First match, use it as a whole.
711 compl_leader = vim_strsave(match->cp_str);
712 if (compl_leader != NULL)
713 {
714 had_match = (curwin->w_cursor.col > compl_col);
715 ins_compl_delete();
716 ins_bytes(compl_leader + ins_compl_len());
717 ins_redraw(FALSE);
718
719 // When the match isn't there (to avoid matching itself) remove it
720 // again after redrawing.
721 if (!had_match)
722 ins_compl_delete();
723 compl_used_match = FALSE;
724 }
725 }
726 else
727 {
728 // Reduce the text if this match differs from compl_leader.
729 p = compl_leader;
730 s = match->cp_str;
731 while (*p != NUL)
732 {
733 if (has_mbyte)
734 {
735 c1 = mb_ptr2char(p);
736 c2 = mb_ptr2char(s);
737 }
738 else
739 {
740 c1 = *p;
741 c2 = *s;
742 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200743 if ((match->cp_flags & CP_ICASE)
744 ? (MB_TOLOWER(c1) != MB_TOLOWER(c2)) : (c1 != c2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100745 break;
746 if (has_mbyte)
747 {
748 MB_PTR_ADV(p);
749 MB_PTR_ADV(s);
750 }
751 else
752 {
753 ++p;
754 ++s;
755 }
756 }
757
758 if (*p != NUL)
759 {
760 // Leader was shortened, need to change the inserted text.
761 *p = NUL;
762 had_match = (curwin->w_cursor.col > compl_col);
763 ins_compl_delete();
764 ins_bytes(compl_leader + ins_compl_len());
765 ins_redraw(FALSE);
766
767 // When the match isn't there (to avoid matching itself) remove it
768 // again after redrawing.
769 if (!had_match)
770 ins_compl_delete();
771 }
772
773 compl_used_match = FALSE;
774 }
775}
776
777/*
778 * Add an array of matches to the list of matches.
779 * Frees matches[].
780 */
781 static void
782ins_compl_add_matches(
783 int num_matches,
784 char_u **matches,
785 int icase)
786{
787 int i;
788 int add_r = OK;
789 int dir = compl_direction;
790
791 for (i = 0; i < num_matches && add_r != FAIL; i++)
Bram Moolenaar08928322020-01-04 14:32:48 +0100792 if ((add_r = ins_compl_add(matches[i], -1, NULL, NULL, NULL, dir,
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200793 icase ? CP_ICASE : 0, FALSE)) == OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100794 // if dir was BACKWARD then honor it just once
795 dir = FORWARD;
796 FreeWild(num_matches, matches);
797}
798
799/*
800 * Make the completion list cyclic.
801 * Return the number of matches (excluding the original).
802 */
803 static int
804ins_compl_make_cyclic(void)
805{
806 compl_T *match;
807 int count = 0;
808
809 if (compl_first_match != NULL)
810 {
811 // Find the end of the list.
812 match = compl_first_match;
813 // there's always an entry for the compl_orig_text, it doesn't count.
814 while (match->cp_next != NULL && match->cp_next != compl_first_match)
815 {
816 match = match->cp_next;
817 ++count;
818 }
819 match->cp_next = compl_first_match;
820 compl_first_match->cp_prev = match;
821 }
822 return count;
823}
824
825/*
826 * Return whether there currently is a shown match.
827 */
828 int
829ins_compl_has_shown_match(void)
830{
831 return compl_shown_match == NULL
832 || compl_shown_match != compl_shown_match->cp_next;
833}
834
835/*
836 * Return whether the shown match is long enough.
837 */
838 int
839ins_compl_long_shown_match(void)
840{
841 return (int)STRLEN(compl_shown_match->cp_str)
842 > curwin->w_cursor.col - compl_col;
843}
844
845/*
846 * Set variables that store noselect and noinsert behavior from the
847 * 'completeopt' value.
848 */
849 void
850completeopt_was_set(void)
851{
852 compl_no_insert = FALSE;
853 compl_no_select = FALSE;
854 if (strstr((char *)p_cot, "noselect") != NULL)
855 compl_no_select = TRUE;
856 if (strstr((char *)p_cot, "noinsert") != NULL)
857 compl_no_insert = TRUE;
858}
859
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100860
861// "compl_match_array" points the currently displayed list of entries in the
862// popup menu. It is NULL when there is no popup menu.
863static pumitem_T *compl_match_array = NULL;
864static int compl_match_arraysize;
865
866/*
867 * Update the screen and when there is any scrolling remove the popup menu.
868 */
869 static void
870ins_compl_upd_pum(void)
871{
872 int h;
873
874 if (compl_match_array != NULL)
875 {
876 h = curwin->w_cline_height;
877 // Update the screen later, before drawing the popup menu over it.
878 pum_call_update_screen();
879 if (h != curwin->w_cline_height)
880 ins_compl_del_pum();
881 }
882}
883
884/*
885 * Remove any popup menu.
886 */
887 static void
888ins_compl_del_pum(void)
889{
890 if (compl_match_array != NULL)
891 {
892 pum_undisplay();
893 VIM_CLEAR(compl_match_array);
894 }
895}
896
897/*
898 * Return TRUE if the popup menu should be displayed.
899 */
900 int
901pum_wanted(void)
902{
903 // 'completeopt' must contain "menu" or "menuone"
904 if (vim_strchr(p_cot, 'm') == NULL)
905 return FALSE;
906
907 // The display looks bad on a B&W display.
908 if (t_colors < 8
909#ifdef FEAT_GUI
910 && !gui.in_use
911#endif
912 )
913 return FALSE;
914 return TRUE;
915}
916
917/*
918 * Return TRUE if there are two or more matches to be shown in the popup menu.
919 * One if 'completopt' contains "menuone".
920 */
921 static int
922pum_enough_matches(void)
923{
924 compl_T *compl;
925 int i;
926
927 // Don't display the popup menu if there are no matches or there is only
928 // one (ignoring the original text).
929 compl = compl_first_match;
930 i = 0;
931 do
932 {
933 if (compl == NULL
Bram Moolenaard9eefe32019-04-06 14:22:21 +0200934 || ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0 && ++i == 2))
Bram Moolenaar7591bb32019-03-30 13:53:47 +0100935 break;
936 compl = compl->cp_next;
937 } while (compl != compl_first_match);
938
939 if (strstr((char *)p_cot, "menuone") != NULL)
940 return (i >= 1);
941 return (i >= 2);
942}
943
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200944#ifdef FEAT_EVAL
945/*
946 * Allocate Dict for the completed item.
947 * { word, abbr, menu, kind, info }
948 */
949 static dict_T *
950ins_compl_dict_alloc(compl_T *match)
951{
952 dict_T *dict = dict_alloc_lock(VAR_FIXED);
953
954 if (dict != NULL)
955 {
956 dict_add_string(dict, "word", match->cp_str);
957 dict_add_string(dict, "abbr", match->cp_text[CPT_ABBR]);
958 dict_add_string(dict, "menu", match->cp_text[CPT_MENU]);
959 dict_add_string(dict, "kind", match->cp_text[CPT_KIND]);
960 dict_add_string(dict, "info", match->cp_text[CPT_INFO]);
Bram Moolenaar08928322020-01-04 14:32:48 +0100961 if (match->cp_user_data.v_type == VAR_UNKNOWN)
962 dict_add_string(dict, "user_data", (char_u *)"");
963 else
964 dict_add_tv(dict, "user_data", &match->cp_user_data);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200965 }
966 return dict;
967}
968
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200969 static void
970trigger_complete_changed_event(int cur)
971{
972 dict_T *v_event;
973 dict_T *item;
974 static int recursive = FALSE;
975
976 if (recursive)
977 return;
978
979 v_event = get_vim_var_dict(VV_EVENT);
980 if (cur < 0)
981 item = dict_alloc();
982 else
983 item = ins_compl_dict_alloc(compl_curr_match);
984 if (item == NULL)
985 return;
986 dict_add_dict(v_event, "completed_item", item);
987 pum_set_event_info(v_event);
988 dict_set_items_ro(v_event);
989
990 recursive = TRUE;
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +0200991 textwinlock++;
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200992 apply_autocmds(EVENT_COMPLETECHANGED, NULL, NULL, FALSE, curbuf);
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +0200993 textwinlock--;
Bram Moolenaard7f246c2019-04-08 18:15:41 +0200994 recursive = FALSE;
995
996 dict_free_contents(v_event);
997 hash_init(&v_event->dv_hashtab);
998}
Bram Moolenaar9cb698d2019-08-21 15:30:45 +0200999#endif
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001000
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001001/*
1002 * Show the popup menu for the list of matches.
1003 * Also adjusts "compl_shown_match" to an entry that is actually displayed.
1004 */
1005 void
1006ins_compl_show_pum(void)
1007{
1008 compl_T *compl;
1009 compl_T *shown_compl = NULL;
1010 int did_find_shown_match = FALSE;
1011 int shown_match_ok = FALSE;
1012 int i;
1013 int cur = -1;
1014 colnr_T col;
1015 int lead_len = 0;
1016
1017 if (!pum_wanted() || !pum_enough_matches())
1018 return;
1019
1020#if defined(FEAT_EVAL)
1021 // Dirty hard-coded hack: remove any matchparen highlighting.
Bram Moolenaar179eb562020-12-27 18:03:22 +01001022 do_cmdline_cmd((char_u *)"if exists('g:loaded_matchparen')|:3match none|endif");
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001023#endif
1024
1025 // Update the screen later, before drawing the popup menu over it.
1026 pum_call_update_screen();
1027
1028 if (compl_match_array == NULL)
1029 {
1030 // Need to build the popup menu list.
1031 compl_match_arraysize = 0;
1032 compl = compl_first_match;
1033 if (compl_leader != NULL)
1034 lead_len = (int)STRLEN(compl_leader);
1035 do
1036 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001037 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001038 && (compl_leader == NULL
1039 || ins_compl_equal(compl, compl_leader, lead_len)))
1040 ++compl_match_arraysize;
1041 compl = compl->cp_next;
1042 } while (compl != NULL && compl != compl_first_match);
1043 if (compl_match_arraysize == 0)
1044 return;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02001045 compl_match_array = ALLOC_CLEAR_MULT(pumitem_T, compl_match_arraysize);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001046 if (compl_match_array != NULL)
1047 {
1048 // If the current match is the original text don't find the first
1049 // match after it, don't highlight anything.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001050 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001051 shown_match_ok = TRUE;
1052
1053 i = 0;
1054 compl = compl_first_match;
1055 do
1056 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001057 if ((compl->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001058 && (compl_leader == NULL
1059 || ins_compl_equal(compl, compl_leader, lead_len)))
1060 {
1061 if (!shown_match_ok)
1062 {
1063 if (compl == compl_shown_match || did_find_shown_match)
1064 {
1065 // This item is the shown match or this is the
1066 // first displayed item after the shown match.
1067 compl_shown_match = compl;
1068 did_find_shown_match = TRUE;
1069 shown_match_ok = TRUE;
1070 }
1071 else
1072 // Remember this displayed match for when the
1073 // shown match is just below it.
1074 shown_compl = compl;
1075 cur = i;
1076 }
1077
1078 if (compl->cp_text[CPT_ABBR] != NULL)
1079 compl_match_array[i].pum_text =
1080 compl->cp_text[CPT_ABBR];
1081 else
1082 compl_match_array[i].pum_text = compl->cp_str;
1083 compl_match_array[i].pum_kind = compl->cp_text[CPT_KIND];
1084 compl_match_array[i].pum_info = compl->cp_text[CPT_INFO];
1085 if (compl->cp_text[CPT_MENU] != NULL)
1086 compl_match_array[i++].pum_extra =
1087 compl->cp_text[CPT_MENU];
1088 else
1089 compl_match_array[i++].pum_extra = compl->cp_fname;
1090 }
1091
1092 if (compl == compl_shown_match)
1093 {
1094 did_find_shown_match = TRUE;
1095
1096 // When the original text is the shown match don't set
1097 // compl_shown_match.
Bram Moolenaard9eefe32019-04-06 14:22:21 +02001098 if (compl->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001099 shown_match_ok = TRUE;
1100
1101 if (!shown_match_ok && shown_compl != NULL)
1102 {
1103 // The shown match isn't displayed, set it to the
1104 // previously displayed match.
1105 compl_shown_match = shown_compl;
1106 shown_match_ok = TRUE;
1107 }
1108 }
1109 compl = compl->cp_next;
1110 } while (compl != NULL && compl != compl_first_match);
1111
1112 if (!shown_match_ok) // no displayed match at all
1113 cur = -1;
1114 }
1115 }
1116 else
1117 {
1118 // popup menu already exists, only need to find the current item.
1119 for (i = 0; i < compl_match_arraysize; ++i)
1120 if (compl_match_array[i].pum_text == compl_shown_match->cp_str
1121 || compl_match_array[i].pum_text
1122 == compl_shown_match->cp_text[CPT_ABBR])
1123 {
1124 cur = i;
1125 break;
1126 }
1127 }
1128
1129 if (compl_match_array != NULL)
1130 {
1131 // In Replace mode when a $ is displayed at the end of the line only
1132 // part of the screen would be updated. We do need to redraw here.
1133 dollar_vcol = -1;
1134
1135 // Compute the screen column of the start of the completed text.
1136 // Use the cursor to get all wrapping and other settings right.
1137 col = curwin->w_cursor.col;
1138 curwin->w_cursor.col = compl_col;
1139 pum_display(compl_match_array, compl_match_arraysize, cur);
1140 curwin->w_cursor.col = col;
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001141
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001142#ifdef FEAT_EVAL
Bram Moolenaard7f246c2019-04-08 18:15:41 +02001143 if (has_completechanged())
1144 trigger_complete_changed_event(cur);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02001145#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001146 }
1147}
1148
1149#define DICT_FIRST (1) // use just first element in "dict"
1150#define DICT_EXACT (2) // "dict" is the exact name of a file
1151
1152/*
1153 * Add any identifiers that match the given pattern in the list of dictionary
1154 * files "dict_start" to the list of completions.
1155 */
1156 static void
1157ins_compl_dictionaries(
1158 char_u *dict_start,
1159 char_u *pat,
1160 int flags, // DICT_FIRST and/or DICT_EXACT
1161 int thesaurus) // Thesaurus completion
1162{
1163 char_u *dict = dict_start;
1164 char_u *ptr;
1165 char_u *buf;
1166 regmatch_T regmatch;
1167 char_u **files;
1168 int count;
1169 int save_p_scs;
1170 int dir = compl_direction;
1171
1172 if (*dict == NUL)
1173 {
1174#ifdef FEAT_SPELL
1175 // When 'dictionary' is empty and spell checking is enabled use
1176 // "spell".
1177 if (!thesaurus && curwin->w_p_spell)
1178 dict = (char_u *)"spell";
1179 else
1180#endif
1181 return;
1182 }
1183
1184 buf = alloc(LSIZE);
1185 if (buf == NULL)
1186 return;
1187 regmatch.regprog = NULL; // so that we can goto theend
1188
1189 // If 'infercase' is set, don't use 'smartcase' here
1190 save_p_scs = p_scs;
1191 if (curbuf->b_p_inf)
1192 p_scs = FALSE;
1193
1194 // When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern
1195 // to only match at the start of a line. Otherwise just match the
1196 // pattern. Also need to double backslashes.
1197 if (ctrl_x_mode_line_or_eval())
1198 {
1199 char_u *pat_esc = vim_strsave_escaped(pat, (char_u *)"\\");
1200 size_t len;
1201
1202 if (pat_esc == NULL)
1203 goto theend;
1204 len = STRLEN(pat_esc) + 10;
Bram Moolenaar964b3742019-05-24 18:54:09 +02001205 ptr = alloc(len);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001206 if (ptr == NULL)
1207 {
1208 vim_free(pat_esc);
1209 goto theend;
1210 }
1211 vim_snprintf((char *)ptr, len, "^\\s*\\zs\\V%s", pat_esc);
1212 regmatch.regprog = vim_regcomp(ptr, RE_MAGIC);
1213 vim_free(pat_esc);
1214 vim_free(ptr);
1215 }
1216 else
1217 {
Bram Moolenaarf4e20992020-12-21 19:59:08 +01001218 regmatch.regprog = vim_regcomp(pat, magic_isset() ? RE_MAGIC : 0);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001219 if (regmatch.regprog == NULL)
1220 goto theend;
1221 }
1222
1223 // ignore case depends on 'ignorecase', 'smartcase' and "pat"
1224 regmatch.rm_ic = ignorecase(pat);
1225 while (*dict != NUL && !got_int && !compl_interrupted)
1226 {
1227 // copy one dictionary file name into buf
1228 if (flags == DICT_EXACT)
1229 {
1230 count = 1;
1231 files = &dict;
1232 }
1233 else
1234 {
1235 // Expand wildcards in the dictionary name, but do not allow
1236 // backticks (for security, the 'dict' option may have been set in
1237 // a modeline).
1238 copy_option_part(&dict, buf, LSIZE, ",");
1239# ifdef FEAT_SPELL
1240 if (!thesaurus && STRCMP(buf, "spell") == 0)
1241 count = -1;
1242 else
1243# endif
1244 if (vim_strchr(buf, '`') != NULL
1245 || expand_wildcards(1, &buf, &count, &files,
1246 EW_FILE|EW_SILENT) != OK)
1247 count = 0;
1248 }
1249
1250# ifdef FEAT_SPELL
1251 if (count == -1)
1252 {
1253 // Complete from active spelling. Skip "\<" in the pattern, we
1254 // don't use it as a RE.
1255 if (pat[0] == '\\' && pat[1] == '<')
1256 ptr = pat + 2;
1257 else
1258 ptr = pat;
1259 spell_dump_compl(ptr, regmatch.rm_ic, &dir, 0);
1260 }
1261 else
1262# endif
1263 if (count > 0) // avoid warning for using "files" uninit
1264 {
1265 ins_compl_files(count, files, thesaurus, flags,
1266 &regmatch, buf, &dir);
1267 if (flags != DICT_EXACT)
1268 FreeWild(count, files);
1269 }
1270 if (flags != 0)
1271 break;
1272 }
1273
1274theend:
1275 p_scs = save_p_scs;
1276 vim_regfree(regmatch.regprog);
1277 vim_free(buf);
1278}
1279
1280 static void
1281ins_compl_files(
1282 int count,
1283 char_u **files,
1284 int thesaurus,
1285 int flags,
1286 regmatch_T *regmatch,
1287 char_u *buf,
1288 int *dir)
1289{
1290 char_u *ptr;
1291 int i;
1292 FILE *fp;
1293 int add_r;
1294
1295 for (i = 0; i < count && !got_int && !compl_interrupted; i++)
1296 {
1297 fp = mch_fopen((char *)files[i], "r"); // open dictionary file
1298 if (flags != DICT_EXACT)
1299 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01001300 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001301 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);
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001582 compl_leader = vim_strnsave(line + compl_col, (p - line) - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001583 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,
Bram Moolenaar71ccd032020-06-12 22:59:11 +02001709 curwin->w_cursor.col - compl_col);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001710 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
Bram Moolenaar957cf672020-11-12 14:21:06 +01001825 || c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_COMMAND)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01001826 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;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002201 typval_T rettv;
2202 int save_State = State;
2203
2204 funcname = (type == CTRL_X_FUNCTION) ? curbuf->b_p_cfu : curbuf->b_p_ofu;
2205 if (*funcname == NUL)
2206 return;
2207
2208 // Call 'completefunc' to obtain the list of matches.
2209 args[0].v_type = VAR_NUMBER;
2210 args[0].vval.v_number = 0;
2211 args[1].v_type = VAR_STRING;
2212 args[1].vval.v_string = base != NULL ? base : (char_u *)"";
2213 args[2].v_type = VAR_UNKNOWN;
2214
2215 pos = curwin->w_cursor;
Bram Moolenaar28976e22021-01-29 21:07:07 +01002216 // Lock the text to avoid weird things from happening. Also disallow
2217 // switching to another window, it should not be needed and may end up in
2218 // Insert mode in another buffer.
2219 ++textwinlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002220
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 }
Bram Moolenaar28976e22021-01-29 21:07:07 +01002242 --textwinlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002243
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002244 curwin->w_cursor = pos; // restore the cursor position
2245 validate_cursor();
2246 if (!EQUAL_POS(curwin->w_cursor, pos))
2247 {
2248 emsg(_(e_compldel));
2249 goto theend;
2250 }
2251
2252 if (matchlist != NULL)
2253 ins_compl_add_list(matchlist);
2254 else if (matchdict != NULL)
2255 ins_compl_add_dict(matchdict);
2256
2257theend:
2258 // Restore State, it might have been changed.
2259 State = save_State;
2260
2261 if (matchdict != NULL)
2262 dict_unref(matchdict);
2263 if (matchlist != NULL)
2264 list_unref(matchlist);
2265}
2266#endif // FEAT_COMPL_FUNC
2267
2268#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL) || defined(PROTO)
2269/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002270 * Add a match to the list of matches from a typeval_T.
2271 * If the given string is already in the list of completions, then return
2272 * NOTDONE, otherwise add it to the list and return OK. If there is an error,
2273 * maybe because alloc() returns NULL, then FAIL is returned.
2274 */
2275 static int
2276ins_compl_add_tv(typval_T *tv, int dir)
2277{
2278 char_u *word;
2279 int dup = FALSE;
2280 int empty = FALSE;
2281 int flags = 0;
2282 char_u *(cptext[CPT_COUNT]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002283 typval_T user_data;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002284
Bram Moolenaar08928322020-01-04 14:32:48 +01002285 user_data.v_type = VAR_UNKNOWN;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002286 if (tv->v_type == VAR_DICT && tv->vval.v_dict != NULL)
2287 {
2288 word = dict_get_string(tv->vval.v_dict, (char_u *)"word", FALSE);
2289 cptext[CPT_ABBR] = dict_get_string(tv->vval.v_dict,
2290 (char_u *)"abbr", FALSE);
2291 cptext[CPT_MENU] = dict_get_string(tv->vval.v_dict,
2292 (char_u *)"menu", FALSE);
2293 cptext[CPT_KIND] = dict_get_string(tv->vval.v_dict,
2294 (char_u *)"kind", FALSE);
2295 cptext[CPT_INFO] = dict_get_string(tv->vval.v_dict,
2296 (char_u *)"info", FALSE);
Bram Moolenaar08928322020-01-04 14:32:48 +01002297 dict_get_tv(tv->vval.v_dict, (char_u *)"user_data", &user_data);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002298 if (dict_get_string(tv->vval.v_dict, (char_u *)"icase", FALSE) != NULL
2299 && dict_get_number(tv->vval.v_dict, (char_u *)"icase"))
2300 flags |= CP_ICASE;
2301 if (dict_get_string(tv->vval.v_dict, (char_u *)"dup", FALSE) != NULL)
2302 dup = dict_get_number(tv->vval.v_dict, (char_u *)"dup");
2303 if (dict_get_string(tv->vval.v_dict, (char_u *)"empty", FALSE) != NULL)
2304 empty = dict_get_number(tv->vval.v_dict, (char_u *)"empty");
2305 if (dict_get_string(tv->vval.v_dict, (char_u *)"equal", FALSE) != NULL
2306 && dict_get_number(tv->vval.v_dict, (char_u *)"equal"))
2307 flags |= CP_EQUAL;
2308 }
2309 else
2310 {
2311 word = tv_get_string_chk(tv);
Bram Moolenaara80faa82020-04-12 19:37:17 +02002312 CLEAR_FIELD(cptext);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002313 }
2314 if (word == NULL || (!empty && *word == NUL))
2315 return FAIL;
Bram Moolenaar08928322020-01-04 14:32:48 +01002316 return ins_compl_add(word, -1, NULL, cptext, &user_data, dir, flags, dup);
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002317}
2318
2319/*
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002320 * Add completions from a list.
2321 */
2322 static void
2323ins_compl_add_list(list_T *list)
2324{
2325 listitem_T *li;
2326 int dir = compl_direction;
2327
2328 // Go through the List with matches and add each of them.
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002329 CHECK_LIST_MATERIALIZE(list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002330 FOR_ALL_LIST_ITEMS(list, li)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002331 {
2332 if (ins_compl_add_tv(&li->li_tv, dir) == OK)
2333 // if dir was BACKWARD then honor it just once
2334 dir = FORWARD;
2335 else if (did_emsg)
2336 break;
2337 }
2338}
2339
2340/*
2341 * Add completions from a dict.
2342 */
2343 static void
2344ins_compl_add_dict(dict_T *dict)
2345{
2346 dictitem_T *di_refresh;
2347 dictitem_T *di_words;
2348
2349 // Check for optional "refresh" item.
2350 compl_opt_refresh_always = FALSE;
2351 di_refresh = dict_find(dict, (char_u *)"refresh", 7);
2352 if (di_refresh != NULL && di_refresh->di_tv.v_type == VAR_STRING)
2353 {
2354 char_u *v = di_refresh->di_tv.vval.v_string;
2355
2356 if (v != NULL && STRCMP(v, (char_u *)"always") == 0)
2357 compl_opt_refresh_always = TRUE;
2358 }
2359
2360 // Add completions from a "words" list.
2361 di_words = dict_find(dict, (char_u *)"words", 5);
2362 if (di_words != NULL && di_words->di_tv.v_type == VAR_LIST)
2363 ins_compl_add_list(di_words->di_tv.vval.v_list);
2364}
2365
2366/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002367 * Start completion for the complete() function.
2368 * "startcol" is where the matched text starts (1 is first column).
2369 * "list" is the list of matches.
2370 */
2371 static void
2372set_completion(colnr_T startcol, list_T *list)
2373{
2374 int save_w_wrow = curwin->w_wrow;
2375 int save_w_leftcol = curwin->w_leftcol;
2376 int flags = CP_ORIGINAL_TEXT;
2377
2378 // If already doing completions stop it.
2379 if (ctrl_x_mode != CTRL_X_NORMAL)
2380 ins_compl_prep(' ');
2381 ins_compl_clear();
2382 ins_compl_free();
2383
2384 compl_direction = FORWARD;
2385 if (startcol > curwin->w_cursor.col)
2386 startcol = curwin->w_cursor.col;
2387 compl_col = startcol;
2388 compl_length = (int)curwin->w_cursor.col - (int)startcol;
2389 // compl_pattern doesn't need to be set
2390 compl_orig_text = vim_strnsave(ml_get_curline() + compl_col, compl_length);
2391 if (p_ic)
2392 flags |= CP_ICASE;
2393 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar08928322020-01-04 14:32:48 +01002394 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002395 return;
2396
2397 ctrl_x_mode = CTRL_X_EVAL;
2398
2399 ins_compl_add_list(list);
2400 compl_matches = ins_compl_make_cyclic();
2401 compl_started = TRUE;
2402 compl_used_match = TRUE;
2403 compl_cont_status = 0;
2404
2405 compl_curr_match = compl_first_match;
2406 if (compl_no_insert || compl_no_select)
2407 {
2408 ins_complete(K_DOWN, FALSE);
2409 if (compl_no_select)
2410 // Down/Up has no real effect.
2411 ins_complete(K_UP, FALSE);
2412 }
2413 else
2414 ins_complete(Ctrl_N, FALSE);
2415 compl_enter_selects = compl_no_insert;
2416
2417 // Lazily show the popup menu, unless we got interrupted.
2418 if (!compl_interrupted)
2419 show_pum(save_w_wrow, save_w_leftcol);
2420 out_flush();
2421}
2422
2423/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002424 * "complete()" function
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002425 */
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002426 void
2427f_complete(typval_T *argvars, typval_T *rettv UNUSED)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002428{
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002429 int startcol;
Bram Moolenaarff06f282020-04-21 22:01:14 +02002430 int save_textlock = textlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002431
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002432 if ((State & INSERT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002433 {
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002434 emsg(_("E785: complete() can only be used in Insert mode"));
2435 return;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002436 }
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002437
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02002438 // "textlock" is set when evaluating 'completefunc' but we can change
2439 // text here.
Bram Moolenaarff06f282020-04-21 22:01:14 +02002440 textlock = 0;
2441
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002442 // Check for undo allowed here, because if something was already inserted
2443 // the line was already saved for undo and this check isn't done.
2444 if (!undo_allowed())
2445 return;
2446
2447 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002448 emsg(_(e_invarg));
Bram Moolenaarff06f282020-04-21 22:01:14 +02002449 else
2450 {
2451 startcol = (int)tv_get_number_chk(&argvars[0], NULL);
2452 if (startcol > 0)
2453 set_completion(startcol - 1, argvars[1].vval.v_list);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002454 }
Bram Moolenaarff06f282020-04-21 22:01:14 +02002455 textlock = save_textlock;
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002456}
2457
2458/*
2459 * "complete_add()" function
2460 */
2461 void
2462f_complete_add(typval_T *argvars, typval_T *rettv)
2463{
2464 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
2465}
2466
2467/*
2468 * "complete_check()" function
2469 */
2470 void
2471f_complete_check(typval_T *argvars UNUSED, typval_T *rettv)
2472{
2473 int saved = RedrawingDisabled;
2474
2475 RedrawingDisabled = 0;
2476 ins_compl_check_keys(0, TRUE);
2477 rettv->vval.v_number = ins_compl_interrupted();
2478 RedrawingDisabled = saved;
2479}
2480
2481/*
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002482 * Return Insert completion mode name string
2483 */
2484 static char_u *
2485ins_compl_mode(void)
2486{
2487 if (ctrl_x_mode == CTRL_X_NOT_DEFINED_YET || compl_started)
2488 return (char_u *)ctrl_x_mode_names[ctrl_x_mode & ~CTRL_X_WANT_IDENT];
2489
2490 return (char_u *)"";
2491}
2492
Bram Moolenaarf9d51352020-10-26 19:22:42 +01002493 static void
2494ins_compl_update_sequence_numbers()
2495{
2496 int number = 0;
2497 compl_T *match;
2498
2499 if (compl_direction == FORWARD)
2500 {
2501 // search backwards for the first valid (!= -1) number.
2502 // This should normally succeed already at the first loop
2503 // cycle, so it's fast!
2504 for (match = compl_curr_match->cp_prev; match != NULL
2505 && match != compl_first_match;
2506 match = match->cp_prev)
2507 if (match->cp_number != -1)
2508 {
2509 number = match->cp_number;
2510 break;
2511 }
2512 if (match != NULL)
2513 // go up and assign all numbers which are not assigned
2514 // yet
2515 for (match = match->cp_next;
2516 match != NULL && match->cp_number == -1;
2517 match = match->cp_next)
2518 match->cp_number = ++number;
2519 }
2520 else // BACKWARD
2521 {
2522 // search forwards (upwards) for the first valid (!= -1)
2523 // number. This should normally succeed already at the
2524 // first loop cycle, so it's fast!
2525 for (match = compl_curr_match->cp_next; match != NULL
2526 && match != compl_first_match;
2527 match = match->cp_next)
2528 if (match->cp_number != -1)
2529 {
2530 number = match->cp_number;
2531 break;
2532 }
2533 if (match != NULL)
2534 // go down and assign all numbers which are not
2535 // assigned yet
2536 for (match = match->cp_prev; match
2537 && match->cp_number == -1;
2538 match = match->cp_prev)
2539 match->cp_number = ++number;
2540 }
2541}
2542
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002543/*
2544 * Get complete information
2545 */
2546 static void
2547get_complete_info(list_T *what_list, dict_T *retdict)
2548{
2549 int ret = OK;
2550 listitem_T *item;
2551#define CI_WHAT_MODE 0x01
2552#define CI_WHAT_PUM_VISIBLE 0x02
2553#define CI_WHAT_ITEMS 0x04
2554#define CI_WHAT_SELECTED 0x08
2555#define CI_WHAT_INSERTED 0x10
2556#define CI_WHAT_ALL 0xff
2557 int what_flag;
2558
2559 if (what_list == NULL)
2560 what_flag = CI_WHAT_ALL;
2561 else
2562 {
2563 what_flag = 0;
Bram Moolenaar7e9f3512020-05-13 22:44:22 +02002564 CHECK_LIST_MATERIALIZE(what_list);
Bram Moolenaaraeea7212020-04-02 18:50:46 +02002565 FOR_ALL_LIST_ITEMS(what_list, item)
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002566 {
2567 char_u *what = tv_get_string(&item->li_tv);
2568
2569 if (STRCMP(what, "mode") == 0)
2570 what_flag |= CI_WHAT_MODE;
2571 else if (STRCMP(what, "pum_visible") == 0)
2572 what_flag |= CI_WHAT_PUM_VISIBLE;
2573 else if (STRCMP(what, "items") == 0)
2574 what_flag |= CI_WHAT_ITEMS;
2575 else if (STRCMP(what, "selected") == 0)
2576 what_flag |= CI_WHAT_SELECTED;
2577 else if (STRCMP(what, "inserted") == 0)
2578 what_flag |= CI_WHAT_INSERTED;
2579 }
2580 }
2581
2582 if (ret == OK && (what_flag & CI_WHAT_MODE))
2583 ret = dict_add_string(retdict, "mode", ins_compl_mode());
2584
2585 if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE))
2586 ret = dict_add_number(retdict, "pum_visible", pum_visible());
2587
2588 if (ret == OK && (what_flag & CI_WHAT_ITEMS))
2589 {
2590 list_T *li;
2591 dict_T *di;
2592 compl_T *match;
2593
2594 li = list_alloc();
2595 if (li == NULL)
2596 return;
2597 ret = dict_add_list(retdict, "items", li);
2598 if (ret == OK && compl_first_match != NULL)
2599 {
2600 match = compl_first_match;
2601 do
2602 {
2603 if (!(match->cp_flags & CP_ORIGINAL_TEXT))
2604 {
2605 di = dict_alloc();
2606 if (di == NULL)
2607 return;
2608 ret = list_append_dict(li, di);
2609 if (ret != OK)
2610 return;
2611 dict_add_string(di, "word", match->cp_str);
2612 dict_add_string(di, "abbr", match->cp_text[CPT_ABBR]);
2613 dict_add_string(di, "menu", match->cp_text[CPT_MENU]);
2614 dict_add_string(di, "kind", match->cp_text[CPT_KIND]);
2615 dict_add_string(di, "info", match->cp_text[CPT_INFO]);
Bram Moolenaar08928322020-01-04 14:32:48 +01002616 if (match->cp_user_data.v_type == VAR_UNKNOWN)
2617 // Add an empty string for backwards compatibility
2618 dict_add_string(di, "user_data", (char_u *)"");
2619 else
2620 dict_add_tv(di, "user_data", &match->cp_user_data);
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002621 }
2622 match = match->cp_next;
2623 }
2624 while (match != NULL && match != compl_first_match);
2625 }
2626 }
2627
2628 if (ret == OK && (what_flag & CI_WHAT_SELECTED))
Bram Moolenaarf9d51352020-10-26 19:22:42 +01002629 {
2630 if (compl_curr_match != NULL && compl_curr_match->cp_number == -1)
2631 ins_compl_update_sequence_numbers();
2632 ret = dict_add_number(retdict, "selected", compl_curr_match != NULL
2633 ? compl_curr_match->cp_number - 1 : -1);
2634 }
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02002635
2636 // TODO
2637 // if (ret == OK && (what_flag & CI_WHAT_INSERTED))
2638}
2639
2640/*
Bram Moolenaar9bca58f2019-08-15 21:31:52 +02002641 * "complete_info()" function
2642 */
2643 void
2644f_complete_info(typval_T *argvars, typval_T *rettv)
2645{
2646 list_T *what_list = NULL;
2647
2648 if (rettv_dict_alloc(rettv) != OK)
2649 return;
2650
2651 if (argvars[0].v_type != VAR_UNKNOWN)
2652 {
2653 if (argvars[0].v_type != VAR_LIST)
2654 {
2655 emsg(_(e_listreq));
2656 return;
2657 }
2658 what_list = argvars[0].vval.v_list;
2659 }
2660 get_complete_info(what_list, rettv->vval.v_dict);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002661}
2662#endif
2663
2664/*
2665 * Get the next expansion(s), using "compl_pattern".
2666 * The search starts at position "ini" in curbuf and in the direction
2667 * compl_direction.
2668 * When "compl_started" is FALSE start at that position, otherwise continue
2669 * where we stopped searching before.
2670 * This may return before finding all the matches.
2671 * Return the total number of matches or -1 if still unknown -- Acevedo
2672 */
2673 static int
2674ins_compl_get_exp(pos_T *ini)
2675{
2676 static pos_T first_match_pos;
2677 static pos_T last_match_pos;
2678 static char_u *e_cpt = (char_u *)""; // curr. entry in 'complete'
2679 static int found_all = FALSE; // Found all matches of a
2680 // certain type.
2681 static buf_T *ins_buf = NULL; // buffer being scanned
2682
2683 pos_T *pos;
2684 char_u **matches;
2685 int save_p_scs;
2686 int save_p_ws;
2687 int save_p_ic;
2688 int i;
2689 int num_matches;
2690 int len;
2691 int found_new_match;
2692 int type = ctrl_x_mode;
2693 char_u *ptr;
2694 char_u *dict = NULL;
2695 int dict_f = 0;
2696 int set_match_pos;
2697
2698 if (!compl_started)
2699 {
2700 FOR_ALL_BUFFERS(ins_buf)
2701 ins_buf->b_scanned = 0;
2702 found_all = FALSE;
2703 ins_buf = curbuf;
2704 e_cpt = (compl_cont_status & CONT_LOCAL)
2705 ? (char_u *)"." : curbuf->b_p_cpt;
2706 last_match_pos = first_match_pos = *ini;
2707 }
2708 else if (ins_buf != curbuf && !buf_valid(ins_buf))
2709 ins_buf = curbuf; // In case the buffer was wiped out.
2710
2711 compl_old_match = compl_curr_match; // remember the last current match
2712 pos = (compl_direction == FORWARD) ? &last_match_pos : &first_match_pos;
2713
2714 // For ^N/^P loop over all the flags/windows/buffers in 'complete'.
2715 for (;;)
2716 {
2717 found_new_match = FAIL;
2718 set_match_pos = FALSE;
2719
2720 // For ^N/^P pick a new entry from e_cpt if compl_started is off,
2721 // or if found_all says this entry is done. For ^X^L only use the
2722 // entries from 'complete' that look in loaded buffers.
2723 if ((ctrl_x_mode == CTRL_X_NORMAL
2724 || ctrl_x_mode_line_or_eval())
2725 && (!compl_started || found_all))
2726 {
2727 found_all = FALSE;
2728 while (*e_cpt == ',' || *e_cpt == ' ')
2729 e_cpt++;
2730 if (*e_cpt == '.' && !curbuf->b_scanned)
2731 {
2732 ins_buf = curbuf;
2733 first_match_pos = *ini;
2734 // Move the cursor back one character so that ^N can match the
2735 // word immediately after the cursor.
2736 if (ctrl_x_mode == CTRL_X_NORMAL && dec(&first_match_pos) < 0)
2737 {
2738 // Move the cursor to after the last character in the
2739 // buffer, so that word at start of buffer is found
2740 // correctly.
2741 first_match_pos.lnum = ins_buf->b_ml.ml_line_count;
2742 first_match_pos.col =
2743 (colnr_T)STRLEN(ml_get(first_match_pos.lnum));
2744 }
2745 last_match_pos = first_match_pos;
2746 type = 0;
2747
2748 // Remember the first match so that the loop stops when we
2749 // wrap and come back there a second time.
2750 set_match_pos = TRUE;
2751 }
2752 else if (vim_strchr((char_u *)"buwU", *e_cpt) != NULL
2753 && (ins_buf = ins_compl_next_buf(ins_buf, *e_cpt)) != curbuf)
2754 {
2755 // Scan a buffer, but not the current one.
2756 if (ins_buf->b_ml.ml_mfp != NULL) // loaded buffer
2757 {
2758 compl_started = TRUE;
2759 first_match_pos.col = last_match_pos.col = 0;
2760 first_match_pos.lnum = ins_buf->b_ml.ml_line_count + 1;
2761 last_match_pos.lnum = 0;
2762 type = 0;
2763 }
2764 else // unloaded buffer, scan like dictionary
2765 {
2766 found_all = TRUE;
2767 if (ins_buf->b_fname == NULL)
2768 continue;
2769 type = CTRL_X_DICTIONARY;
2770 dict = ins_buf->b_fname;
2771 dict_f = DICT_EXACT;
2772 }
Bram Moolenaarcc233582020-12-12 13:32:07 +01002773 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002774 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning: %s"),
2775 ins_buf->b_fname == NULL
2776 ? buf_spname(ins_buf)
2777 : ins_buf->b_sfname == NULL
2778 ? ins_buf->b_fname
2779 : ins_buf->b_sfname);
2780 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2781 }
2782 else if (*e_cpt == NUL)
2783 break;
2784 else
2785 {
2786 if (ctrl_x_mode_line_or_eval())
2787 type = -1;
2788 else if (*e_cpt == 'k' || *e_cpt == 's')
2789 {
2790 if (*e_cpt == 'k')
2791 type = CTRL_X_DICTIONARY;
2792 else
2793 type = CTRL_X_THESAURUS;
2794 if (*++e_cpt != ',' && *e_cpt != NUL)
2795 {
2796 dict = e_cpt;
2797 dict_f = DICT_FIRST;
2798 }
2799 }
2800#ifdef FEAT_FIND_ID
2801 else if (*e_cpt == 'i')
2802 type = CTRL_X_PATH_PATTERNS;
2803 else if (*e_cpt == 'd')
2804 type = CTRL_X_PATH_DEFINES;
2805#endif
2806 else if (*e_cpt == ']' || *e_cpt == 't')
2807 {
Bram Moolenaarcc233582020-12-12 13:32:07 +01002808 msg_hist_off = TRUE; // reset in msg_trunc_attr()
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002809 type = CTRL_X_TAGS;
2810 vim_snprintf((char *)IObuff, IOSIZE, _("Scanning tags."));
2811 (void)msg_trunc_attr((char *)IObuff, TRUE, HL_ATTR(HLF_R));
2812 }
2813 else
2814 type = -1;
2815
2816 // in any case e_cpt is advanced to the next entry
2817 (void)copy_option_part(&e_cpt, IObuff, IOSIZE, ",");
2818
2819 found_all = TRUE;
2820 if (type == -1)
2821 continue;
2822 }
2823 }
2824
2825 // If complete() was called then compl_pattern has been reset. The
2826 // following won't work then, bail out.
2827 if (compl_pattern == NULL)
2828 break;
2829
2830 switch (type)
2831 {
2832 case -1:
2833 break;
2834#ifdef FEAT_FIND_ID
2835 case CTRL_X_PATH_PATTERNS:
2836 case CTRL_X_PATH_DEFINES:
2837 find_pattern_in_path(compl_pattern, compl_direction,
2838 (int)STRLEN(compl_pattern), FALSE, FALSE,
2839 (type == CTRL_X_PATH_DEFINES
2840 && !(compl_cont_status & CONT_SOL))
2841 ? FIND_DEFINE : FIND_ANY, 1L, ACTION_EXPAND,
2842 (linenr_T)1, (linenr_T)MAXLNUM);
2843 break;
2844#endif
2845
2846 case CTRL_X_DICTIONARY:
2847 case CTRL_X_THESAURUS:
2848 ins_compl_dictionaries(
2849 dict != NULL ? dict
2850 : (type == CTRL_X_THESAURUS
2851 ? (*curbuf->b_p_tsr == NUL
2852 ? p_tsr
2853 : curbuf->b_p_tsr)
2854 : (*curbuf->b_p_dict == NUL
2855 ? p_dict
2856 : curbuf->b_p_dict)),
2857 compl_pattern,
2858 dict != NULL ? dict_f
2859 : 0, type == CTRL_X_THESAURUS);
2860 dict = NULL;
2861 break;
2862
2863 case CTRL_X_TAGS:
2864 // set p_ic according to p_ic, p_scs and pat for find_tags().
2865 save_p_ic = p_ic;
2866 p_ic = ignorecase(compl_pattern);
2867
2868 // Find up to TAG_MANY matches. Avoids that an enormous number
2869 // of matches is found when compl_pattern is empty
Bram Moolenaar45e18cb2019-04-28 18:05:35 +02002870 g_tag_at_cursor = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002871 if (find_tags(compl_pattern, &num_matches, &matches,
2872 TAG_REGEXP | TAG_NAMES | TAG_NOIC | TAG_INS_COMP
2873 | (ctrl_x_mode != CTRL_X_NORMAL ? TAG_VERBOSE : 0),
2874 TAG_MANY, curbuf->b_ffname) == OK && num_matches > 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002875 ins_compl_add_matches(num_matches, matches, p_ic);
Bram Moolenaar45e18cb2019-04-28 18:05:35 +02002876 g_tag_at_cursor = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002877 p_ic = save_p_ic;
2878 break;
2879
2880 case CTRL_X_FILES:
2881 if (expand_wildcards(1, &compl_pattern, &num_matches, &matches,
2882 EW_FILE|EW_DIR|EW_ADDSLASH|EW_SILENT) == OK)
2883 {
2884
2885 // May change home directory back to "~".
2886 tilde_replace(compl_pattern, num_matches, matches);
Bram Moolenaarac3150d2019-07-28 16:36:39 +02002887#ifdef BACKSLASH_IN_FILENAME
2888 if (curbuf->b_p_csl[0] != NUL)
2889 {
2890 int i;
2891
2892 for (i = 0; i < num_matches; ++i)
2893 {
2894 char_u *ptr = matches[i];
2895
2896 while (*ptr != NUL)
2897 {
2898 if (curbuf->b_p_csl[0] == 's' && *ptr == '\\')
2899 *ptr = '/';
2900 else if (curbuf->b_p_csl[0] == 'b' && *ptr == '/')
2901 *ptr = '\\';
2902 ptr += (*mb_ptr2len)(ptr);
2903 }
2904 }
2905 }
2906#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002907 ins_compl_add_matches(num_matches, matches, p_fic || p_wic);
2908 }
2909 break;
2910
2911 case CTRL_X_CMDLINE:
2912 if (expand_cmdline(&compl_xp, compl_pattern,
2913 (int)STRLEN(compl_pattern),
2914 &num_matches, &matches) == EXPAND_OK)
2915 ins_compl_add_matches(num_matches, matches, FALSE);
2916 break;
2917
2918#ifdef FEAT_COMPL_FUNC
2919 case CTRL_X_FUNCTION:
2920 case CTRL_X_OMNI:
2921 expand_by_function(type, compl_pattern);
2922 break;
2923#endif
2924
2925 case CTRL_X_SPELL:
2926#ifdef FEAT_SPELL
2927 num_matches = expand_spelling(first_match_pos.lnum,
2928 compl_pattern, &matches);
2929 if (num_matches > 0)
2930 ins_compl_add_matches(num_matches, matches, p_ic);
2931#endif
2932 break;
2933
2934 default: // normal ^P/^N and ^X^L
2935 // If 'infercase' is set, don't use 'smartcase' here
2936 save_p_scs = p_scs;
2937 if (ins_buf->b_p_inf)
2938 p_scs = FALSE;
2939
2940 // Buffers other than curbuf are scanned from the beginning or the
2941 // end but never from the middle, thus setting nowrapscan in this
Bram Moolenaar32aa1022019-11-02 22:54:41 +01002942 // buffer is a good idea, on the other hand, we always set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002943 // wrapscan for curbuf to avoid missing matches -- Acevedo,Webb
2944 save_p_ws = p_ws;
2945 if (ins_buf != curbuf)
2946 p_ws = FALSE;
2947 else if (*e_cpt == '.')
2948 p_ws = TRUE;
2949 for (;;)
2950 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02002951 int cont_s_ipos = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002952
2953 ++msg_silent; // Don't want messages for wrapscan.
2954
2955 // ctrl_x_mode_line_or_eval() || word-wise search that
2956 // has added a word that was at the beginning of the line
2957 if (ctrl_x_mode_line_or_eval()
2958 || (compl_cont_status & CONT_SOL))
2959 found_new_match = search_for_exact_line(ins_buf, pos,
2960 compl_direction, compl_pattern);
2961 else
2962 found_new_match = searchit(NULL, ins_buf, pos, NULL,
2963 compl_direction,
2964 compl_pattern, 1L, SEARCH_KEEP + SEARCH_NFMSG,
Bram Moolenaar92ea26b2019-10-18 20:53:34 +02002965 RE_LAST, NULL);
Bram Moolenaar7591bb32019-03-30 13:53:47 +01002966 --msg_silent;
2967 if (!compl_started || set_match_pos)
2968 {
2969 // set "compl_started" even on fail
2970 compl_started = TRUE;
2971 first_match_pos = *pos;
2972 last_match_pos = *pos;
2973 set_match_pos = FALSE;
2974 }
2975 else if (first_match_pos.lnum == last_match_pos.lnum
2976 && first_match_pos.col == last_match_pos.col)
2977 found_new_match = FAIL;
2978 if (found_new_match == FAIL)
2979 {
2980 if (ins_buf == curbuf)
2981 found_all = TRUE;
2982 break;
2983 }
2984
2985 // when ADDING, the text before the cursor matches, skip it
2986 if ( (compl_cont_status & CONT_ADDING) && ins_buf == curbuf
2987 && ini->lnum == pos->lnum
2988 && ini->col == pos->col)
2989 continue;
2990 ptr = ml_get_buf(ins_buf, pos->lnum, FALSE) + pos->col;
2991 if (ctrl_x_mode_line_or_eval())
2992 {
2993 if (compl_cont_status & CONT_ADDING)
2994 {
2995 if (pos->lnum >= ins_buf->b_ml.ml_line_count)
2996 continue;
2997 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
2998 if (!p_paste)
2999 ptr = skipwhite(ptr);
3000 }
3001 len = (int)STRLEN(ptr);
3002 }
3003 else
3004 {
3005 char_u *tmp_ptr = ptr;
3006
3007 if (compl_cont_status & CONT_ADDING)
3008 {
3009 tmp_ptr += compl_length;
3010 // Skip if already inside a word.
3011 if (vim_iswordp(tmp_ptr))
3012 continue;
3013 // Find start of next word.
3014 tmp_ptr = find_word_start(tmp_ptr);
3015 }
3016 // Find end of this word.
3017 tmp_ptr = find_word_end(tmp_ptr);
3018 len = (int)(tmp_ptr - ptr);
3019
3020 if ((compl_cont_status & CONT_ADDING)
3021 && len == compl_length)
3022 {
3023 if (pos->lnum < ins_buf->b_ml.ml_line_count)
3024 {
3025 // Try next line, if any. the new word will be
3026 // "join" as if the normal command "J" was used.
3027 // IOSIZE is always greater than
3028 // compl_length, so the next STRNCPY always
3029 // works -- Acevedo
3030 STRNCPY(IObuff, ptr, len);
3031 ptr = ml_get_buf(ins_buf, pos->lnum + 1, FALSE);
3032 tmp_ptr = ptr = skipwhite(ptr);
3033 // Find start of next word.
3034 tmp_ptr = find_word_start(tmp_ptr);
3035 // Find end of next word.
3036 tmp_ptr = find_word_end(tmp_ptr);
3037 if (tmp_ptr > ptr)
3038 {
3039 if (*ptr != ')' && IObuff[len - 1] != TAB)
3040 {
3041 if (IObuff[len - 1] != ' ')
3042 IObuff[len++] = ' ';
3043 // IObuf =~ "\k.* ", thus len >= 2
3044 if (p_js
3045 && (IObuff[len - 2] == '.'
3046 || (vim_strchr(p_cpo, CPO_JOINSP)
3047 == NULL
3048 && (IObuff[len - 2] == '?'
3049 || IObuff[len - 2] == '!'))))
3050 IObuff[len++] = ' ';
3051 }
3052 // copy as much as possible of the new word
3053 if (tmp_ptr - ptr >= IOSIZE - len)
3054 tmp_ptr = ptr + IOSIZE - len - 1;
3055 STRNCPY(IObuff + len, ptr, tmp_ptr - ptr);
3056 len += (int)(tmp_ptr - ptr);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003057 cont_s_ipos = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003058 }
3059 IObuff[len] = NUL;
3060 ptr = IObuff;
3061 }
3062 if (len == compl_length)
3063 continue;
3064 }
3065 }
3066 if (ins_compl_add_infercase(ptr, len, p_ic,
3067 ins_buf == curbuf ? NULL : ins_buf->b_sfname,
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003068 0, cont_s_ipos) != NOTDONE)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003069 {
3070 found_new_match = OK;
3071 break;
3072 }
3073 }
3074 p_scs = save_p_scs;
3075 p_ws = save_p_ws;
3076 }
3077
3078 // check if compl_curr_match has changed, (e.g. other type of
3079 // expansion added something)
3080 if (type != 0 && compl_curr_match != compl_old_match)
3081 found_new_match = OK;
3082
3083 // break the loop for specialized modes (use 'complete' just for the
3084 // generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new
3085 // match
3086 if ((ctrl_x_mode != CTRL_X_NORMAL
3087 && !ctrl_x_mode_line_or_eval()) || found_new_match != FAIL)
3088 {
3089 if (got_int)
3090 break;
3091 // Fill the popup menu as soon as possible.
3092 if (type != -1)
3093 ins_compl_check_keys(0, FALSE);
3094
3095 if ((ctrl_x_mode != CTRL_X_NORMAL
3096 && !ctrl_x_mode_line_or_eval()) || compl_interrupted)
3097 break;
3098 compl_started = TRUE;
3099 }
3100 else
3101 {
3102 // Mark a buffer scanned when it has been scanned completely
3103 if (type == 0 || type == CTRL_X_PATH_PATTERNS)
3104 ins_buf->b_scanned = TRUE;
3105
3106 compl_started = FALSE;
3107 }
3108 }
3109 compl_started = TRUE;
3110
3111 if ((ctrl_x_mode == CTRL_X_NORMAL || ctrl_x_mode_line_or_eval())
3112 && *e_cpt == NUL) // Got to end of 'complete'
3113 found_new_match = FAIL;
3114
3115 i = -1; // total of matches, unknown
3116 if (found_new_match == FAIL || (ctrl_x_mode != CTRL_X_NORMAL
3117 && !ctrl_x_mode_line_or_eval()))
3118 i = ins_compl_make_cyclic();
3119
3120 if (compl_old_match != NULL)
3121 {
3122 // If several matches were added (FORWARD) or the search failed and has
3123 // just been made cyclic then we have to move compl_curr_match to the
3124 // next or previous entry (if any) -- Acevedo
3125 compl_curr_match = compl_direction == FORWARD ? compl_old_match->cp_next
3126 : compl_old_match->cp_prev;
3127 if (compl_curr_match == NULL)
3128 compl_curr_match = compl_old_match;
3129 }
3130 return i;
3131}
3132
3133/*
3134 * Delete the old text being completed.
3135 */
3136 void
3137ins_compl_delete(void)
3138{
3139 int col;
3140
3141 // In insert mode: Delete the typed part.
3142 // In replace mode: Put the old characters back, if any.
3143 col = compl_col + (compl_cont_status & CONT_ADDING ? compl_length : 0);
3144 if ((int)curwin->w_cursor.col > col)
3145 {
3146 if (stop_arrow() == FAIL)
3147 return;
3148 backspace_until_column(col);
3149 }
3150
3151 // TODO: is this sufficient for redrawing? Redrawing everything causes
3152 // flicker, thus we can't do that.
3153 changed_cline_bef_curs();
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003154#ifdef FEAT_EVAL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003155 // clear v:completed_item
3156 set_vim_var_dict(VV_COMPLETED_ITEM, dict_alloc_lock(VAR_FIXED));
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003157#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003158}
3159
3160/*
3161 * Insert the new text being completed.
3162 * "in_compl_func" is TRUE when called from complete_check().
3163 */
3164 void
3165ins_compl_insert(int in_compl_func)
3166{
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003167 ins_bytes(compl_shown_match->cp_str + ins_compl_len());
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003168 if (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003169 compl_used_match = FALSE;
3170 else
3171 compl_used_match = TRUE;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003172#ifdef FEAT_EVAL
3173 {
3174 dict_T *dict = ins_compl_dict_alloc(compl_shown_match);
3175
3176 set_vim_var_dict(VV_COMPLETED_ITEM, dict);
3177 }
3178#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003179 if (!in_compl_func)
3180 compl_curr_match = compl_shown_match;
3181}
3182
3183/*
3184 * Fill in the next completion in the current direction.
3185 * If "allow_get_expansion" is TRUE, then we may call ins_compl_get_exp() to
3186 * get more completions. If it is FALSE, then we just do nothing when there
3187 * are no more completions in a given direction. The latter case is used when
3188 * we are still in the middle of finding completions, to allow browsing
3189 * through the ones found so far.
3190 * Return the total number of matches, or -1 if still unknown -- webb.
3191 *
3192 * compl_curr_match is currently being used by ins_compl_get_exp(), so we use
3193 * compl_shown_match here.
3194 *
3195 * Note that this function may be called recursively once only. First with
3196 * "allow_get_expansion" TRUE, which calls ins_compl_get_exp(), which in turn
3197 * calls this function with "allow_get_expansion" FALSE.
3198 */
3199 static int
3200ins_compl_next(
3201 int allow_get_expansion,
3202 int count, // repeat completion this many times; should
3203 // be at least 1
3204 int insert_match, // Insert the newly selected match
3205 int in_compl_func) // called from complete_check()
3206{
3207 int num_matches = -1;
3208 int todo = count;
3209 compl_T *found_compl = NULL;
3210 int found_end = FALSE;
3211 int advance;
3212 int started = compl_started;
3213
3214 // When user complete function return -1 for findstart which is next
3215 // time of 'always', compl_shown_match become NULL.
3216 if (compl_shown_match == NULL)
3217 return -1;
3218
3219 if (compl_leader != NULL
Bram Moolenaar28976e22021-01-29 21:07:07 +01003220 && (compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003221 {
3222 // Set "compl_shown_match" to the actually shown match, it may differ
3223 // when "compl_leader" is used to omit some of the matches.
3224 while (!ins_compl_equal(compl_shown_match,
3225 compl_leader, (int)STRLEN(compl_leader))
3226 && compl_shown_match->cp_next != NULL
3227 && compl_shown_match->cp_next != compl_first_match)
3228 compl_shown_match = compl_shown_match->cp_next;
3229
3230 // If we didn't find it searching forward, and compl_shows_dir is
3231 // backward, find the last match.
3232 if (compl_shows_dir == BACKWARD
3233 && !ins_compl_equal(compl_shown_match,
3234 compl_leader, (int)STRLEN(compl_leader))
3235 && (compl_shown_match->cp_next == NULL
3236 || compl_shown_match->cp_next == compl_first_match))
3237 {
3238 while (!ins_compl_equal(compl_shown_match,
3239 compl_leader, (int)STRLEN(compl_leader))
3240 && compl_shown_match->cp_prev != NULL
3241 && compl_shown_match->cp_prev != compl_first_match)
3242 compl_shown_match = compl_shown_match->cp_prev;
3243 }
3244 }
3245
3246 if (allow_get_expansion && insert_match
3247 && (!(compl_get_longest || compl_restarting) || compl_used_match))
3248 // Delete old text to be replaced
3249 ins_compl_delete();
3250
3251 // When finding the longest common text we stick at the original text,
3252 // don't let CTRL-N or CTRL-P move to the first match.
3253 advance = count != 1 || !allow_get_expansion || !compl_get_longest;
3254
3255 // When restarting the search don't insert the first match either.
3256 if (compl_restarting)
3257 {
3258 advance = FALSE;
3259 compl_restarting = FALSE;
3260 }
3261
3262 // Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap
3263 // around.
3264 while (--todo >= 0)
3265 {
3266 if (compl_shows_dir == FORWARD && compl_shown_match->cp_next != NULL)
3267 {
3268 compl_shown_match = compl_shown_match->cp_next;
3269 found_end = (compl_first_match != NULL
3270 && (compl_shown_match->cp_next == compl_first_match
3271 || compl_shown_match == compl_first_match));
3272 }
3273 else if (compl_shows_dir == BACKWARD
3274 && compl_shown_match->cp_prev != NULL)
3275 {
3276 found_end = (compl_shown_match == compl_first_match);
3277 compl_shown_match = compl_shown_match->cp_prev;
3278 found_end |= (compl_shown_match == compl_first_match);
3279 }
3280 else
3281 {
3282 if (!allow_get_expansion)
3283 {
3284 if (advance)
3285 {
3286 if (compl_shows_dir == BACKWARD)
3287 compl_pending -= todo + 1;
3288 else
3289 compl_pending += todo + 1;
3290 }
3291 return -1;
3292 }
3293
3294 if (!compl_no_select && advance)
3295 {
3296 if (compl_shows_dir == BACKWARD)
3297 --compl_pending;
3298 else
3299 ++compl_pending;
3300 }
3301
3302 // Find matches.
3303 num_matches = ins_compl_get_exp(&compl_startpos);
3304
3305 // handle any pending completions
3306 while (compl_pending != 0 && compl_direction == compl_shows_dir
3307 && advance)
3308 {
3309 if (compl_pending > 0 && compl_shown_match->cp_next != NULL)
3310 {
3311 compl_shown_match = compl_shown_match->cp_next;
3312 --compl_pending;
3313 }
3314 if (compl_pending < 0 && compl_shown_match->cp_prev != NULL)
3315 {
3316 compl_shown_match = compl_shown_match->cp_prev;
3317 ++compl_pending;
3318 }
3319 else
3320 break;
3321 }
3322 found_end = FALSE;
3323 }
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003324 if ((compl_shown_match->cp_flags & CP_ORIGINAL_TEXT) == 0
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003325 && compl_leader != NULL
3326 && !ins_compl_equal(compl_shown_match,
3327 compl_leader, (int)STRLEN(compl_leader)))
3328 ++todo;
3329 else
3330 // Remember a matching item.
3331 found_compl = compl_shown_match;
3332
3333 // Stop at the end of the list when we found a usable match.
3334 if (found_end)
3335 {
3336 if (found_compl != NULL)
3337 {
3338 compl_shown_match = found_compl;
3339 break;
3340 }
3341 todo = 1; // use first usable match after wrapping around
3342 }
3343 }
3344
3345 // Insert the text of the new completion, or the compl_leader.
3346 if (compl_no_insert && !started)
3347 {
3348 ins_bytes(compl_orig_text + ins_compl_len());
3349 compl_used_match = FALSE;
3350 }
3351 else if (insert_match)
3352 {
3353 if (!compl_get_longest || compl_used_match)
3354 ins_compl_insert(in_compl_func);
3355 else
3356 ins_bytes(compl_leader + ins_compl_len());
3357 }
3358 else
3359 compl_used_match = FALSE;
3360
3361 if (!allow_get_expansion)
3362 {
3363 // may undisplay the popup menu first
3364 ins_compl_upd_pum();
3365
3366 if (pum_enough_matches())
3367 // Will display the popup menu, don't redraw yet to avoid flicker.
3368 pum_call_update_screen();
3369 else
3370 // Not showing the popup menu yet, redraw to show the user what was
3371 // inserted.
3372 update_screen(0);
3373
3374 // display the updated popup menu
3375 ins_compl_show_pum();
3376#ifdef FEAT_GUI
3377 if (gui.in_use)
3378 {
3379 // Show the cursor after the match, not after the redrawn text.
3380 setcursor();
3381 out_flush_cursor(FALSE, FALSE);
3382 }
3383#endif
3384
3385 // Delete old text to be replaced, since we're still searching and
3386 // don't want to match ourselves!
3387 ins_compl_delete();
3388 }
3389
3390 // Enter will select a match when the match wasn't inserted and the popup
3391 // menu is visible.
3392 if (compl_no_insert && !started)
3393 compl_enter_selects = TRUE;
3394 else
3395 compl_enter_selects = !insert_match && compl_match_array != NULL;
3396
3397 // Show the file name for the match (if any)
3398 // Truncate the file name to avoid a wait for return.
3399 if (compl_shown_match->cp_fname != NULL)
3400 {
3401 char *lead = _("match in file");
3402 int space = sc_col - vim_strsize((char_u *)lead) - 2;
3403 char_u *s;
3404 char_u *e;
3405
3406 if (space > 0)
3407 {
3408 // We need the tail that fits. With double-byte encoding going
3409 // back from the end is very slow, thus go from the start and keep
3410 // the text that fits in "space" between "s" and "e".
3411 for (s = e = compl_shown_match->cp_fname; *e != NUL; MB_PTR_ADV(e))
3412 {
3413 space -= ptr2cells(e);
3414 while (space < 0)
3415 {
3416 space += ptr2cells(s);
3417 MB_PTR_ADV(s);
3418 }
3419 }
Bram Moolenaarcc233582020-12-12 13:32:07 +01003420 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003421 vim_snprintf((char *)IObuff, IOSIZE, "%s %s%s", lead,
3422 s > compl_shown_match->cp_fname ? "<" : "", s);
3423 msg((char *)IObuff);
Bram Moolenaarcc233582020-12-12 13:32:07 +01003424 msg_hist_off = FALSE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003425 redraw_cmdline = FALSE; // don't overwrite!
3426 }
3427 }
3428
3429 return num_matches;
3430}
3431
3432/*
3433 * Call this while finding completions, to check whether the user has hit a key
3434 * that should change the currently displayed completion, or exit completion
3435 * mode. Also, when compl_pending is not zero, show a completion as soon as
3436 * possible. -- webb
3437 * "frequency" specifies out of how many calls we actually check.
3438 * "in_compl_func" is TRUE when called from complete_check(), don't set
3439 * compl_curr_match.
3440 */
3441 void
3442ins_compl_check_keys(int frequency, int in_compl_func)
3443{
3444 static int count = 0;
3445 int c;
3446
3447 // Don't check when reading keys from a script, :normal or feedkeys().
3448 // That would break the test scripts. But do check for keys when called
3449 // from complete_check().
3450 if (!in_compl_func && (using_script() || ex_normal_busy))
3451 return;
3452
3453 // Only do this at regular intervals
3454 if (++count < frequency)
3455 return;
3456 count = 0;
3457
3458 // Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key()
3459 // can't do its work correctly.
3460 c = vpeekc_any();
3461 if (c != NUL)
3462 {
3463 if (vim_is_ctrl_x_key(c) && c != Ctrl_X && c != Ctrl_R)
3464 {
3465 c = safe_vgetc(); // Eat the character
3466 compl_shows_dir = ins_compl_key2dir(c);
3467 (void)ins_compl_next(FALSE, ins_compl_key2count(c),
3468 c != K_UP && c != K_DOWN, in_compl_func);
3469 }
3470 else
3471 {
3472 // Need to get the character to have KeyTyped set. We'll put it
3473 // back with vungetc() below. But skip K_IGNORE.
3474 c = safe_vgetc();
3475 if (c != K_IGNORE)
3476 {
3477 // Don't interrupt completion when the character wasn't typed,
3478 // e.g., when doing @q to replay keys.
3479 if (c != Ctrl_R && KeyTyped)
3480 compl_interrupted = TRUE;
3481
3482 vungetc(c);
3483 }
3484 }
3485 }
3486 if (compl_pending != 0 && !got_int && !compl_no_insert)
3487 {
3488 int todo = compl_pending > 0 ? compl_pending : -compl_pending;
3489
3490 compl_pending = 0;
3491 (void)ins_compl_next(FALSE, todo, TRUE, in_compl_func);
3492 }
3493}
3494
3495/*
3496 * Decide the direction of Insert mode complete from the key typed.
3497 * Returns BACKWARD or FORWARD.
3498 */
3499 static int
3500ins_compl_key2dir(int c)
3501{
3502 if (c == Ctrl_P || c == Ctrl_L
3503 || c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP || c == K_UP)
3504 return BACKWARD;
3505 return FORWARD;
3506}
3507
3508/*
3509 * Return TRUE for keys that are used for completion only when the popup menu
3510 * is visible.
3511 */
3512 static int
3513ins_compl_pum_key(int c)
3514{
3515 return pum_visible() && (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP
3516 || c == K_PAGEDOWN || c == K_KPAGEDOWN || c == K_S_DOWN
3517 || c == K_UP || c == K_DOWN);
3518}
3519
3520/*
3521 * Decide the number of completions to move forward.
3522 * Returns 1 for most keys, height of the popup menu for page-up/down keys.
3523 */
3524 static int
3525ins_compl_key2count(int c)
3526{
3527 int h;
3528
3529 if (ins_compl_pum_key(c) && c != K_UP && c != K_DOWN)
3530 {
3531 h = pum_get_height();
3532 if (h > 3)
3533 h -= 2; // keep some context
3534 return h;
3535 }
3536 return 1;
3537}
3538
3539/*
3540 * Return TRUE if completion with "c" should insert the match, FALSE if only
3541 * to change the currently selected completion.
3542 */
3543 static int
3544ins_compl_use_match(int c)
3545{
3546 switch (c)
3547 {
3548 case K_UP:
3549 case K_DOWN:
3550 case K_PAGEDOWN:
3551 case K_KPAGEDOWN:
3552 case K_S_DOWN:
3553 case K_PAGEUP:
3554 case K_KPAGEUP:
3555 case K_S_UP:
3556 return FALSE;
3557 }
3558 return TRUE;
3559}
3560
3561/*
3562 * Do Insert mode completion.
3563 * Called when character "c" was typed, which has a meaning for completion.
3564 * Returns OK if completion was done, FAIL if something failed (out of mem).
3565 */
3566 int
3567ins_complete(int c, int enable_pum)
3568{
3569 char_u *line;
3570 int startcol = 0; // column where searched text starts
3571 colnr_T curs_col; // cursor column
3572 int n;
3573 int save_w_wrow;
3574 int save_w_leftcol;
3575 int insert_match;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003576#ifdef FEAT_COMPL_FUNC
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003577 int save_did_ai = did_ai;
Bram Moolenaar9cb698d2019-08-21 15:30:45 +02003578#endif
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003579 int flags = CP_ORIGINAL_TEXT;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003580
3581 compl_direction = ins_compl_key2dir(c);
3582 insert_match = ins_compl_use_match(c);
3583
3584 if (!compl_started)
3585 {
3586 // First time we hit ^N or ^P (in a row, I mean)
3587
3588 did_ai = FALSE;
3589#ifdef FEAT_SMARTINDENT
3590 did_si = FALSE;
3591 can_si = FALSE;
3592 can_si_back = FALSE;
3593#endif
3594 if (stop_arrow() == FAIL)
3595 return FAIL;
3596
3597 line = ml_get(curwin->w_cursor.lnum);
3598 curs_col = curwin->w_cursor.col;
3599 compl_pending = 0;
3600
3601 // If this same ctrl_x_mode has been interrupted use the text from
3602 // "compl_startpos" to the cursor as a pattern to add a new word
3603 // instead of expand the one before the cursor, in word-wise if
3604 // "compl_startpos" is not in the same line as the cursor then fix it
3605 // (the line has been split because it was longer than 'tw'). if SOL
3606 // is set then skip the previous pattern, a word at the beginning of
3607 // the line has been inserted, we'll look for that -- Acevedo.
3608 if ((compl_cont_status & CONT_INTRPT) == CONT_INTRPT
3609 && compl_cont_mode == ctrl_x_mode)
3610 {
3611 // it is a continued search
3612 compl_cont_status &= ~CONT_INTRPT; // remove INTRPT
3613 if (ctrl_x_mode == CTRL_X_NORMAL
3614 || ctrl_x_mode == CTRL_X_PATH_PATTERNS
3615 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3616 {
3617 if (compl_startpos.lnum != curwin->w_cursor.lnum)
3618 {
3619 // line (probably) wrapped, set compl_startpos to the
3620 // first non_blank in the line, if it is not a wordchar
3621 // include it to get a better pattern, but then we don't
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01003622 // want the "\\<" prefix, check it below
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003623 compl_col = (colnr_T)getwhitecols(line);
3624 compl_startpos.col = compl_col;
3625 compl_startpos.lnum = curwin->w_cursor.lnum;
3626 compl_cont_status &= ~CONT_SOL; // clear SOL if present
3627 }
3628 else
3629 {
3630 // S_IPOS was set when we inserted a word that was at the
3631 // beginning of the line, which means that we'll go to SOL
3632 // mode but first we need to redefine compl_startpos
3633 if (compl_cont_status & CONT_S_IPOS)
3634 {
3635 compl_cont_status |= CONT_SOL;
3636 compl_startpos.col = (colnr_T)(skipwhite(
3637 line + compl_length
3638 + compl_startpos.col) - line);
3639 }
3640 compl_col = compl_startpos.col;
3641 }
3642 compl_length = curwin->w_cursor.col - (int)compl_col;
3643 // IObuff is used to add a "word from the next line" would we
3644 // have enough space? just being paranoid
3645#define MIN_SPACE 75
3646 if (compl_length > (IOSIZE - MIN_SPACE))
3647 {
3648 compl_cont_status &= ~CONT_SOL;
3649 compl_length = (IOSIZE - MIN_SPACE);
3650 compl_col = curwin->w_cursor.col - compl_length;
3651 }
3652 compl_cont_status |= CONT_ADDING | CONT_N_ADDS;
3653 if (compl_length < 1)
3654 compl_cont_status &= CONT_LOCAL;
3655 }
3656 else if (ctrl_x_mode_line_or_eval())
3657 compl_cont_status = CONT_ADDING | CONT_N_ADDS;
3658 else
3659 compl_cont_status = 0;
3660 }
3661 else
3662 compl_cont_status &= CONT_LOCAL;
3663
3664 if (!(compl_cont_status & CONT_ADDING)) // normal expansion
3665 {
3666 compl_cont_mode = ctrl_x_mode;
3667 if (ctrl_x_mode != CTRL_X_NORMAL)
3668 // Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL
3669 compl_cont_status = 0;
3670 compl_cont_status |= CONT_N_ADDS;
3671 compl_startpos = curwin->w_cursor;
3672 startcol = (int)curs_col;
3673 compl_col = 0;
3674 }
3675
3676 // Work out completion pattern and original text -- webb
3677 if (ctrl_x_mode == CTRL_X_NORMAL || (ctrl_x_mode & CTRL_X_WANT_IDENT))
3678 {
3679 if ((compl_cont_status & CONT_SOL)
3680 || ctrl_x_mode == CTRL_X_PATH_DEFINES)
3681 {
3682 if (!(compl_cont_status & CONT_ADDING))
3683 {
3684 while (--startcol >= 0 && vim_isIDc(line[startcol]))
3685 ;
3686 compl_col += ++startcol;
3687 compl_length = curs_col - startcol;
3688 }
3689 if (p_ic)
3690 compl_pattern = str_foldcase(line + compl_col,
3691 compl_length, NULL, 0);
3692 else
3693 compl_pattern = vim_strnsave(line + compl_col,
3694 compl_length);
3695 if (compl_pattern == NULL)
3696 return FAIL;
3697 }
3698 else if (compl_cont_status & CONT_ADDING)
3699 {
3700 char_u *prefix = (char_u *)"\\<";
3701
3702 // we need up to 2 extra chars for the prefix
3703 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3704 compl_length) + 2);
3705 if (compl_pattern == NULL)
3706 return FAIL;
3707 if (!vim_iswordp(line + compl_col)
3708 || (compl_col > 0
3709 && (vim_iswordp(mb_prevptr(line, line + compl_col)))))
3710 prefix = (char_u *)"";
3711 STRCPY((char *)compl_pattern, prefix);
3712 (void)quote_meta(compl_pattern + STRLEN(prefix),
3713 line + compl_col, compl_length);
3714 }
3715 else if (--startcol < 0
3716 || !vim_iswordp(mb_prevptr(line, line + startcol + 1)))
3717 {
3718 // Match any word of at least two chars
3719 compl_pattern = vim_strsave((char_u *)"\\<\\k\\k");
3720 if (compl_pattern == NULL)
3721 return FAIL;
3722 compl_col += curs_col;
3723 compl_length = 0;
3724 }
3725 else
3726 {
3727 // Search the point of change class of multibyte character
3728 // or not a word single byte character backward.
3729 if (has_mbyte)
3730 {
3731 int base_class;
3732 int head_off;
3733
3734 startcol -= (*mb_head_off)(line, line + startcol);
3735 base_class = mb_get_class(line + startcol);
3736 while (--startcol >= 0)
3737 {
3738 head_off = (*mb_head_off)(line, line + startcol);
3739 if (base_class != mb_get_class(line + startcol
3740 - head_off))
3741 break;
3742 startcol -= head_off;
3743 }
3744 }
3745 else
3746 while (--startcol >= 0 && vim_iswordc(line[startcol]))
3747 ;
3748 compl_col += ++startcol;
3749 compl_length = (int)curs_col - startcol;
3750 if (compl_length == 1)
3751 {
3752 // Only match word with at least two chars -- webb
3753 // there's no need to call quote_meta,
3754 // alloc(7) is enough -- Acevedo
3755 compl_pattern = alloc(7);
3756 if (compl_pattern == NULL)
3757 return FAIL;
3758 STRCPY((char *)compl_pattern, "\\<");
3759 (void)quote_meta(compl_pattern + 2, line + compl_col, 1);
3760 STRCAT((char *)compl_pattern, "\\k");
3761 }
3762 else
3763 {
3764 compl_pattern = alloc(quote_meta(NULL, line + compl_col,
3765 compl_length) + 2);
3766 if (compl_pattern == NULL)
3767 return FAIL;
3768 STRCPY((char *)compl_pattern, "\\<");
3769 (void)quote_meta(compl_pattern + 2, line + compl_col,
3770 compl_length);
3771 }
3772 }
3773 }
3774 else if (ctrl_x_mode_line_or_eval())
3775 {
3776 compl_col = (colnr_T)getwhitecols(line);
3777 compl_length = (int)curs_col - (int)compl_col;
3778 if (compl_length < 0) // cursor in indent: empty pattern
3779 compl_length = 0;
3780 if (p_ic)
3781 compl_pattern = str_foldcase(line + compl_col, compl_length,
3782 NULL, 0);
3783 else
3784 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3785 if (compl_pattern == NULL)
3786 return FAIL;
3787 }
3788 else if (ctrl_x_mode == CTRL_X_FILES)
3789 {
3790 // Go back to just before the first filename character.
3791 if (startcol > 0)
3792 {
3793 char_u *p = line + startcol;
3794
3795 MB_PTR_BACK(line, p);
3796 while (p > line && vim_isfilec(PTR2CHAR(p)))
3797 MB_PTR_BACK(line, p);
3798 if (p == line && vim_isfilec(PTR2CHAR(p)))
3799 startcol = 0;
3800 else
3801 startcol = (int)(p - line) + 1;
3802 }
3803
3804 compl_col += startcol;
3805 compl_length = (int)curs_col - startcol;
3806 compl_pattern = addstar(line + compl_col, compl_length,
3807 EXPAND_FILES);
3808 if (compl_pattern == NULL)
3809 return FAIL;
3810 }
3811 else if (ctrl_x_mode == CTRL_X_CMDLINE)
3812 {
3813 compl_pattern = vim_strnsave(line, curs_col);
3814 if (compl_pattern == NULL)
3815 return FAIL;
3816 set_cmd_context(&compl_xp, compl_pattern,
3817 (int)STRLEN(compl_pattern), curs_col, FALSE);
3818 if (compl_xp.xp_context == EXPAND_UNSUCCESSFUL
3819 || compl_xp.xp_context == EXPAND_NOTHING)
3820 // No completion possible, use an empty pattern to get a
3821 // "pattern not found" message.
3822 compl_col = curs_col;
3823 else
3824 compl_col = (int)(compl_xp.xp_pattern - compl_pattern);
3825 compl_length = curs_col - compl_col;
3826 }
3827 else if (ctrl_x_mode == CTRL_X_FUNCTION || ctrl_x_mode == CTRL_X_OMNI)
3828 {
3829#ifdef FEAT_COMPL_FUNC
3830 // Call user defined function 'completefunc' with "a:findstart"
3831 // set to 1 to obtain the length of text to use for completion.
3832 typval_T args[3];
3833 int col;
3834 char_u *funcname;
3835 pos_T pos;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003836 int save_State = State;
3837
3838 // Call 'completefunc' or 'omnifunc' and get pattern length as a
3839 // string
3840 funcname = ctrl_x_mode == CTRL_X_FUNCTION
3841 ? curbuf->b_p_cfu : curbuf->b_p_ofu;
3842 if (*funcname == NUL)
3843 {
3844 semsg(_(e_notset), ctrl_x_mode == CTRL_X_FUNCTION
3845 ? "completefunc" : "omnifunc");
3846 // restore did_ai, so that adding comment leader works
3847 did_ai = save_did_ai;
3848 return FAIL;
3849 }
3850
3851 args[0].v_type = VAR_NUMBER;
3852 args[0].vval.v_number = 1;
3853 args[1].v_type = VAR_STRING;
3854 args[1].vval.v_string = (char_u *)"";
3855 args[2].v_type = VAR_UNKNOWN;
3856 pos = curwin->w_cursor;
Bram Moolenaar3eb6bd92021-01-29 21:47:24 +01003857 ++textwinlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003858 col = call_func_retnr(funcname, 2, args);
Bram Moolenaar3eb6bd92021-01-29 21:47:24 +01003859 --textwinlock;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003860
3861 State = save_State;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003862 curwin->w_cursor = pos; // restore the cursor position
3863 validate_cursor();
3864 if (!EQUAL_POS(curwin->w_cursor, pos))
3865 {
3866 emsg(_(e_compldel));
3867 return FAIL;
3868 }
3869
3870 // Return value -2 means the user complete function wants to
3871 // cancel the complete without an error.
3872 // Return value -3 does the same as -2 and leaves CTRL-X mode.
3873 if (col == -2)
3874 return FAIL;
3875 if (col == -3)
3876 {
3877 ctrl_x_mode = CTRL_X_NORMAL;
3878 edit_submode = NULL;
3879 if (!shortmess(SHM_COMPLETIONMENU))
3880 msg_clr_cmdline();
3881 return FAIL;
3882 }
3883
3884 // Reset extended parameters of completion, when start new
3885 // completion.
3886 compl_opt_refresh_always = FALSE;
3887 compl_opt_suppress_empty = FALSE;
3888
3889 if (col < 0)
3890 col = curs_col;
3891 compl_col = col;
3892 if (compl_col > curs_col)
3893 compl_col = curs_col;
3894
3895 // Setup variables for completion. Need to obtain "line" again,
3896 // it may have become invalid.
3897 line = ml_get(curwin->w_cursor.lnum);
3898 compl_length = curs_col - compl_col;
3899 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3900 if (compl_pattern == NULL)
3901#endif
3902 return FAIL;
3903 }
3904 else if (ctrl_x_mode == CTRL_X_SPELL)
3905 {
3906#ifdef FEAT_SPELL
3907 if (spell_bad_len > 0)
3908 compl_col = curs_col - spell_bad_len;
3909 else
3910 compl_col = spell_word_start(startcol);
3911 if (compl_col >= (colnr_T)startcol)
3912 {
3913 compl_length = 0;
3914 compl_col = curs_col;
3915 }
3916 else
3917 {
3918 spell_expand_check_cap(compl_col);
3919 compl_length = (int)curs_col - compl_col;
3920 }
3921 // Need to obtain "line" again, it may have become invalid.
3922 line = ml_get(curwin->w_cursor.lnum);
3923 compl_pattern = vim_strnsave(line + compl_col, compl_length);
3924 if (compl_pattern == NULL)
3925#endif
3926 return FAIL;
3927 }
3928 else
3929 {
3930 internal_error("ins_complete()");
3931 return FAIL;
3932 }
3933
3934 if (compl_cont_status & CONT_ADDING)
3935 {
3936 edit_submode_pre = (char_u *)_(" Adding");
3937 if (ctrl_x_mode_line_or_eval())
3938 {
3939 // Insert a new line, keep indentation but ignore 'comments'
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003940 char_u *old = curbuf->b_p_com;
3941
3942 curbuf->b_p_com = (char_u *)"";
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003943 compl_startpos.lnum = curwin->w_cursor.lnum;
3944 compl_startpos.col = compl_col;
3945 ins_eol('\r');
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003946 curbuf->b_p_com = old;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003947 compl_length = 0;
3948 compl_col = curwin->w_cursor.col;
3949 }
3950 }
3951 else
3952 {
3953 edit_submode_pre = NULL;
3954 compl_startpos.col = compl_col;
3955 }
3956
3957 if (compl_cont_status & CONT_LOCAL)
3958 edit_submode = (char_u *)_(ctrl_x_msgs[CTRL_X_LOCAL_MSG]);
3959 else
3960 edit_submode = (char_u *)_(CTRL_X_MSG(ctrl_x_mode));
3961
3962 // If any of the original typed text has been changed we need to fix
3963 // the redo buffer.
3964 ins_compl_fixRedoBufForLeader(NULL);
3965
3966 // Always add completion for the original text.
3967 vim_free(compl_orig_text);
3968 compl_orig_text = vim_strnsave(line + compl_col, compl_length);
Bram Moolenaard9eefe32019-04-06 14:22:21 +02003969 if (p_ic)
3970 flags |= CP_ICASE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003971 if (compl_orig_text == NULL || ins_compl_add(compl_orig_text,
Bram Moolenaar08928322020-01-04 14:32:48 +01003972 -1, NULL, NULL, NULL, 0, flags, FALSE) != OK)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01003973 {
3974 VIM_CLEAR(compl_pattern);
3975 VIM_CLEAR(compl_orig_text);
3976 return FAIL;
3977 }
3978
3979 // showmode might reset the internal line pointers, so it must
3980 // be called before line = ml_get(), or when this address is no
3981 // longer needed. -- Acevedo.
3982 edit_submode_extra = (char_u *)_("-- Searching...");
3983 edit_submode_highl = HLF_COUNT;
3984 showmode();
3985 edit_submode_extra = NULL;
3986 out_flush();
3987 }
3988 else if (insert_match && stop_arrow() == FAIL)
3989 return FAIL;
3990
3991 compl_shown_match = compl_curr_match;
3992 compl_shows_dir = compl_direction;
3993
3994 // Find next match (and following matches).
3995 save_w_wrow = curwin->w_wrow;
3996 save_w_leftcol = curwin->w_leftcol;
3997 n = ins_compl_next(TRUE, ins_compl_key2count(c), insert_match, FALSE);
3998
3999 // may undisplay the popup menu
4000 ins_compl_upd_pum();
4001
4002 if (n > 1) // all matches have been found
4003 compl_matches = n;
4004 compl_curr_match = compl_shown_match;
4005 compl_direction = compl_shows_dir;
4006
4007 // Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert
4008 // mode.
4009 if (got_int && !global_busy)
4010 {
4011 (void)vgetc();
4012 got_int = FALSE;
4013 }
4014
4015 // we found no match if the list has only the "compl_orig_text"-entry
4016 if (compl_first_match == compl_first_match->cp_next)
4017 {
4018 edit_submode_extra = (compl_cont_status & CONT_ADDING)
4019 && compl_length > 1
4020 ? (char_u *)_(e_hitend) : (char_u *)_(e_patnotf);
4021 edit_submode_highl = HLF_E;
4022 // remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode,
4023 // because we couldn't expand anything at first place, but if we used
4024 // ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word
4025 // (such as M in M'exico) if not tried already. -- Acevedo
4026 if ( compl_length > 1
4027 || (compl_cont_status & CONT_ADDING)
4028 || (ctrl_x_mode != CTRL_X_NORMAL
4029 && ctrl_x_mode != CTRL_X_PATH_PATTERNS
4030 && ctrl_x_mode != CTRL_X_PATH_DEFINES))
4031 compl_cont_status &= ~CONT_N_ADDS;
4032 }
4033
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004034 if (compl_curr_match->cp_flags & CP_CONT_S_IPOS)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004035 compl_cont_status |= CONT_S_IPOS;
4036 else
4037 compl_cont_status &= ~CONT_S_IPOS;
4038
4039 if (edit_submode_extra == NULL)
4040 {
Bram Moolenaard9eefe32019-04-06 14:22:21 +02004041 if (compl_curr_match->cp_flags & CP_ORIGINAL_TEXT)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004042 {
4043 edit_submode_extra = (char_u *)_("Back at original");
4044 edit_submode_highl = HLF_W;
4045 }
4046 else if (compl_cont_status & CONT_S_IPOS)
4047 {
4048 edit_submode_extra = (char_u *)_("Word from other line");
4049 edit_submode_highl = HLF_COUNT;
4050 }
4051 else if (compl_curr_match->cp_next == compl_curr_match->cp_prev)
4052 {
4053 edit_submode_extra = (char_u *)_("The only match");
4054 edit_submode_highl = HLF_COUNT;
Bram Moolenaarf9d51352020-10-26 19:22:42 +01004055 compl_curr_match->cp_number = 1;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004056 }
4057 else
4058 {
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01004059#if defined(FEAT_COMPL_FUNC) || defined(FEAT_EVAL)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004060 // Update completion sequence number when needed.
4061 if (compl_curr_match->cp_number == -1)
Bram Moolenaarf9d51352020-10-26 19:22:42 +01004062 ins_compl_update_sequence_numbers();
Bram Moolenaar977fd0b2020-10-27 09:12:45 +01004063#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004064 // The match should always have a sequence number now, this is
4065 // just a safety check.
4066 if (compl_curr_match->cp_number != -1)
4067 {
4068 // Space for 10 text chars. + 2x10-digit no.s = 31.
4069 // Translations may need more than twice that.
4070 static char_u match_ref[81];
4071
4072 if (compl_matches > 0)
4073 vim_snprintf((char *)match_ref, sizeof(match_ref),
4074 _("match %d of %d"),
4075 compl_curr_match->cp_number, compl_matches);
4076 else
4077 vim_snprintf((char *)match_ref, sizeof(match_ref),
4078 _("match %d"),
4079 compl_curr_match->cp_number);
4080 edit_submode_extra = match_ref;
4081 edit_submode_highl = HLF_R;
4082 if (dollar_vcol >= 0)
4083 curs_columns(FALSE);
4084 }
4085 }
4086 }
4087
4088 // Show a message about what (completion) mode we're in.
4089 if (!compl_opt_suppress_empty)
4090 {
4091 showmode();
4092 if (!shortmess(SHM_COMPLETIONMENU))
4093 {
4094 if (edit_submode_extra != NULL)
4095 {
4096 if (!p_smd)
Bram Moolenaarcc233582020-12-12 13:32:07 +01004097 {
4098 msg_hist_off = TRUE;
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004099 msg_attr((char *)edit_submode_extra,
4100 edit_submode_highl < HLF_COUNT
4101 ? HL_ATTR(edit_submode_highl) : 0);
Bram Moolenaarcc233582020-12-12 13:32:07 +01004102 msg_hist_off = FALSE;
4103 }
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004104 }
4105 else
4106 msg_clr_cmdline(); // necessary for "noshowmode"
4107 }
4108 }
4109
4110 // Show the popup menu, unless we got interrupted.
4111 if (enable_pum && !compl_interrupted)
4112 show_pum(save_w_wrow, save_w_leftcol);
4113
4114 compl_was_interrupted = compl_interrupted;
4115 compl_interrupted = FALSE;
4116
4117 return OK;
4118}
4119
4120 static void
4121show_pum(int prev_w_wrow, int prev_w_leftcol)
4122{
4123 // RedrawingDisabled may be set when invoked through complete().
4124 int n = RedrawingDisabled;
4125
4126 RedrawingDisabled = 0;
4127
4128 // If the cursor moved or the display scrolled we need to remove the pum
4129 // first.
4130 setcursor();
4131 if (prev_w_wrow != curwin->w_wrow || prev_w_leftcol != curwin->w_leftcol)
4132 ins_compl_del_pum();
4133
4134 ins_compl_show_pum();
4135 setcursor();
4136 RedrawingDisabled = n;
4137}
4138
4139/*
4140 * Looks in the first "len" chars. of "src" for search-metachars.
4141 * If dest is not NULL the chars. are copied there quoting (with
4142 * a backslash) the metachars, and dest would be NUL terminated.
4143 * Returns the length (needed) of dest
4144 */
4145 static unsigned
4146quote_meta(char_u *dest, char_u *src, int len)
4147{
4148 unsigned m = (unsigned)len + 1; // one extra for the NUL
4149
4150 for ( ; --len >= 0; src++)
4151 {
4152 switch (*src)
4153 {
4154 case '.':
4155 case '*':
4156 case '[':
4157 if (ctrl_x_mode == CTRL_X_DICTIONARY
4158 || ctrl_x_mode == CTRL_X_THESAURUS)
4159 break;
4160 // FALLTHROUGH
4161 case '~':
Bram Moolenaarf4e20992020-12-21 19:59:08 +01004162 if (!magic_isset()) // quote these only if magic is set
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004163 break;
4164 // FALLTHROUGH
4165 case '\\':
4166 if (ctrl_x_mode == CTRL_X_DICTIONARY
4167 || ctrl_x_mode == CTRL_X_THESAURUS)
4168 break;
4169 // FALLTHROUGH
4170 case '^': // currently it's not needed.
4171 case '$':
4172 m++;
4173 if (dest != NULL)
4174 *dest++ = '\\';
4175 break;
4176 }
4177 if (dest != NULL)
4178 *dest++ = *src;
4179 // Copy remaining bytes of a multibyte character.
4180 if (has_mbyte)
4181 {
4182 int i, mb_len;
4183
4184 mb_len = (*mb_ptr2len)(src) - 1;
4185 if (mb_len > 0 && len >= mb_len)
4186 for (i = 0; i < mb_len; ++i)
4187 {
4188 --len;
4189 ++src;
4190 if (dest != NULL)
4191 *dest++ = *src;
4192 }
4193 }
4194 }
4195 if (dest != NULL)
4196 *dest = NUL;
4197
4198 return m;
4199}
4200
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004201#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004202 void
4203free_insexpand_stuff(void)
4204{
4205 VIM_CLEAR(compl_orig_text);
4206}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004207#endif
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004208
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004209#ifdef FEAT_SPELL
Bram Moolenaar7591bb32019-03-30 13:53:47 +01004210/*
4211 * Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly
4212 * spelled word, if there is one.
4213 */
4214 static void
4215spell_back_to_badword(void)
4216{
4217 pos_T tpos = curwin->w_cursor;
4218
4219 spell_bad_len = spell_move_to(curwin, BACKWARD, TRUE, TRUE, NULL);
4220 if (curwin->w_cursor.col != tpos.col)
4221 start_arrow(&tpos);
4222}
Bram Moolenaare2c453d2019-08-21 14:37:09 +02004223#endif