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