robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// insexpand.c: functions for Insert mode completion 2 3#include <assert.h> 4#include <limits.h> 5#include <stdbool.h> 6#include <stddef.h> 7#include <stdint.h> 8#include <stdio.h> 9#include <stdlib.h> 10#include <string.h> 11 12#include "klib/kvec.h" 13#include "nvim/api/private/helpers.h" 14#include "nvim/ascii_defs.h" 15#include "nvim/autocmd.h" 16#include "nvim/autocmd_defs.h" 17#include "nvim/buffer.h" 18#include "nvim/buffer_defs.h" 19#include "nvim/change.h" 20#include "nvim/charset.h" 21#include "nvim/cmdexpand.h" 22#include "nvim/cmdexpand_defs.h" 23#include "nvim/cursor.h" 24#include "nvim/drawscreen.h" 25#include "nvim/errors.h" 26#include "nvim/eval.h" 27#include "nvim/eval/executor.h" 28#include "nvim/eval/typval.h" 29#include "nvim/eval/typval_defs.h" 30#include "nvim/eval/userfunc.h" 31#include "nvim/eval/vars.h" 32#include "nvim/ex_eval.h" 33#include "nvim/ex_getln.h" 34#include "nvim/extmark.h" 35#include "nvim/extmark_defs.h" 36#include "nvim/fileio.h" 37#include "nvim/fuzzy.h" 38#include "nvim/garray.h" 39#include "nvim/garray_defs.h" 40#include "nvim/gettext_defs.h" 41#include "nvim/globals.h" 42#include "nvim/highlight_defs.h" 43#include "nvim/highlight_group.h" 44#include "nvim/indent.h" 45#include "nvim/indent_c.h" 46#include "nvim/input.h" 47#include "nvim/insert.h" 48#include "nvim/insexpand.h" 49#include "nvim/keycodes.h" 50#include "nvim/lua/executor.h" 51#include "nvim/macros_defs.h" 52#include "nvim/mark_defs.h" 53#include "nvim/mbyte.h" 54#include "nvim/mbyte_defs.h" 55#include "nvim/memline.h" 56#include "nvim/memory.h" 57#include "nvim/message.h" 58#include "nvim/move.h" 59#include "nvim/option.h" 60#include "nvim/option_defs.h" 61#include "nvim/option_vars.h" 62#include "nvim/os/fs.h" 63#include "nvim/os/input.h" 64#include "nvim/os/time.h" 65#include "nvim/path.h" 66#include "nvim/popupmenu.h" 67#include "nvim/pos_defs.h" 68#include "nvim/regexp.h" 69#include "nvim/regexp_defs.h" 70#include "nvim/register.h" 71#include "nvim/search.h" 72#include "nvim/spell.h" 73#include "nvim/state.h" 74#include "nvim/state_defs.h" 75#include "nvim/strings.h" 76#include "nvim/tag.h" 77#include "nvim/textformat.h" 78#include "nvim/types_defs.h" 79#include "nvim/ui.h" 80#include "nvim/undo.h" 81#include "nvim/vim_defs.h" 82#include "nvim/window.h" 83#include "nvim/winfloat.h" 84 85// Definitions used for CTRL-X submode. 86// Note: If you change CTRL-X submode, you must also maintain ctrl_x_msgs[] 87// and ctrl_x_mode_names[]. 88 89#define CTRL_X_WANT_IDENT 0x100 90 91enum { 92CTRL_X_NORMAL = 0 ,///< CTRL-N CTRL-P completion, default 93CTRL_X_NOT_DEFINED_YET = 1 , 94CTRL_X_SCROLL = 2 , 95CTRL_X_WHOLE_LINE = 3 , 96CTRL_X_FILES = 4 , 97CTRL_X_TAGS = (5 + CTRL_X_WANT_IDENT ), 98CTRL_X_PATH_PATTERNS = (6 + CTRL_X_WANT_IDENT ), 99CTRL_X_PATH_DEFINES = (7 + CTRL_X_WANT_IDENT ), 100CTRL_X_FINISHED = 8 , 101CTRL_X_DICTIONARY = (9 + CTRL_X_WANT_IDENT ), 102CTRL_X_THESAURUS = (10 + CTRL_X_WANT_IDENT ), 103CTRL_X_CMDLINE = 11 , 104CTRL_X_FUNCTION = 12 , 105CTRL_X_OMNI = 13 , 106CTRL_X_SPELL = 14 , 107CTRL_X_LOCAL_MSG = 15 ,///< only used in "ctrl_x_msgs" 108CTRL_X_EVAL = 16 ,///< for builtin function complete() 109CTRL_X_CMDLINE_CTRL_X = 17 ,///< CTRL-X typed in CTRL_X_CMDLINE 110CTRL_X_BUFNAMES = 18 , 111CTRL_X_REGISTER = 19 ,///< complete words from registers 112}; 113 114#define CTRL_X_MSG (i ) ctrl_x_msgs[(i) & ~CTRL_X_WANT_IDENT] 115 116/// Message for CTRL-X mode, index is ctrl_x_mode. 117static char * ctrl_x_msgs []= { 118N_ (" Keyword completion (^N^P)" ),// CTRL_X_NORMAL, ^P/^N compl. 119N_ (" ^X mode (^]^D^E^F^I^K^L^N^O^P^Rs^U^V^Y)" ), 120NULL ,// CTRL_X_SCROLL: depends on state 121N_ (" Whole line completion (^L^N^P)" ), 122N_ (" File name completion (^F^N^P)" ), 123N_ (" Tag completion (^]^N^P)" ), 124N_ (" Path pattern completion (^N^P)" ), 125N_ (" Definition completion (^D^N^P)" ), 126NULL ,// CTRL_X_FINISHED 127N_ (" Dictionary completion (^K^N^P)" ), 128N_ (" Thesaurus completion (^T^N^P)" ), 129N_ (" Command-line completion (^V^N^P)" ), 130N_ (" User defined completion (^U^N^P)" ), 131N_ (" Omni completion (^O^N^P)" ), 132N_ (" Spelling suggestion (^S^N^P)" ), 133N_ (" Keyword Local completion (^N^P)" ), 134NULL ,// CTRL_X_EVAL doesn't use msg. 135N_ (" Command-line completion (^V^N^P)" ), 136NULL , 137N_ (" Register completion (^N^P)" ), 138}; 139 140static String ctrl_x_mode_names []= { 141STATIC_CSTR_STRING_INIT ("keyword" ), 142STATIC_CSTR_STRING_INIT ("ctrl_x" ), 143STATIC_CSTR_STRING_INIT ("scroll" ), 144STATIC_CSTR_STRING_INIT ("whole_line" ), 145STATIC_CSTR_STRING_INIT ("files" ), 146STATIC_CSTR_STRING_INIT ("tags" ), 147STATIC_CSTR_STRING_INIT ("path_patterns" ), 148STATIC_CSTR_STRING_INIT ("path_defines" ), 149STATIC_CSTR_STRING_INIT ("unknown" ),// CTRL_X_FINISHED 150STATIC_CSTR_STRING_INIT ("dictionary" ), 151STATIC_CSTR_STRING_INIT ("thesaurus" ), 152STATIC_CSTR_STRING_INIT ("cmdline" ), 153STATIC_CSTR_STRING_INIT ("function" ), 154STATIC_CSTR_STRING_INIT ("omni" ), 155STATIC_CSTR_STRING_INIT ("spell" ), 156STRING_INIT ,// CTRL_X_LOCAL_MSG is only used in "ctrl_x_msgs" 157STATIC_CSTR_STRING_INIT ("eval" ), 158STATIC_CSTR_STRING_INIT ("cmdline" ), 159STRING_INIT ,// CTRL_X_BUFNAME 160STATIC_CSTR_STRING_INIT ("register" ), 161}; 162 163/// Structure used to store one match for insert completion. 164typedef struct compl_S compl_T ; 165struct compl_S { 166compl_T * cp_next ; 167compl_T * cp_prev ; 168compl_T * cp_match_next ;///< matched next compl_T 169String cp_str ;///< matched text 170char * (cp_text [CPT_COUNT ]);///< text for the menu 171typval_T cp_user_data ; 172char * cp_fname ;///< file containing the match, allocated when 173///< cp_flags has CP_FREE_FNAME 174char * cp_commit_chars ;///< commit characters, allocated. May be NULL. 175int cp_flags ;///< CP_ values 176int cp_number ;///< sequence number 177bool cp_preselect ;///< preselect item 178int cp_score ;///< fuzzy match score or proximity score 179bool cp_in_match_array ;///< collected by compl_match_array 180int cp_user_abbr_hl_id ;///< highlight group ID for abbr 181int cp_user_kind_hl_id ;///< highlight group ID for kind 182int cp_cpt_source_idx ;///< index of this match's source in 'cpt' option 183}; 184 185/// state information used for getting the next set of insert completion 186/// matches. 187typedef struct { 188char * e_cpt_copy ;///< copy of 'complete' 189char * e_cpt ;///< current entry in "e_cpt_copy" 190buf_T * ins_buf ;///< buffer being scanned 191pos_T * cur_match_pos ;///< current match position 192pos_T prev_match_pos ;///< previous match position 193bool set_match_pos ;///< save first_match_pos/last_match_pos 194pos_T first_match_pos ;///< first match position 195pos_T last_match_pos ;///< last match position 196bool found_all ;///< found all matches of a certain type. 197char * dict ;///< dictionary file to search 198int dict_f ;///< "dict" is an exact file name or not 199Callback * func_cb ;///< callback of function in 'cpt' option 200}ins_compl_next_state_T ; 201 202#include "insexpand.c.generated.h" 203 204/// values for cp_flags 205typedef enum { 206CP_ORIGINAL_TEXT = 1 ,///< the original text when the expansion begun 207CP_FREE_FNAME = 2 ,///< cp_fname is allocated 208CP_CONT_S_IPOS = 4 ,///< use CONT_S_IPOS for compl_cont_status 209CP_EQUAL = 8 ,///< ins_compl_equal() always returns true 210CP_ICASE = 16 ,///< ins_compl_equal ignores case 211CP_FAST = 32 ,///< use fast_breakcheck instead of os_breakcheck 212}cp_flags_T ; 213 214static const char e_compldel []= N_ ("E840: Completion function deleted text" ); 215 216// All the current matches are stored in a list. 217// "compl_first_match" points to the start of the list. 218// "compl_curr_match" points to the currently selected entry. 219// "compl_shown_match" is different from compl_curr_match during 220// ins_compl_get_exp(), when new matches are added to the list. 221// "compl_old_match" points to previous "compl_curr_match". 222 223static compl_T * compl_first_match = NULL ; 224static compl_T * compl_curr_match = NULL ; 225static compl_T * compl_shown_match = NULL ; 226static compl_T * compl_old_match = NULL ; 227static compl_T * compl_preselect_match = NULL ; 228 229/// Hashtab with the strings of the matches in the list above, except the 230/// original-text entries. Each entry owns a copy of the string and counts 231/// the matches with that string, so that when matches were added with "adup" 232/// the entry remains until the last match with the string is removed. 233typedef struct { 234int cse_count ;// number of matches with this string 235char cse_str [];// the string 236}complstr_T ; 237 238#define CSE_OFF (offsetof(complstr_T, cse_str)) 239#define HI2CSE (hi ) ((complstr_T *)((hi)->hi_key - CSE_OFF)) 240 241static hashtab_T compl_strings_ht ; 242 243/// Count the string of a new match in the duplicate-check hashtab. 244/// "hash" is the hash of "str" when it is not zero. 245static void compl_strings_add (const char * str ,size_t len ,hash_T hash ) 246{ 247if (compl_strings_ht .ht_array == NULL ) { 248hash_init (& compl_strings_ht ); 249 } 250if (hash == 0 ) { 251hash = hash_hash (str ); 252 } 253hashitem_T * hi = hash_lookup (& compl_strings_ht ,str ,len ,hash ); 254if (HASHITEM_EMPTY (hi )) { 255complstr_T * entry = xmalloc (CSE_OFF + len + 1 ); 256entry -> cse_count = 1 ; 257xmemcpyz (entry -> cse_str ,str ,len ); 258hash_add_item (& compl_strings_ht ,hi ,entry -> cse_str ,hash ); 259 }else { 260HI2CSE (hi )-> cse_count ++ ; 261 } 262} 263 264/// list used to store the compl_T which have the max score 265static compl_T ** compl_best_matches = NULL ; 266static int compl_num_bests = 0 ; 267 268/// After using a cursor key <Enter> selects a match in the popup menu, 269/// otherwise it inserts a line break. 270static bool compl_enter_selects = false; 271 272/// When "compl_leader" is not NULL only matches that start with this string 273/// are used. 274static String compl_leader = STRING_INIT ; 275 276static bool compl_get_longest = false;///< put longest common string in compl_leader 277 278/// This flag is false when no match is selected (by ^N/^P) or the match was 279/// edited or using the longest common string. 280static bool compl_used_match ; 281 282/// didn't finish finding completions. 283static bool compl_was_interrupted = false; 284 285// Set when character typed while looking for matches and it means we should 286// stop looking for matches. 287static bool compl_interrupted = false; 288 289static bool compl_restarting = false;///< don't insert match 290 291/// When the first completion is done "compl_started" is set. When it's 292/// false the word to be completed must be located. 293static bool compl_started = false; 294 295/// Which Ctrl-X mode are we in? 296static int ctrl_x_mode = CTRL_X_NORMAL ; 297 298static int compl_matches = 0 ;///< number of completion matches 299static String compl_pattern = STRING_INIT ;///< search pattern for matching items 300static String cpt_compl_pattern = STRING_INIT ;///< pattern returned by func in 'cpt' 301static Direction compl_direction = FORWARD ; 302static Direction compl_shows_dir = FORWARD ; 303static int compl_pending = 0 ;///< > 1 for postponed CTRL-N 304static pos_T compl_startpos ; 305/// Length in bytes of the text being completed (this is deleted to be replaced 306/// by the match.) 307static int compl_length = 0 ; 308static linenr_T compl_lnum = 0 ;///< lnum where the completion start 309static colnr_T compl_col = 0 ;///< column where the text starts 310///< that is being completed 311static colnr_T compl_ins_end_col = 0 ; 312static colnr_T compl_longest_end_col = 0 ;///< end of 'longest' inserted text 313static String compl_orig_text = STRING_INIT ;///< text as it was before 314///< completion started 315/// Undo information to restore extmarks for original text. 316static extmark_undo_vec_t compl_orig_extmarks ; 317static int compl_cont_mode = 0 ; 318static expand_T compl_xp ; 319 320static win_T * compl_curr_win = NULL ;///< win where completion is active 321static buf_T * compl_curr_buf = NULL ;///< buf where completion is active 322 323#define COMPL_INITIAL_TIMEOUT_MS 80 324// Autocomplete uses a decaying timeout: starting from COMPL_INITIAL_TIMEOUT_MS, 325// if the current source exceeds its timeout, it is interrupted and the next 326// begins with half the time. A small minimum timeout ensures every source 327// gets at least a brief chance. 328// Special case: when 'complete' contains "F" or "o" (function sources), a 329// longer fixed timeout is used (COMPL_FUNC_TIMEOUT_MS or 330// COMPL_FUNC_TIMEOUT_NON_KW_MS). - girish 331static bool compl_autocomplete = false;///< whether autocompletion is active 332static bool compl_autostarted = false;///< Vim started this completion 333static bool compl_autostart_pending = false;///< the trigger armed one 334static bool compl_autocomplete_pending = false; 335static uint64_t compl_autocomplete_start_tv ;///< when the delay was armed 336static uint64_t compl_timeout_ms = COMPL_INITIAL_TIMEOUT_MS ; 337static bool compl_time_slice_expired = false;///< time budget exceeded for current source 338static bool compl_from_nonkeyword = false;///< completion started from non-keyword 339static bool compl_hi_on_autocompl_longest = false;///< apply "PreInsert" highlight 340 341// Halve the current completion timeout, simulating exponential decay. 342#define COMPL_MIN_TIMEOUT_MS 5 343#define DECAY_COMPL_TIMEOUT () \ 344 do { \ 345 if (compl_timeout_ms > COMPL_MIN_TIMEOUT_MS) { \ 346 compl_timeout_ms /= 2; \ 347 } \ 348 } while (0) 349 350// Timeout values for F{func}, F and o values in 'complete' 351#define COMPL_FUNC_TIMEOUT_MS 300 352#define COMPL_FUNC_TIMEOUT_NON_KW_MS 1000 353 354// List of flags for method of completion. 355static int compl_cont_status = 0 ; 356#define CONT_ADDING 1 ///< "normal" or "adding" expansion 357#define CONT_INTRPT (2 + 4) ///< a ^X interrupted the current expansion 358///< it's set only iff N_ADDS is set 359#define CONT_N_ADDS 4 ///< next ^X<> will add-new or expand-current 360#define CONT_S_IPOS 8 ///< next ^X<> will set initial_pos? 361///< if so, word-wise-expansion will set SOL 362#define CONT_SOL 16 ///< pattern includes start of line, just for 363///< word-wise expansion, not set for ^X^L 364#define CONT_LOCAL 32 ///< for ctrl_x_mode 0, ^X^P/^X^N do a local 365///< expansion, (eg use complete=.) 366 367static bool compl_opt_refresh_always = false; 368 369static size_t spell_bad_len = 0 ;// length of located bad word 370 371static int compl_selected_item = -1 ; 372 373static int * compl_fuzzy_scores ; 374 375/// Define the structure for completion source (in 'cpt' option) information 376typedef struct cpt_source_T { 377bool cs_refresh_always ;///< Whether 'refresh:always' is set for func 378int cs_startcol ;///< Start column returned by func 379int cs_max_matches ;///< Max items to display from this source 380uint64_t compl_start_tv ;///< Timestamp when match collection starts 381char cs_flag ;///< Flag indicating the type of source 382}cpt_source_T ; 383 384/// Pointer to the array of completion sources 385static cpt_source_T * cpt_sources_array ; 386/// Total number of completion sources specified in the 'cpt' option 387static int cpt_sources_count ; 388/// Index of the current completion source being expanded 389static int cpt_sources_index = -1 ; 390 391// "compl_match_array" points the currently displayed list of entries in the 392// popup menu. It is NULL when there is no popup menu. 393static pumitem_T * compl_match_array = NULL ; 394static int compl_match_arraysize ; 395 396/// CTRL-X pressed in Insert mode. 397void ins_ctrl_x (void ) 398{ 399if (!ctrl_x_mode_cmdline ()) { 400// if the next ^X<> won't ADD nothing, then reset compl_cont_status 401if (compl_cont_status & CONT_N_ADDS ) { 402compl_cont_status |=CONT_INTRPT ; 403 }else { 404compl_cont_status = 0 ; 405 } 406// We're not sure which CTRL-X mode it will be yet 407ctrl_x_mode = CTRL_X_NOT_DEFINED_YET ; 408edit_submode = _ (CTRL_X_MSG (ctrl_x_mode )); 409edit_submode_pre = NULL ; 410redraw_mode = true; 411 }else { 412// CTRL-X in CTRL-X CTRL-V mode behaves differently to make CTRL-X 413// CTRL-V look like CTRL-N 414ctrl_x_mode = CTRL_X_CMDLINE_CTRL_X ; 415 } 416 417may_trigger_modechanged (); 418} 419 420// Functions to check the current CTRL-X mode. 421 422bool ctrl_x_mode_none (void ) 423FUNC_ATTR_PURE 424{ 425return ctrl_x_mode == 0 ; 426} 427 428bool ctrl_x_mode_normal (void ) 429FUNC_ATTR_PURE 430{ 431return ctrl_x_mode == CTRL_X_NORMAL ; 432} 433 434bool ctrl_x_mode_scroll (void ) 435FUNC_ATTR_PURE 436{ 437return ctrl_x_mode == CTRL_X_SCROLL ; 438} 439 440bool ctrl_x_mode_whole_line (void ) 441FUNC_ATTR_PURE 442{ 443return ctrl_x_mode == CTRL_X_WHOLE_LINE ; 444} 445 446bool ctrl_x_mode_files (void ) 447FUNC_ATTR_PURE 448{ 449return ctrl_x_mode == CTRL_X_FILES ; 450} 451 452bool ctrl_x_mode_tags (void ) 453FUNC_ATTR_PURE 454{ 455return ctrl_x_mode == CTRL_X_TAGS ; 456} 457 458bool ctrl_x_mode_path_patterns (void ) 459FUNC_ATTR_PURE 460{ 461return ctrl_x_mode == CTRL_X_PATH_PATTERNS ; 462} 463 464bool ctrl_x_mode_path_defines (void ) 465FUNC_ATTR_PURE 466{ 467return ctrl_x_mode == CTRL_X_PATH_DEFINES ; 468} 469 470bool ctrl_x_mode_dictionary (void ) 471FUNC_ATTR_PURE 472{ 473return ctrl_x_mode == CTRL_X_DICTIONARY ; 474} 475 476bool ctrl_x_mode_thesaurus (void ) 477FUNC_ATTR_PURE 478{ 479return ctrl_x_mode == CTRL_X_THESAURUS ; 480} 481 482bool ctrl_x_mode_cmdline (void ) 483FUNC_ATTR_PURE 484{ 485return ctrl_x_mode == CTRL_X_CMDLINE || ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X ; 486} 487 488bool ctrl_x_mode_function (void ) 489FUNC_ATTR_PURE 490{ 491return ctrl_x_mode == CTRL_X_FUNCTION ; 492} 493 494bool ctrl_x_mode_omni (void ) 495FUNC_ATTR_PURE 496{ 497return ctrl_x_mode == CTRL_X_OMNI ; 498} 499 500bool ctrl_x_mode_spell (void ) 501FUNC_ATTR_PURE 502{ 503return ctrl_x_mode == CTRL_X_SPELL ; 504} 505 506bool ctrl_x_mode_eval (void ) 507FUNC_ATTR_PURE 508{ 509return ctrl_x_mode == CTRL_X_EVAL ; 510} 511 512bool ctrl_x_mode_line_or_eval (void ) 513FUNC_ATTR_PURE 514{ 515return ctrl_x_mode == CTRL_X_WHOLE_LINE || ctrl_x_mode == CTRL_X_EVAL ; 516} 517 518bool ctrl_x_mode_register (void ) 519FUNC_ATTR_PURE 520{ 521return ctrl_x_mode == CTRL_X_REGISTER ; 522} 523 524/// Whether other than default completion has been selected. 525bool ctrl_x_mode_not_default (void ) 526FUNC_ATTR_PURE 527{ 528return ctrl_x_mode != CTRL_X_NORMAL ; 529} 530 531/// Whether CTRL-X was typed without a following character, 532/// not including when in CTRL-X CTRL-V mode. 533bool ctrl_x_mode_not_defined_yet (void ) 534FUNC_ATTR_PURE 535{ 536return ctrl_x_mode == CTRL_X_NOT_DEFINED_YET ; 537} 538 539/// @return true if currently in "normal" or "adding" insert completion matches state 540bool compl_status_adding (void ) 541{ 542return compl_cont_status & CONT_ADDING ; 543} 544 545/// @return true if the completion pattern includes start of line, just for 546/// word-wise expansion. 547bool compl_status_sol (void ) 548{ 549return compl_cont_status & CONT_SOL ; 550} 551 552/// @return true if ^X^P/^X^N will do a local completion (i.e. use complete=.) 553bool compl_status_local (void ) 554{ 555return compl_cont_status & CONT_LOCAL ; 556} 557 558/// Clear the completion status flags 559void compl_status_clear (void ) 560{ 561compl_cont_status = 0 ; 562} 563 564/// @return true if completion is using the forward direction matches 565static bool compl_dir_forward (void ) 566{ 567return compl_direction == FORWARD ; 568} 569 570/// @return true if currently showing forward completion matches 571static bool compl_shows_dir_forward (void ) 572{ 573return compl_shows_dir == FORWARD ; 574} 575 576/// @return true if currently showing backward completion matches 577static bool compl_shows_dir_backward (void ) 578{ 579return compl_shows_dir == BACKWARD ; 580} 581 582/// Check that the 'dictionary' or 'thesaurus' option can be used. 583/// 584/// @param dict_opt check 'dictionary' when true, 'thesaurus' when false. 585bool check_compl_option (bool dict_opt ) 586{ 587if (dict_opt 588 ? (* curbuf -> b_p_dict == NUL && * p_dict == NUL && !curwin -> w_p_spell ) 589 : (* curbuf -> b_p_tsr == NUL && * p_tsr == NUL 590&& curbuf -> b_p_tsrfu .type == kCallbackNone && p_tsrfu .type == kCallbackNone )) { 591ctrl_x_mode = CTRL_X_NORMAL ; 592edit_submode = NULL ; 593emsg (dict_opt ?_ ("'dictionary' option is empty" ) :_ ("'thesaurus' option is empty" )); 594if (emsg_silent == 0 && !in_assert_fails ) { 595vim_beep (kOptBoFlagComplete ); 596setcursor (); 597msg_delay (2004 , false); 598 } 599return false; 600 } 601return true; 602} 603 604/// Check that the character "c" a valid key to go to or keep us in CTRL-X mode? 605/// This depends on the current mode. 606/// 607/// @param c character to check 608bool vim_is_ctrl_x_key (int c ) 609FUNC_ATTR_WARN_UNUSED_RESULT 610{ 611// Accept <PageUp> and <PageDown> if the popup menu is visible. 612if (ins_compl_pum_key (c )) { 613return true; 614 } 615 616switch (ctrl_x_mode ) { 617case 0 :// Not in any CTRL-X mode 618return c == Ctrl_N || c == Ctrl_P || c == Ctrl_X ; 619case CTRL_X_NOT_DEFINED_YET : 620case CTRL_X_CMDLINE_CTRL_X : 621return c == Ctrl_X || c == Ctrl_Y || c == Ctrl_E 622|| c == Ctrl_L || c == Ctrl_F || c == Ctrl_RSB 623|| c == Ctrl_I || c == Ctrl_D || c == Ctrl_P 624|| c == Ctrl_N || c == Ctrl_T || c == Ctrl_V 625|| c == Ctrl_Q || c == Ctrl_U || c == Ctrl_O 626|| c == Ctrl_S || c == Ctrl_K || c == 's' 627|| c == Ctrl_Z || c == Ctrl_R ; 628case CTRL_X_SCROLL : 629return c == Ctrl_Y || c == Ctrl_E ; 630case CTRL_X_WHOLE_LINE : 631return c == Ctrl_L || c == Ctrl_P || c == Ctrl_N ; 632case CTRL_X_FILES : 633return c == Ctrl_F || c == Ctrl_P || c == Ctrl_N ; 634case CTRL_X_DICTIONARY : 635return c == Ctrl_K || c == Ctrl_P || c == Ctrl_N ; 636case CTRL_X_THESAURUS : 637return c == Ctrl_T || c == Ctrl_P || c == Ctrl_N ; 638case CTRL_X_TAGS : 639return c == Ctrl_RSB || c == Ctrl_P || c == Ctrl_N ; 640case CTRL_X_PATH_PATTERNS : 641return c == Ctrl_P || c == Ctrl_N ; 642case CTRL_X_PATH_DEFINES : 643return c == Ctrl_D || c == Ctrl_P || c == Ctrl_N ; 644case CTRL_X_CMDLINE : 645return c == Ctrl_V || c == Ctrl_Q || c == Ctrl_P || c == Ctrl_N 646|| c == Ctrl_X ; 647case CTRL_X_FUNCTION : 648return c == Ctrl_U || c == Ctrl_P || c == Ctrl_N ; 649case CTRL_X_OMNI : 650return c == Ctrl_O || c == Ctrl_P || c == Ctrl_N ; 651case CTRL_X_SPELL : 652return c == Ctrl_S || c == Ctrl_P || c == Ctrl_N ; 653case CTRL_X_EVAL : 654return (c == Ctrl_P || c == Ctrl_N ); 655case CTRL_X_BUFNAMES : 656return (c == Ctrl_P || c == Ctrl_N ); 657case CTRL_X_REGISTER : 658return (c == Ctrl_R || c == Ctrl_P || c == Ctrl_N ); 659 } 660internal_error ("vim_is_ctrl_x_key()" ); 661return false; 662} 663 664/// @return true if "match" is the original text when the completion began. 665static bool match_at_original_text (const compl_T * const match ) 666{ 667return match -> cp_flags & CP_ORIGINAL_TEXT ; 668} 669 670/// @return true if "match" is the first match in the completion list. 671static bool is_first_match (const compl_T * const match ) 672{ 673return match == compl_first_match ; 674} 675 676/// Return the entry holding the original text, NULL if not found. 677/// It is the first item, or the last one for backward completion. 678static compl_T * find_original_text_match (void ) 679{ 680if (compl_first_match == NULL ) { 681return NULL ; 682 } 683if (match_at_original_text (compl_first_match )) { 684return compl_first_match ; 685 } 686if (compl_first_match -> cp_prev != NULL 687&& match_at_original_text (compl_first_match -> cp_prev )) { 688return compl_first_match -> cp_prev ; 689 } 690return NULL ; 691} 692 693static void do_autocmd_completedone (int c ,int mode ,String * word ) 694{ 695save_v_event_T save_v_event ; 696dict_T * v_event = get_v_event (& save_v_event ); 697 698if (word == NULL || word -> data == NULL ) { 699tv_dict_add_str_len (v_event ,S_LEN ("complete_word" ),"" ,0 ); 700 }else { 701tv_dict_add_str_len (v_event ,S_LEN ("complete_word" ),word -> data , (int )word -> size ); 702 } 703 704String * mode_str = & ctrl_x_mode_names [mode & ~CTRL_X_WANT_IDENT ]; 705tv_dict_add_str_len (v_event ,S_LEN ("complete_type" ), 706mode_str -> data == NULL ?"" :mode_str -> data , 707 (int )mode_str -> size ); 708 709tv_dict_add_str (v_event ,S_LEN ("reason" ), 710 (c == Ctrl_Y || (word != NULL && word -> data != NULL ) 711 ?"accept" : (c == Ctrl_E ?"cancel" :"discard" ))); 712tv_dict_set_keys_readonly (v_event ); 713 714ins_apply_autocmds (EVENT_COMPLETEDONE ); 715restore_v_event (v_event ,& save_v_event ); 716} 717 718/// Check that character "c" is part of the item currently being 719/// completed. Used to decide whether to abandon complete mode when the menu 720/// is visible. 721/// 722/// @param c character to check 723bool ins_compl_accept_char (int c ) 724FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 725{ 726if (compl_autocomplete && compl_from_nonkeyword ) { 727return false; 728 } 729 730if (ctrl_x_mode & CTRL_X_WANT_IDENT ) { 731// When expanding an identifier only accept identifier chars. 732return vim_isIDc (c ); 733 } 734 735switch (ctrl_x_mode ) { 736case CTRL_X_FILES : 737// When expanding file name only accept file name chars. But not 738// path separators, so that "proto/<Tab>" expands files in 739// "proto", not "proto/" as a whole 740return vim_isfilec (c )&& !vim_ispathsep (c ); 741 742case CTRL_X_CMDLINE : 743case CTRL_X_CMDLINE_CTRL_X : 744case CTRL_X_OMNI : 745// Command line and Omni completion can work with just about any 746// printable character, but do stop at white space. 747return vim_isprintc (c )&& !ascii_iswhite (c ); 748 749case CTRL_X_WHOLE_LINE : 750// For while line completion a space can be part of the line. 751return vim_isprintc (c ); 752 } 753return vim_iswordc (c ); 754} 755 756/// Check if "c" is a commit character for the currently selected completion 757/// match: typing it accepts the match, then "c" is inserted as usual. 758/// Set with the "commit_chars" item property, see |complete-items|. 759bool ins_compl_commit_char (int c ) 760{ 761// Control characters and special keys (negative) are never commit 762// characters: CR/NL must keep their compl_enter_selects semantics. 763if (c < ' ' ) { 764return false; 765 } 766return compl_shown_match != NULL 767&& !match_at_original_text (compl_shown_match ) 768&& compl_shown_match -> cp_commit_chars != NULL 769&& vim_strchr (compl_shown_match -> cp_commit_chars ,c )!= NULL ; 770} 771 772/// Get the completed text by inferring the case of the originally typed text. 773/// If the result is in allocated memory "tofree" is set to it. 774static char * ins_compl_infercase_gettext (const char * str ,int char_len ,int compl_char_len , 775int min_len ,char ** tofree ) 776{ 777bool has_lower = false; 778 779// Allocate wide character array for the completion and fill it. 780int * const wca = xmalloc ((size_t )char_len * sizeof (* wca )); 781 { 782const char * p = str ; 783for (int i = 0 ;i < char_len ;i ++ ) { 784wca [i ]= mb_ptr2char_adv (& p ); 785 } 786 } 787 788// Rule 1: Were any chars converted to lower? 789 { 790const char * p = compl_orig_text .data ; 791for (int i = 0 ;i < min_len ;i ++ ) { 792const int c = mb_ptr2char_adv (& p ); 793if (mb_islower (c )) { 794has_lower = true; 795if (mb_isupper (wca [i ])) { 796// Rule 1 is satisfied. 797for (i = compl_char_len ;i < char_len ;i ++ ) { 798wca [i ]= mb_tolower (wca [i ]); 799 } 800break ; 801 } 802 } 803 } 804 } 805 806// Rule 2: No lower case, 2nd consecutive letter converted to 807// upper case. 808if (!has_lower ) { 809bool was_letter = false; 810const char * p = compl_orig_text .data ; 811for (int i = 0 ;i < min_len ;i ++ ) { 812const int c = mb_ptr2char_adv (& p ); 813if (was_letter && mb_isupper (c )&& mb_islower (wca [i ])) { 814// Rule 2 is satisfied. 815for (i = compl_char_len ;i < char_len ;i ++ ) { 816wca [i ]= mb_toupper (wca [i ]); 817 } 818break ; 819 } 820was_letter = mb_islower (c )|| mb_isupper (c ); 821 } 822 } 823 824// Copy the original case of the part we typed. 825 { 826const char * p = compl_orig_text .data ; 827for (int i = 0 ;i < min_len ;i ++ ) { 828const int c = mb_ptr2char_adv (& p ); 829if (mb_islower (c )) { 830wca [i ]= mb_tolower (wca [i ]); 831 }else if (mb_isupper (c )) { 832wca [i ]= mb_toupper (wca [i ]); 833 } 834 } 835 } 836 837// Generate encoding specific output from wide character array. 838garray_T gap ; 839char * p = IObuff ; 840int i = 0 ; 841ga_init (& gap ,1 ,500 ); 842while (i < char_len ) { 843if (gap .ga_data != NULL ) { 844ga_grow (& gap ,10 ); 845assert (gap .ga_data != NULL );// suppress clang "Dereference of NULL pointer" 846p = (char * )gap .ga_data + gap .ga_len ; 847gap .ga_len += utf_char2bytes (wca [i ++ ],p ); 848 }else if ((p - IObuff )+ 6 >=IOSIZE ) { 849// Multi-byte characters can occupy up to five bytes more than 850// ASCII characters, and we also need one byte for NUL, so when 851// getting to six bytes from the edge of IObuff switch to using a 852// growarray. Add the character in the next round. 853ga_grow (& gap ,IOSIZE ); 854* p = NUL ; 855STRCPY (gap .ga_data ,IObuff ); 856gap .ga_len = (int )(p - IObuff ); 857 }else { 858p += utf_char2bytes (wca [i ++ ],p ); 859 } 860 } 861xfree (wca ); 862 863if (gap .ga_data != NULL ) { 864* tofree = gap .ga_data ; 865return gap .ga_data ; 866 } 867 868* p = NUL ; 869return IObuff ; 870} 871 872/// This is like ins_compl_add(), but if 'ic' and 'inf' are set, then the 873/// case of the originally typed text is used, and the case of the completed 874/// text is inferred, ie this tries to work out what case you probably wanted 875/// the rest of the word to be in -- webb 876/// 877/// @param[in] cont_s_ipos next ^X<> will set initial_pos 878int ins_compl_add_infercase (char * str_arg ,int len ,bool icase ,char * fname ,Direction dir , 879bool cont_s_ipos ,int score ) 880FUNC_ATTR_NONNULL_ARG (1 ) 881{ 882char * str = str_arg ; 883int char_len ;// count multi-byte characters 884int compl_char_len ; 885int flags = 0 ; 886char * tofree = NULL ; 887 888if (p_ic && curbuf -> b_p_inf && len > 0 ) { 889// Infer case of completed part. 890 891// Find actual length of completion. 892 { 893const char * p = str ; 894char_len = 0 ; 895while (* p != NUL ) { 896MB_PTR_ADV (p ); 897char_len ++ ; 898 } 899 } 900 901// Find actual length of original text. 902 { 903const char * p = compl_orig_text .data ; 904compl_char_len = 0 ; 905while (* p != NUL ) { 906MB_PTR_ADV (p ); 907compl_char_len ++ ; 908 } 909 } 910 911// "char_len" may be smaller than "compl_char_len" when using 912// thesaurus, only use the minimum when comparing. 913int min_len = MIN (char_len ,compl_char_len ); 914 915str = ins_compl_infercase_gettext (str ,char_len ,compl_char_len ,min_len ,& tofree ); 916 } 917if (cont_s_ipos ) { 918flags |=CP_CONT_S_IPOS ; 919 } 920if (icase ) { 921flags |=CP_ICASE ; 922 } 923 924int res = ins_compl_add (str ,len ,fname ,NULL , false,NULL ,dir ,flags , false,NULL ,score , 925 false,NULL ); 926xfree (tofree ); 927return res ; 928} 929 930/// free cptext 931static inline void free_cptext (char * const * const cptext ) 932{ 933if (cptext != NULL ) { 934for (size_t i = 0 ;i < CPT_COUNT ;i ++ ) { 935xfree (cptext [i ]); 936 } 937 } 938} 939 940/// Check if fuzzy matching is enabled 941static bool cot_fuzzy (void ) 942{ 943return (get_cot_flags ()& kOptCotFlagFuzzy )!= 0 && !ctrl_x_mode_thesaurus (); 944} 945 946/// Returns true if matches should be sorted based on proximity to the cursor. 947static bool is_nearest_active (void ) 948{ 949return (compl_autocomplete || (get_cot_flags ()& kOptCotFlagNearest )) 950&& !cot_fuzzy (); 951} 952 953/// True if a match is selected (even if it is not inserted). 954bool ins_compl_is_match_selected (void ) 955{ 956return compl_shown_match != NULL && !is_first_match (compl_shown_match ); 957} 958 959/// Returns true if autocomplete is active and the pre-insert effect targets the 960/// longest prefix. 961bool ins_compl_preinsert_longest (void ) 962{ 963return compl_autocomplete 964&& (get_cot_flags ()& (kOptCotFlagLongest |kOptCotFlagPreinsert |kOptCotFlagFuzzy )) 965== kOptCotFlagLongest ; 966} 967 968/// Add a match to the list of matches 969/// 970/// @param[in] str text of the match to add 971/// @param[in] len length of "str". If -1, then the length of "str" is computed. 972/// @param[in] fname file name to associate with this match. May be NULL. 973/// @param[in] cptext list of strings to use with this match (for abbr, menu, info 974/// and kind). May be NULL. 975/// If not NULL, must have exactly #CPT_COUNT items. 976/// @param[in] cptext_allocated If true, will not copy cptext strings. 977/// 978/// @note Will free strings in case of error. 979/// cptext itself will not be freed. 980/// @param[in] user_data user supplied data (any vim type) for this match 981/// @param[in] cdir match direction. If 0, use "compl_direction". 982/// @param[in] flags_arg match flags (cp_flags) 983/// @param[in] adup accept this match even if it is already present. 984/// @param[in] user_hl list of extra highlight attributes for abbr kind. 985/// @param[in] commit_chars commit characters for this match. May be NULL. 986/// Must be allocated, ownership is transferred: 987/// freed here when the match is not added. 988/// 989/// If "cdir" is FORWARD, then the match is added after the current match. 990/// Otherwise, it is added before the current match. 991/// 992/// @return NOTDONE if the given string is already in the list of completions, 993/// otherwise it is added to the list and OK is returned. FAIL will be 994/// returned in case of error. 995static int ins_compl_add (char * const str ,int len ,char * const fname ,char * const * const cptext , 996const bool cptext_allocated ,typval_T * user_data ,const Direction cdir , 997int flags_arg ,const bool adup ,const int * user_hl ,const int score , 998bool preselect ,char * const commit_chars ) 999FUNC_ATTR_NONNULL_ARG (1 ) 1000{ 1001compl_T * match ; 1002const Direction dir = (cdir == kDirectionNotSet ?compl_direction :cdir ); 1003int flags = flags_arg ; 1004bool inserted = false; 1005char * new_str = NULL ; 1006hash_T str_hash = 0 ;// hash of the match string, when not 0 1007 1008if (flags & CP_FAST ) { 1009fast_breakcheck (); 1010 }else { 1011os_breakcheck (); 1012 } 1013if (got_int ) { 1014if (cptext_allocated ) { 1015free_cptext (cptext ); 1016 } 1017xfree (commit_chars ); 1018return FAIL ; 1019 } 1020if (len < 0 ) { 1021len = (int )strlen (str ); 1022 } 1023 1024// If the same match is already present, don't add it. 1025if (compl_first_match != NULL && !adup && compl_strings_ht .ht_used > 0 ) { 1026// The key must be NUL terminated. 1027char keybuf [128 ]; 1028char * key ; 1029if (len < (int )sizeof (keybuf )) { 1030memmove (keybuf ,str , (size_t )len ); 1031keybuf [len ]= NUL ; 1032key = keybuf ; 1033 }else { 1034new_str = xstrnsave (str , (size_t )len ); 1035key = new_str ; 1036 } 1037str_hash = hash_hash (key ); 1038hashitem_T * hi = hash_lookup (& compl_strings_ht ,key , (size_t )len ,str_hash ); 1039if (!HASHITEM_EMPTY (hi )) { 1040if (is_nearest_active ()&& score > 0 ) { 1041// The duplicate may need its score updated, scan the 1042// matches to find it. 1043match = compl_first_match ; 1044do { 1045if (!match_at_original_text (match ) 1046&& strncmp (match -> cp_str .data ,str , (size_t )len )== 0 1047&& ((int )match -> cp_str .size <=len || match -> cp_str .data [len ]== NUL )) { 1048if (score < match -> cp_score ) { 1049match -> cp_score = score ; 1050 } 1051break ; 1052 } 1053match = match -> cp_next ; 1054 }while (match != NULL && !is_first_match (match )); 1055 } 1056xfree (new_str ); 1057if (cptext_allocated ) { 1058free_cptext (cptext ); 1059 } 1060xfree (commit_chars ); 1061return NOTDONE ; 1062 } 1063 } 1064 1065// Remove any popup menu before changing the list of matches. 1066ins_compl_del_pum (); 1067 1068// Allocate a new match structure. 1069// Copy the values to the new match structure. 1070match = xcalloc (1 ,sizeof (compl_T )); 1071match -> cp_number = flags & CP_ORIGINAL_TEXT ?0 :-1 ; 1072new_str = new_str == NULL ?xstrnsave (str , (size_t )len ) :new_str ; 1073match -> cp_str = cbuf_as_string (new_str , (size_t )len ); 1074match -> cp_commit_chars = commit_chars ; 1075match -> cp_preselect = preselect ; 1076if (preselect && compl_preselect_match == NULL 1077&& (get_cot_flags ()& kOptCotFlagPreselect )) { 1078compl_preselect_match = match ; 1079 } 1080 1081// match-fname is: 1082// - compl_curr_match->cp_fname if it is a string equal to fname. 1083// - a copy of fname, CP_FREE_FNAME is set to free later THE allocated mem. 1084// - NULL otherwise. --Acevedo 1085if (fname != NULL 1086&& compl_curr_match != NULL 1087&& compl_curr_match -> cp_fname != NULL 1088&& strcmp (fname ,compl_curr_match -> cp_fname )== 0 ) { 1089match -> cp_fname = compl_curr_match -> cp_fname ; 1090 }else if (fname != NULL ) { 1091match -> cp_fname = xstrdup (fname ); 1092flags |=CP_FREE_FNAME ; 1093 }else { 1094match -> cp_fname = NULL ; 1095 } 1096match -> cp_flags = flags ; 1097match -> cp_user_abbr_hl_id = user_hl ?user_hl [0 ] :0 ; 1098match -> cp_user_kind_hl_id = user_hl ?user_hl [1 ] :0 ; 1099match -> cp_score = score ; 1100match -> cp_cpt_source_idx = cpt_sources_index ; 1101 1102if (cptext != NULL ) { 1103for (int i = 0 ;i < CPT_COUNT ;i ++ ) { 1104if (cptext [i ]== NULL ) { 1105continue ; 1106 } 1107if (* cptext [i ]!= NUL ) { 1108match -> cp_text [i ]= (cptext_allocated ?cptext [i ] :xstrdup (cptext [i ])); 1109 }else if (cptext_allocated ) { 1110xfree (cptext [i ]); 1111 } 1112 } 1113 } 1114 1115if (user_data != NULL ) { 1116match -> cp_user_data = * user_data ; 1117 } 1118 1119// Link the new match structure after (FORWARD) or before (BACKWARD) the 1120// current match in the list of matches . 1121if (compl_first_match == NULL ) { 1122match -> cp_next = match -> cp_prev = NULL ; 1123 }else if (cot_fuzzy ()&& score != FUZZY_SCORE_NONE && compl_get_longest ) { 1124compl_T * current = compl_first_match -> cp_next ; 1125compl_T * prev = compl_first_match ; 1126inserted = false; 1127// The direction is ignored when using longest and fuzzy match, because 1128// matches are inserted and sorted by score. 1129while (current != NULL && current != compl_first_match ) { 1130if (current -> cp_score < score ) { 1131match -> cp_next = current ; 1132match -> cp_prev = current -> cp_prev ; 1133if (current -> cp_prev ) { 1134current -> cp_prev -> cp_next = match ; 1135 } 1136current -> cp_prev = match ; 1137inserted = true; 1138break ; 1139 } 1140prev = current ; 1141current = current -> cp_next ; 1142 } 1143if (!inserted ) { 1144prev -> cp_next = match ; 1145match -> cp_prev = prev ; 1146match -> cp_next = compl_first_match ; 1147compl_first_match -> cp_prev = match ; 1148 } 1149 }else if (dir == FORWARD ) { 1150match -> cp_next = compl_curr_match -> cp_next ; 1151match -> cp_prev = compl_curr_match ; 1152 }else {// BACKWARD 1153match -> cp_next = compl_curr_match ; 1154match -> cp_prev = compl_curr_match -> cp_prev ; 1155 } 1156if (match -> cp_next ) { 1157match -> cp_next -> cp_prev = match ; 1158 } 1159if (match -> cp_prev ) { 1160match -> cp_prev -> cp_next = match ; 1161 }else {// if there's nothing before, it is the first match 1162compl_first_match = match ; 1163 } 1164compl_curr_match = match ; 1165 1166if (!match_at_original_text (match )) { 1167compl_strings_add (match -> cp_str .data ,match -> cp_str .size ,str_hash ); 1168 } 1169 1170// Find the longest common string if still doing that. 1171if (compl_get_longest && (flags & CP_ORIGINAL_TEXT )== 0 && !cot_fuzzy () 1172&& !ins_compl_preinsert_longest ()&& !ctrl_x_mode_thesaurus ()) { 1173ins_compl_longest_match (match ); 1174 } 1175 1176return OK ; 1177} 1178 1179/// Check that "str[len]" matches with "match->cp_str", considering 1180/// "match->cp_flags". 1181/// 1182/// @param match completion match 1183/// @param str character string to check 1184/// @param len length of "str" 1185static bool ins_compl_equal (compl_T * match ,char * str ,size_t len ) 1186FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL 1187{ 1188if (match -> cp_flags & CP_EQUAL ) { 1189return true; 1190 } 1191if (match -> cp_flags & CP_ICASE ) { 1192return STRNICMP (match -> cp_str .data ,str ,len )== 0 ; 1193 } 1194return strncmp (match -> cp_str .data ,str ,len )== 0 ; 1195} 1196 1197/// Like ins_compl_equal(), but ignore case in the 'longest'-inserted part of 1198/// the leader, so CTRL-N and CTRL-P filter the same way. 1199static bool ins_compl_equal_sc (compl_T * match ,char * str ,size_t len ) 1200FUNC_ATTR_NONNULL_ALL 1201{ 1202int typed = compl_length ; 1203int longest_end = (compl_get_longest && compl_longest_end_col > compl_col ) 1204 ? (int )(compl_longest_end_col - compl_col ) :typed ; 1205 1206if ((match -> cp_flags & (CP_EQUAL |CP_ICASE ))|| longest_end <=typed ) { 1207return ins_compl_equal (match ,str ,len ); 1208 } 1209 1210if (match -> cp_str .size < len ) { 1211return false; 1212 } 1213 1214for (int i = 0 ; (size_t )i < len ;i ++ ) { 1215if (i >=typed && i < longest_end 1216 ?TOLOWER_LOC ((uint8_t )match -> cp_str .data [i ])!= TOLOWER_LOC ((uint8_t )str [i ]) 1217 :match -> cp_str .data [i ]!= str [i ]) { 1218return false; 1219 } 1220 } 1221return true; 1222} 1223 1224/// when len is -1 mean use whole length of p otherwise part of p 1225static void ins_compl_insert_bytes (char * p ,int len ) 1226FUNC_ATTR_NONNULL_ALL 1227{ 1228if (len == -1 ) { 1229len = (int )strlen (p ); 1230 } 1231assert (len >=0 ); 1232ins_bytes_len (p , (size_t )len ); 1233compl_ins_end_col = curwin -> w_cursor .col ; 1234} 1235 1236/// Get current completion leader 1237char * ins_compl_leader (void ) 1238{ 1239return compl_leader .data != NULL ?compl_leader .data :compl_orig_text .data ; 1240} 1241 1242/// Get current completion leader length 1243static size_t ins_compl_leader_len (void ) 1244{ 1245return compl_leader .data != NULL ?compl_leader .size :compl_orig_text .size ; 1246} 1247 1248/// Checks if the column is within the currently inserted completion text 1249/// column range. If it is, it returns a special highlight attribute. 1250/// -1 means normal item. 1251int ins_compl_col_range_attr (linenr_T lnum ,int col ) 1252{ 1253const bool has_preinsert = ins_compl_has_preinsert ()|| ins_compl_preinsert_longest (); 1254 1255int attr ; 1256if (cot_fuzzy () 1257|| (!compl_hi_on_autocompl_longest && ins_compl_preinsert_longest ()) 1258|| (attr = syn_name2attr (has_preinsert ?"PreInsert" :"ComplMatchIns" ))== 0 ) { 1259return -1 ; 1260 } 1261 1262int start_col = compl_col + (int )ins_compl_leader_len (); 1263if (!ins_compl_has_multiple ()) { 1264return (col >=start_col && col < compl_ins_end_col ) ?attr :-1 ; 1265 } 1266 1267// Multiple lines 1268if ((lnum == compl_lnum && col >=start_col && col < MAXCOL ) 1269|| (lnum > compl_lnum && lnum < curwin -> w_cursor .lnum ) 1270|| (lnum == curwin -> w_cursor .lnum && col <=compl_ins_end_col )) { 1271return attr ; 1272 } 1273 1274return -1 ; 1275} 1276 1277/// Returns true if the current completion string contains newline characters, 1278/// indicating it's a multi-line completion. 1279static bool ins_compl_has_multiple (void ) 1280{ 1281return vim_strchr (compl_shown_match -> cp_str .data ,'\n' )!= NULL ; 1282} 1283 1284/// Returns true if the given line number falls within the range of a multi-line 1285/// completion, i.e. between the starting line (compl_lnum) and current cursor 1286/// line. Always returns false for single-line completions. 1287bool ins_compl_lnum_in_range (linenr_T lnum ) 1288{ 1289if (!ins_compl_has_multiple ()) { 1290return false; 1291 } 1292return lnum >=compl_lnum && lnum <=curwin -> w_cursor .lnum ; 1293} 1294 1295/// Reduce the longest common string for match "match". 1296static void ins_compl_longest_match (compl_T * match ) 1297{ 1298if (compl_leader .data == NULL ) { 1299// First match, use it as a whole. 1300compl_leader = copy_string (match -> cp_str ,NULL ); 1301 1302bool had_match = (curwin -> w_cursor .col > compl_col ); 1303ins_compl_longest_insert (compl_leader .data ); 1304 1305// When the match isn't there (to avoid matching itself) remove it 1306// again after redrawing. 1307if (!had_match ) { 1308ins_compl_delete (false); 1309 } 1310compl_used_match = false; 1311 1312return ; 1313 } 1314 1315// Reduce the text if this match differs from compl_leader. 1316char * p = compl_leader .data ; 1317char * s = match -> cp_str .data ; 1318while (* p != NUL ) { 1319int c1 = utf_ptr2char (p ); 1320int c2 = utf_ptr2char (s ); 1321 1322if ((match -> cp_flags & CP_ICASE ) 1323 ? (mb_tolower (c1 )!= mb_tolower (c2 )) 1324 : (c1 != c2 )) { 1325break ; 1326 } 1327MB_PTR_ADV (p ); 1328MB_PTR_ADV (s ); 1329 } 1330 1331if (* p != NUL ) { 1332// Leader was shortened, need to change the inserted text. 1333* p = NUL ; 1334compl_leader .size = (size_t )(p - compl_leader .data ); 1335 1336bool had_match = (curwin -> w_cursor .col > compl_col ); 1337ins_compl_longest_insert (compl_leader .data ); 1338 1339// When the match isn't there (to avoid matching itself) remove it 1340// again after redrawing. 1341if (!had_match ) { 1342ins_compl_delete (false); 1343 } 1344 } 1345 1346compl_used_match = false; 1347} 1348 1349/// Add an array of matches to the list of matches. 1350/// Frees matches[]. 1351static void ins_compl_add_matches (int num_matches ,char ** matches ,int icase ) 1352{ 1353int add_r = OK ; 1354Direction dir = compl_direction ; 1355 1356for (int i = 0 ;i < num_matches && add_r != FAIL ;i ++ ) { 1357add_r = ins_compl_add (matches [i ],-1 ,NULL ,NULL , false,NULL ,dir , 1358CP_FAST | (icase ?CP_ICASE :0 ), false,NULL , 1359FUZZY_SCORE_NONE , false,NULL ); 1360if (add_r == OK ) { 1361// If dir was BACKWARD then honor it just once. 1362dir = FORWARD ; 1363 } 1364 } 1365FreeWild (num_matches ,matches ); 1366} 1367 1368/// Make the completion list cyclic. 1369/// Return the number of matches (excluding the original). 1370static int ins_compl_make_cyclic (void ) 1371{ 1372if (compl_first_match == NULL ) { 1373return 0 ; 1374 } 1375 1376// Find the end of the list. 1377compl_T * match = compl_first_match ; 1378int count = 0 ; 1379// there's always an entry for the compl_orig_text, it doesn't count. 1380while (match -> cp_next != NULL && !is_first_match (match -> cp_next )) { 1381match = match -> cp_next ; 1382count ++ ; 1383 } 1384match -> cp_next = compl_first_match ; 1385compl_first_match -> cp_prev = match ; 1386 1387return count ; 1388} 1389 1390/// Return whether there currently is a shown match. 1391bool ins_compl_has_shown_match (void ) 1392{ 1393return compl_shown_match == NULL || compl_shown_match != compl_shown_match -> cp_next ; 1394} 1395 1396/// Return whether the shown match is long enough. 1397bool ins_compl_long_shown_match (void ) 1398{ 1399return compl_shown_match != NULL && compl_shown_match -> cp_str .data != NULL 1400&& (colnr_T )compl_shown_match -> cp_str .size > curwin -> w_cursor .col - compl_col ; 1401} 1402 1403/// Get the local or global value of 'completeopt' flags. 1404unsigned get_cot_flags (void ) 1405{ 1406return curbuf -> b_cot_flags != 0 ?curbuf -> b_cot_flags :cot_flags ; 1407} 1408 1409/// Remove any popup menu. 1410static void ins_compl_del_pum (void ) 1411{ 1412if (compl_match_array == NULL ) { 1413return ; 1414 } 1415 1416pum_undisplay (false); 1417XFREE_CLEAR (compl_match_array ); 1418} 1419 1420/// Check if the popup menu should be displayed. 1421bool pum_wanted (void ) 1422FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1423{ 1424// "completeopt" must contain "menu" or "menuone" 1425return (get_cot_flags ()& (kOptCotFlagMenu |kOptCotFlagMenuone ))!= 0 || compl_autocomplete ; 1426} 1427 1428/// Check that there are two or more matches to be shown in the popup menu. 1429/// One if "completopt" contains "menuone". 1430static bool pum_enough_matches (void ) 1431FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 1432{ 1433// Don't display the popup menu if there are no matches or there is only 1434// one (ignoring the original text). 1435compl_T * comp = compl_first_match ; 1436int i = 0 ; 1437do { 1438if (comp == NULL || (!match_at_original_text (comp )&& ++ i == 2 )) { 1439break ; 1440 } 1441comp = comp -> cp_next ; 1442 }while (!is_first_match (comp )); 1443 1444if ((get_cot_flags ()& kOptCotFlagMenuone )|| compl_autocomplete ) { 1445return i >=1 ; 1446 } 1447return i >=2 ; 1448} 1449 1450/// Convert to complete item dict 1451static dict_T * ins_compl_dict_alloc (compl_T * match ) 1452{ 1453// { word, abbr, menu, kind, info } 1454dict_T * dict = tv_dict_alloc_lock (VAR_FIXED ); 1455fill_complete_info_dict (dict ,match , false); 1456return dict ; 1457} 1458 1459/// Trigger the CompleteChanged autocmd event. Invoked each time the Insert mode 1460/// completion menu is changed. 1461static void trigger_complete_changed_event (int cur ) 1462{ 1463static bool recursive = false; 1464save_v_event_T save_v_event ; 1465 1466if (recursive ) { 1467return ; 1468 } 1469 1470dict_T * item = cur < 0 ?tv_dict_alloc () :ins_compl_dict_alloc (compl_curr_match ); 1471dict_T * v_event = get_v_event (& save_v_event ); 1472tv_dict_add_dict (v_event ,S_LEN ("completed_item" ),item ); 1473pum_set_event_info (v_event ); 1474tv_dict_set_keys_readonly (v_event ); 1475 1476recursive = true; 1477textlock ++ ; 1478apply_autocmds (EVENT_COMPLETECHANGED ,NULL ,NULL , false,curbuf ); 1479textlock -- ; 1480recursive = false; 1481 1482restore_v_event (v_event ,& save_v_event ); 1483} 1484 1485// Helper functions for mergesort_list(). 1486 1487static void * cp_get_next (void * node ) 1488{ 1489return ((compl_T * )node )-> cp_next ; 1490} 1491 1492static void cp_set_next (void * node ,void * next ) 1493{ 1494 ((compl_T * )node )-> cp_next = (compl_T * )next ; 1495} 1496 1497static void * cp_get_prev (void * node ) 1498{ 1499return ((compl_T * )node )-> cp_prev ; 1500} 1501 1502static void cp_set_prev (void * node ,void * prev ) 1503{ 1504 ((compl_T * )node )-> cp_prev = (compl_T * )prev ; 1505} 1506 1507static int cp_compare_fuzzy (const void * a ,const void * b ) 1508{ 1509int score_a = ((compl_T * )a )-> cp_score ; 1510int score_b = ((compl_T * )b )-> cp_score ; 1511return (score_b > score_a ) ?1 : (score_b < score_a ) ?-1 :0 ; 1512} 1513 1514static int cp_compare_nearest (const void * a ,const void * b ) 1515{ 1516int score_a = ((compl_T * )a )-> cp_score ; 1517int score_b = ((compl_T * )b )-> cp_score ; 1518if (score_a == FUZZY_SCORE_NONE || score_b == FUZZY_SCORE_NONE ) { 1519return 0 ; 1520 } 1521return (score_a > score_b ) ?1 : (score_a < score_b ) ?-1 :0 ; 1522} 1523 1524/// Constructs a new string by prepending text from the current line (from 1525/// startcol to compl_col) to the given source string. Stores the result in 1526/// dest. 1527static void prepend_startcol_text (String * dest ,String * src ,int startcol ) 1528{ 1529int prepend_len = compl_col - startcol ; 1530int new_length = prepend_len + (int )src -> size ; 1531 1532dest -> size = (size_t )new_length ; 1533dest -> data = xmalloc ((size_t )new_length + 1 );// +1 for NUL 1534 1535char * line = ml_get (curwin -> w_cursor .lnum ); 1536 1537memmove (dest -> data ,line + startcol , (size_t )prepend_len ); 1538memmove (dest -> data + prepend_len ,src -> data ,src -> size ); 1539dest -> data [new_length ]= NUL ; 1540} 1541 1542/// Returns the completion leader string adjusted for a specific source's 1543/// startcol. If the source's startcol is before compl_col, prepends text from 1544/// the buffer line to the original compl_leader. 1545static String * get_leader_for_startcol (compl_T * match ,bool cached ) 1546{ 1547static String adjusted_leader = STRING_INIT ; 1548 1549if (match == NULL ) { 1550API_CLEAR_STRING (adjusted_leader ); 1551return NULL ; 1552 } 1553 1554if (cpt_sources_array == NULL ) { 1555 gototheend ; 1556 } 1557 1558int cpt_idx = match -> cp_cpt_source_idx ; 1559if (cpt_idx < 0 ) { 1560 gototheend ; 1561 } 1562int startcol = cpt_sources_array [cpt_idx ].cs_startcol ; 1563 1564if (compl_leader .data == NULL ) { 1565// When leader is not set (e.g. 'autocomplete' first fires before 1566// compl_leader is initialised), fall back to compl_orig_text for 1567// matches starting at or after compl_col. Matches starting before 1568// compl_col carry pre-compl_col text and must not be compared with 1569// compl_orig_text, so return &compl_leader (NULL string) to signal 1570// "pass through" (no prefix filter). 1571if (startcol < 0 || startcol >=compl_col ) { 1572return & compl_orig_text ; 1573 } 1574return & compl_leader ;// pass through (startcol < compl_col) 1575 } 1576 1577if (compl_col <=0 ) { 1578 gototheend ; 1579 } 1580 1581if (startcol >=0 && startcol < compl_col ) { 1582int prepend_len = compl_col - startcol ; 1583int new_length = prepend_len + (int )compl_leader .size ; 1584if (cached && (size_t )new_length == adjusted_leader .size 1585&& adjusted_leader .data != NULL ) { 1586return & adjusted_leader ; 1587 } 1588 1589API_CLEAR_STRING (adjusted_leader ); 1590prepend_startcol_text (& adjusted_leader ,& compl_leader ,startcol ); 1591return & adjusted_leader ; 1592 } 1593theend : 1594return & compl_leader ; 1595} 1596 1597/// Set fuzzy score for completion matches. 1598static void set_fuzzy_score (void ) 1599{ 1600if (compl_first_match == NULL ) { 1601return ; 1602 } 1603 1604// Determine the pattern to match against 1605bool use_leader = (compl_leader .data != NULL && compl_leader .size > 0 ); 1606char * pattern ; 1607if (!use_leader ) { 1608if (compl_orig_text .data == NULL || compl_orig_text .size == 0 ) { 1609return ; 1610 } 1611pattern = compl_orig_text .data ; 1612 }else { 1613// Clear the leader cache once before the loop 1614 (void )get_leader_for_startcol (NULL , true); 1615pattern = NULL ;// Will be computed per-completion 1616 } 1617 1618// Score all completion matches 1619compl_T * comp = compl_first_match ; 1620do { 1621if (use_leader ) { 1622pattern = get_leader_for_startcol (comp , true)-> data ; 1623 } 1624 1625comp -> cp_score = fuzzy_match_str (comp -> cp_str .data ,pattern ); 1626comp = comp -> cp_next ; 1627 }while (comp != NULL && !is_first_match (comp )); 1628} 1629 1630/// Sort completion matches, leaving the entry with the original text in place. 1631static void sort_compl_match_list (MergeSortCompareFunc compare ) 1632{ 1633if (!compl_first_match || is_first_match (compl_first_match -> cp_next )) { 1634return ; 1635 } 1636 1637compl_T * orig_text = find_original_text_match (); 1638if (orig_text == NULL ) { 1639return ; 1640 } 1641 1642ins_compl_make_linear (); 1643if (orig_text == compl_first_match ) { 1644compl_first_match -> cp_next -> cp_prev = NULL ; 1645compl_first_match -> cp_next = mergesort_list (compl_first_match -> cp_next , 1646cp_get_next ,cp_set_next , 1647cp_get_prev ,cp_set_prev , 1648compare ); 1649compl_first_match -> cp_next -> cp_prev = compl_first_match ; 1650 }else { 1651orig_text -> cp_prev -> cp_next = NULL ; 1652compl_first_match = mergesort_list (compl_first_match ,cp_get_next ,cp_set_next , 1653cp_get_prev ,cp_set_prev ,compare ); 1654compl_T * tail = compl_first_match ; 1655while (tail -> cp_next != NULL ) { 1656tail = tail -> cp_next ; 1657 } 1658tail -> cp_next = orig_text ; 1659orig_text -> cp_prev = tail ; 1660 } 1661 (void )ins_compl_make_cyclic (); 1662} 1663 1664/// Return the attribute for highlight group "hl_id", -1 when it has none. 1665static int get_user_highlight_attr (int hl_id ) 1666{ 1667int attr ; 1668 1669if (hl_id <=0 ) { 1670return -1 ; 1671 } 1672attr = syn_id2attr (hl_id ); 1673return attr > 0 ?attr :-1 ; 1674} 1675 1676/// Build a popup menu to show the completion matches. 1677/// 1678/// @return the popup menu entry that should be selected, 1679/// -1 if nothing should be selected. 1680static int ins_compl_build_pum (void ) 1681{ 1682// Need to build the popup menu list. 1683compl_match_arraysize = 0 ; 1684 1685// If it's user complete function and refresh_always, 1686// do not use "compl_leader" as prefix filter. 1687if (ins_compl_need_restart ()) { 1688API_CLEAR_STRING (compl_leader ); 1689 } 1690 1691bool compl_no_select = (get_cot_flags ()& kOptCotFlagNoselect )!= 0 1692|| (compl_autocomplete && !ins_compl_has_preinsert ()); 1693 1694compl_T * match_head = NULL ,* match_tail = NULL ; 1695int * match_count = NULL ; 1696bool is_forward = compl_shows_dir_forward (); 1697bool is_cpt_completion = (cpt_sources_array != NULL ); 1698 1699// If the current match is the original text don't find the first 1700// match after it, don't highlight anything. 1701bool shown_match_ok = match_at_original_text (compl_shown_match ); 1702 1703if (strequal (compl_leader .data ,compl_orig_text .data )&& !shown_match_ok ) { 1704compl_shown_match = compl_no_select ?compl_first_match :compl_first_match -> cp_next ; 1705 } 1706 1707bool did_find_shown_match = false; 1708bool preselect_ok = false; 1709compl_T * comp ; 1710compl_T * shown_compl = NULL ; 1711int i = 0 ; 1712int cur = -1 ; 1713 1714if (is_cpt_completion ) { 1715match_count = xcalloc ((size_t )cpt_sources_count ,sizeof (int )); 1716 } 1717 1718 (void )get_leader_for_startcol (NULL , true);// Clear the cache 1719 1720comp = compl_first_match ; 1721do { 1722comp -> cp_in_match_array = false; 1723 1724String * leader = get_leader_for_startcol (comp , true); 1725 1726// Apply 'smartcase': judge case from compl_orig_text, not the leader 1727// which 'longest' may fill with uppercase the user never typed. 1728if (ctrl_x_mode_normal ()&& !p_inf && compl_orig_text .data 1729&& !ignorecase (compl_orig_text .data )&& !cot_fuzzy ()) { 1730comp -> cp_flags &= ~CP_ICASE ; 1731 } 1732 1733if (!match_at_original_text (comp ) 1734&& (leader -> data == NULL 1735|| ins_compl_equal_sc (comp ,leader -> data ,leader -> size ) 1736|| (cot_fuzzy ()&& comp -> cp_score != FUZZY_SCORE_NONE ))) { 1737// Limit number of items from each source if max_items is set. 1738bool match_limit_exceeded = false; 1739int cur_source = comp -> cp_cpt_source_idx ; 1740if (is_forward && cur_source != -1 && is_cpt_completion ) { 1741match_count [cur_source ]++ ; 1742int max_matches = cpt_sources_array [cur_source ].cs_max_matches ; 1743if (max_matches > 0 && match_count [cur_source ]> max_matches ) { 1744match_limit_exceeded = true; 1745 } 1746 } 1747 1748if (!match_limit_exceeded ) { 1749compl_match_arraysize ++ ; 1750comp -> cp_in_match_array = true; 1751if (match_head == NULL ) { 1752match_head = comp ; 1753 }else { 1754match_tail -> cp_match_next = comp ; 1755 } 1756match_tail = comp ; 1757 1758if (!shown_match_ok && !cot_fuzzy ()) { 1759if (comp == compl_shown_match || did_find_shown_match ) { 1760// This item is the shown match or this is the 1761// first displayed item after the shown match. 1762compl_shown_match = comp ; 1763did_find_shown_match = true; 1764shown_match_ok = true; 1765 }else { 1766// Remember this displayed match for when the 1767// shown match is just below it. 1768shown_compl = comp ; 1769 } 1770cur = i ; 1771 }else if (cot_fuzzy ()) { 1772if (i == 0 ) { 1773shown_compl = comp ; 1774 } 1775 1776if (!shown_match_ok && comp == compl_shown_match ) { 1777cur = i ; 1778shown_match_ok = true; 1779 } 1780 } 1781if (compl_preselect_match != NULL && comp -> cp_preselect && !preselect_ok ) { 1782cur = i ; 1783compl_shown_match = comp ; 1784shown_match_ok = true; 1785preselect_ok = true; 1786 } 1787i ++ ; 1788 } 1789 } 1790 1791if (comp == compl_shown_match && !cot_fuzzy ()) { 1792did_find_shown_match = true; 1793// When the original text is the shown match don't set 1794// compl_shown_match. 1795if (match_at_original_text (comp )) { 1796shown_match_ok = true; 1797 } 1798if (!shown_match_ok && shown_compl != NULL ) { 1799// The shown match isn't displayed, set it to the 1800// previously displayed match. 1801compl_shown_match = shown_compl ; 1802shown_match_ok = true; 1803 } 1804 } 1805comp = comp -> cp_next ; 1806 }while (comp != NULL && !is_first_match (comp )); 1807 1808xfree (match_count ); 1809 1810if (compl_match_arraysize == 0 ) { 1811return -1 ; 1812 } 1813 1814if (cot_fuzzy ()&& !compl_no_select && !shown_match_ok ) { 1815compl_shown_match = shown_compl ; 1816shown_match_ok = true; 1817cur = 0 ; 1818 } 1819 1820assert (compl_match_arraysize >=0 ); 1821compl_match_array = xcalloc ((size_t )compl_match_arraysize ,sizeof (pumitem_T )); 1822 1823i = 0 ; 1824comp = match_head ; 1825while (comp != NULL ) { 1826compl_match_array [i ].pum_text = comp -> cp_text [CPT_ABBR ]!= NULL 1827 ?comp -> cp_text [CPT_ABBR ] :comp -> cp_str .data ; 1828compl_match_array [i ].pum_kind = comp -> cp_text [CPT_KIND ]; 1829compl_match_array [i ].pum_info = comp -> cp_text [CPT_INFO ]; 1830compl_match_array [i ].pum_cpt_source_idx = comp -> cp_cpt_source_idx ; 1831compl_match_array [i ].pum_user_abbr_hlattr = get_user_highlight_attr (comp -> cp_user_abbr_hl_id ); 1832compl_match_array [i ].pum_user_kind_hlattr = get_user_highlight_attr (comp -> cp_user_kind_hl_id ); 1833compl_match_array [i ++ ].pum_extra = comp -> cp_text [CPT_MENU ]!= NULL 1834 ?comp -> cp_text [CPT_MENU ] :comp -> cp_fname ; 1835compl_T * match_next = comp -> cp_match_next ; 1836comp -> cp_match_next = NULL ; 1837comp = match_next ; 1838 } 1839 1840if (!shown_match_ok ) {// no displayed match at all 1841cur = -1 ; 1842 } 1843 1844return cur ; 1845} 1846 1847/// Show the popup menu for the list of matches. 1848/// Also adjusts "compl_shown_match" to an entry that is actually displayed. 1849void ins_compl_show_pum (void ) 1850{ 1851if (!pum_wanted ()|| !pum_enough_matches ()) { 1852return ; 1853 } 1854 1855// Update the screen before drawing the popup menu over it. 1856update_screen (); 1857 1858int cur = -1 ; 1859bool array_changed = false; 1860 1861if (compl_match_array == NULL ) { 1862array_changed = true; 1863// Need to build the popup menu list. 1864cur = ins_compl_build_pum (); 1865 }else { 1866// popup menu already exists, only need to find the current item. 1867for (int i = 0 ;i < compl_match_arraysize ;i ++ ) { 1868if (compl_match_array [i ].pum_text == compl_shown_match -> cp_str .data 1869|| compl_match_array [i ].pum_text == compl_shown_match -> cp_text [CPT_ABBR ]) { 1870cur = i ; 1871break ; 1872 } 1873 } 1874 } 1875 1876if (compl_match_array == NULL ) { 1877if (compl_started && has_event (EVENT_COMPLETECHANGED )) { 1878trigger_complete_changed_event (cur ); 1879 } 1880return ; 1881 } 1882 1883// In Replace mode when a $ is displayed at the end of the line only 1884// part of the screen would be updated. We do need to redraw here. 1885dollar_vcol = -1 ; 1886 1887// Compute the screen column of the start of the completed text. 1888// Use the cursor to get all wrapping and other settings right. 1889const colnr_T col = curwin -> w_cursor .col ; 1890curwin -> w_cursor .col = compl_col ; 1891compl_selected_item = cur ; 1892pum_display (compl_match_array ,compl_match_arraysize ,cur ,array_changed ,0 ); 1893curwin -> w_cursor .col = col ; 1894 1895// The cursor was temporarily moved to "compl_col" above to position the 1896// menu, so the screen update left w_wcol conceal-corrected for that column 1897// rather than for the real cursor. Redraw the cursor line so the caret is 1898// positioned correctly when the cursor line has concealed text. 1899if (curwin -> w_p_cole > 0 && conceal_cursor_line (curwin )) { 1900redrawWinline (curwin ,curwin -> w_cursor .lnum ); 1901 } 1902 1903// After adding leader, set the current match to shown match. 1904if (compl_started && compl_curr_match != compl_shown_match ) { 1905compl_curr_match = compl_shown_match ; 1906 } 1907 1908if (has_event (EVENT_COMPLETECHANGED )) { 1909trigger_complete_changed_event (cur ); 1910 } 1911} 1912 1913/// check selected is current match. 1914/// 1915/// @param selected the item which is selected. 1916/// @return bool return true when is current match otherwise is false. 1917bool compl_match_curr_select (int selected ) 1918{ 1919if (selected < 0 ) { 1920return false; 1921 } 1922compl_T * match = compl_first_match ; 1923int selected_idx = -1 ,list_idx = 0 ; 1924do { 1925if (!match_at_original_text (match )) { 1926if (compl_curr_match != NULL 1927&& compl_curr_match -> cp_number == match -> cp_number ) { 1928selected_idx = list_idx ; 1929break ; 1930 } 1931list_idx += 1 ; 1932 } 1933match = match -> cp_next ; 1934 }while (match != NULL && !is_first_match (match )); 1935 1936return selected == selected_idx ; 1937} 1938 1939#define DICT_FIRST (1) ///< use just first element in "dict" 1940#define DICT_EXACT (2) ///< "dict" is the exact name of a file 1941 1942/// Add any identifiers that match the given pattern "pat" in the list of 1943/// dictionary files "dict_start" to the list of completions. 1944/// 1945/// @param flags DICT_FIRST and/or DICT_EXACT 1946/// @param thesaurus Thesaurus completion 1947static void ins_compl_dictionaries (char * dict_start ,char * pat ,int flags ,bool thesaurus ) 1948{ 1949char * dict = dict_start ; 1950char * ptr ; 1951regmatch_T regmatch ; 1952char ** files ; 1953int count ; 1954Direction dir = compl_direction ; 1955 1956if (* dict == NUL ) { 1957// When 'dictionary' is empty and spell checking is enabled use 1958// "spell". 1959if (!thesaurus && curwin -> w_p_spell ) { 1960dict = "spell" ; 1961 }else { 1962return ; 1963 } 1964 } 1965 1966char * buf = xmalloc (LSIZE ); 1967regmatch .regprog = NULL ;// so that we can goto theend 1968 1969// If 'infercase' is set, don't use 'smartcase' here 1970int save_p_scs = p_scs ; 1971if (curbuf -> b_p_inf ) { 1972p_scs = false; 1973 } 1974 1975// When invoked to match whole lines for CTRL-X CTRL-L adjust the pattern 1976// to only match at the start of a line. Otherwise just match the 1977// pattern. Also need to double backslashes. 1978if (ctrl_x_mode_line_or_eval ()) { 1979char * pat_esc = vim_strsave_escaped (pat ,"\\" ); 1980 1981size_t len = strlen (pat_esc )+ 10 ; 1982ptr = xmalloc (len ); 1983vim_snprintf (ptr ,len ,"^\\s*\\zs\\V%s" ,pat_esc ); 1984regmatch .regprog = vim_regcomp (ptr ,RE_MAGIC ); 1985xfree (pat_esc ); 1986xfree (ptr ); 1987 }else { 1988regmatch .regprog = vim_regcomp (pat ,p_magic ?RE_MAGIC :0 ); 1989if (regmatch .regprog == NULL ) { 1990 gototheend ; 1991 } 1992 } 1993 1994// ignore case depends on 'ignorecase', 'smartcase' and "pat" 1995regmatch .rm_ic = ignorecase (pat ); 1996while (* dict != NUL && !got_int && !compl_interrupted ) { 1997// copy one dictionary file name into buf 1998if (flags == DICT_EXACT ) { 1999count = 1 ; 2000files = & dict ; 2001 }else { 2002// Expand wildcards in the dictionary name, but do not allow 2003// backticks (for security, the 'dict' option may have been set in 2004// a modeline). 2005copy_option_part (& dict ,buf ,LSIZE ,"," ); 2006if (!thesaurus && strcmp (buf ,"spell" )== 0 ) { 2007count = -1 ; 2008 }else if (vim_strchr (buf ,'`' )!= NULL 2009|| expand_wildcards (1 ,& buf ,& count ,& files , 2010EW_FILE |EW_SILENT )!= OK ) { 2011count = 0 ; 2012 } 2013 } 2014 2015if (count == -1 ) { 2016// Complete from active spelling. Skip "\<" in the pattern, we 2017// don't use it as a RE. 2018if (pat [0 ]== '\\' && pat [1 ]== '<' ) { 2019ptr = pat + 2 ; 2020 }else { 2021ptr = pat ; 2022 } 2023spell_dump_compl (ptr ,regmatch .rm_ic ,& dir ,0 ); 2024 }else if (count > 0 ) {// avoid warning for using "files" uninit 2025ins_compl_files (count ,files ,thesaurus ,flags ,& regmatch ,buf ,& dir ); 2026if (flags != DICT_EXACT ) { 2027FreeWild (count ,files ); 2028 } 2029 } 2030if (flags != 0 ) { 2031break ; 2032 } 2033 } 2034 2035theend : 2036p_scs = save_p_scs ; 2037vim_regfree (regmatch .regprog ); 2038xfree (buf ); 2039} 2040 2041/// Add all the words in the line "*buf_arg" from the thesaurus file "fname" 2042/// skipping the word at 'skip_word'. 2043/// 2044/// @return OK on success. 2045static int thesaurus_add_words_in_line (char * fname ,char ** buf_arg ,int dir ,const char * skip_word ) 2046{ 2047int status = OK ; 2048 2049// Add the other matches on the line 2050char * ptr = * buf_arg ; 2051while (!got_int ) { 2052// Find start of the next word. Skip white 2053// space and punctuation. 2054ptr = find_word_start (ptr ); 2055if (* ptr == NUL || * ptr == NL ) { 2056break ; 2057 } 2058char * wstart = ptr ; 2059 2060// Find end of the word. 2061// Japanese words may have characters in 2062// different classes, only separate words 2063// with single-byte non-word characters. 2064while (* ptr != NUL ) { 2065const int l = utfc_ptr2len (ptr ); 2066 2067if (l < 2 && !vim_iswordc ((uint8_t )(* ptr ))) { 2068break ; 2069 } 2070ptr += l ; 2071 } 2072 2073// Add the word. Skip the regexp match. 2074if (wstart != skip_word ) { 2075status = ins_compl_add_infercase (wstart , (int )(ptr - wstart ),p_ic , 2076fname ,dir , false,FUZZY_SCORE_NONE ); 2077if (status == FAIL ) { 2078break ; 2079 } 2080 } 2081 } 2082 2083* buf_arg = ptr ; 2084return status ; 2085} 2086 2087/// Process "count" dictionary/thesaurus "files" and add the text matching 2088/// "regmatch". 2089static void ins_compl_files (int count ,char ** files ,bool thesaurus ,int flags , 2090regmatch_T * regmatch ,char * buf ,Direction * dir ) 2091FUNC_ATTR_NONNULL_ARG (2 ,7 ) 2092{ 2093char * leader = cot_fuzzy () ?ins_compl_leader () :NULL ; 2094int leader_len = cot_fuzzy () ? (int )ins_compl_leader_len () :0 ; 2095 2096for (int i = 0 ;i < count && !got_int && !ins_compl_interrupted ();i ++ ) { 2097FILE * fp = os_fopen (files [i ],"r" );// open dictionary file 2098if (flags != DICT_EXACT && !shortmess (kShmCompletionscan )&& !compl_autocomplete ) { 2099vim_snprintf (IObuff ,IOSIZE ,_ ("Scanning dictionary: %s" ),files [i ]); 2100msg_progress (IObuff ,"nvim.completion" ,"running" ,HLF_R , false, true, false); 2101 } 2102 2103if (fp == NULL ) { 2104continue ; 2105 } 2106 2107// Read dictionary file line by line. 2108// Check each line for a match. 2109while (!got_int && !ins_compl_interrupted ()&& !vim_fgets (buf ,LSIZE ,fp )) { 2110char * ptr = buf ; 2111if (cot_fuzzy ()&& leader_len > 0 ) { 2112char * line_end = find_line_end (ptr ); 2113while (ptr < line_end ) { 2114int score = 0 ; 2115int len = 0 ; 2116if (fuzzy_match_str_in_line (& ptr ,leader ,& len ,NULL ,& score )) { 2117char * end_ptr = ctrl_x_mode_line_or_eval () 2118 ?find_line_end (ptr ) :find_word_end (ptr ); 2119int add_r = ins_compl_add_infercase (ptr , (int )(end_ptr - ptr ), 2120p_ic ,files [i ],* dir , false,score ); 2121if (add_r == FAIL ) { 2122break ; 2123 } 2124ptr = end_ptr ;// start from next word 2125if (compl_get_longest && ctrl_x_mode_normal () 2126&& compl_first_match -> cp_next 2127&& score == compl_first_match -> cp_next -> cp_score ) { 2128compl_num_bests ++ ; 2129 } 2130 } 2131 } 2132 }else if (regmatch != NULL ) { 2133while (vim_regexec (regmatch ,buf , (colnr_T )(ptr - buf ))) { 2134ptr = regmatch -> startp [0 ]; 2135ptr = ctrl_x_mode_line_or_eval () ?find_line_end (ptr ) :find_word_end (ptr ); 2136int add_r = ins_compl_add_infercase (regmatch -> startp [0 ], 2137 (int )(ptr - regmatch -> startp [0 ]), 2138p_ic ,files [i ],* dir , false, 2139FUZZY_SCORE_NONE ); 2140if (thesaurus ) { 2141// For a thesaurus, add all the words in the line 2142ptr = buf ; 2143add_r = thesaurus_add_words_in_line (files [i ],& ptr ,* dir ,regmatch -> startp [0 ]); 2144 } 2145if (add_r == OK ) { 2146// if dir was BACKWARD then honor it just once 2147* dir = FORWARD ; 2148 }else if (add_r == FAIL ) { 2149break ; 2150 } 2151// avoid expensive call to vim_regexec() when at end 2152// of line 2153if (* ptr == '\n' || got_int ) { 2154break ; 2155 } 2156 } 2157 } 2158line_breakcheck (); 2159ins_compl_check_keys (50 , false); 2160 } 2161fclose (fp ); 2162 } 2163} 2164 2165/// Find the start of the next word. 2166/// Returns a pointer to the first char of the word. Also stops at a NUL. 2167char * find_word_start (char * ptr ) 2168FUNC_ATTR_PURE 2169{ 2170while (* ptr != NUL && * ptr != '\n' && mb_get_class (ptr ) <=1 ) { 2171ptr += utfc_ptr2len (ptr ); 2172 } 2173return ptr ; 2174} 2175 2176/// Find the end of the word. Assumes it starts inside a word. 2177/// Returns a pointer to just after the word. 2178char * find_word_end (char * ptr ) 2179FUNC_ATTR_PURE 2180{ 2181const int start_class = mb_get_class (ptr ); 2182if (start_class > 1 ) { 2183while (* ptr != NUL ) { 2184ptr += utfc_ptr2len (ptr ); 2185if (mb_get_class (ptr )!= start_class ) { 2186break ; 2187 } 2188 } 2189 } 2190return ptr ; 2191} 2192 2193/// Find the end of the line, omitting CR and NL at the end. 2194/// 2195/// @return a pointer to just after the line. 2196char * find_line_end (char * ptr ) 2197{ 2198char * s = ptr + strlen (ptr ); 2199while (s > ptr && (s [-1 ]== CAR || s [-1 ]== NL )) { 2200s -- ; 2201 } 2202return s ; 2203} 2204 2205/// Free a completion item in the list 2206static void ins_compl_item_free (compl_T * match ) 2207{ 2208// Uncount the match string in the duplicate-check hashtab; the entry is 2209// only removed with its last match. The hashtab is empty when it was 2210// already cleared as a whole by ins_compl_free(). 2211if (compl_strings_ht .ht_used > 0 && match -> cp_str .data != NULL 2212&& !match_at_original_text (match )) { 2213hashitem_T * hi = hash_find (& compl_strings_ht ,match -> cp_str .data ); 2214if (!HASHITEM_EMPTY (hi )) { 2215complstr_T * entry = HI2CSE (hi ); 2216if (-- entry -> cse_count <=0 ) { 2217hash_remove (& compl_strings_ht ,hi ); 2218xfree (entry ); 2219 } 2220 } 2221 } 2222API_CLEAR_STRING (match -> cp_str ); 2223// several entries may use the same fname, free it just once. 2224if (match -> cp_flags & CP_FREE_FNAME ) { 2225xfree (match -> cp_fname ); 2226 } 2227free_cptext (match -> cp_text ); 2228tv_clear (& match -> cp_user_data ); 2229xfree (match -> cp_commit_chars ); 2230xfree (match ); 2231} 2232 2233/// Free the list of completions 2234static void ins_compl_free (void ) 2235{ 2236API_CLEAR_STRING (compl_pattern ); 2237API_CLEAR_STRING (compl_leader ); 2238 2239if (compl_first_match == NULL ) { 2240return ; 2241 } 2242 2243ins_compl_del_pum (); 2244pum_clear (); 2245 2246// Free the duplicate-check hashtab entries all at once, then freeing 2247// the matches below does not need to uncount them one by one. 2248hash_clear_all (& compl_strings_ht ,CSE_OFF ); 2249hash_init (& compl_strings_ht ); 2250 2251compl_curr_match = compl_first_match ; 2252do { 2253compl_T * match = compl_curr_match ; 2254compl_curr_match = compl_curr_match -> cp_next ; 2255ins_compl_item_free (match ); 2256 }while (compl_curr_match != NULL && !is_first_match (compl_curr_match )); 2257compl_first_match = compl_curr_match = NULL ; 2258compl_shown_match = NULL ; 2259compl_preselect_match = NULL ; 2260compl_old_match = NULL ; 2261} 2262 2263/// Reset/clear the completion state. 2264void ins_compl_clear (void ) 2265{ 2266compl_cont_status = 0 ; 2267compl_started = false; 2268compl_matches = 0 ; 2269compl_selected_item = -1 ; 2270compl_ins_end_col = 0 ; 2271compl_longest_end_col = 0 ; 2272compl_curr_win = NULL ; 2273compl_curr_buf = NULL ; 2274API_CLEAR_STRING (compl_pattern ); 2275API_CLEAR_STRING (compl_leader ); 2276edit_submode_extra = NULL ; 2277kv_destroy (compl_orig_extmarks ); 2278API_CLEAR_STRING (compl_orig_text ); 2279compl_enter_selects = false; 2280cpt_sources_clear (); 2281compl_autocomplete = false; 2282compl_from_nonkeyword = false; 2283compl_autostarted = false; 2284compl_num_bests = 0 ; 2285// clear v:completed_item 2286set_vim_var_dict (VV_COMPLETED_ITEM ,tv_dict_alloc_lock (VAR_FIXED )); 2287} 2288 2289/// Check that Insert completion is active. 2290bool ins_compl_active (void ) 2291FUNC_ATTR_PURE 2292{ 2293return compl_started ; 2294} 2295 2296/// Return true when wp is the actual completion window 2297bool ins_compl_win_active (win_T * wp ) 2298{ 2299return ins_compl_active ()&& wp == compl_curr_win && wp -> w_buffer == compl_curr_buf ; 2300} 2301 2302/// Selected one of the matches. When false, the match was edited or 2303/// using the longest common string. 2304bool ins_compl_used_match (void ) 2305{ 2306return compl_used_match ; 2307} 2308 2309/// Initialize get longest common string. 2310void ins_compl_init_get_longest (void ) 2311{ 2312compl_get_longest = false; 2313} 2314 2315/// Returns true when insert completion is interrupted. 2316bool ins_compl_interrupted (void ) 2317{ 2318return compl_interrupted || compl_time_slice_expired ; 2319} 2320 2321/// Returns true if the <Enter> key selects a match in the completion popup 2322/// menu. 2323bool ins_compl_enter_selects (void ) 2324{ 2325return compl_enter_selects ; 2326} 2327 2328/// Return the column where the text starts that is being completed 2329colnr_T ins_compl_col (void ) 2330{ 2331return compl_col ; 2332} 2333 2334/// Return the length in bytes of the text being completed 2335int ins_compl_len (void ) 2336{ 2337return compl_length ; 2338} 2339 2340/// Return true when the 'completeopt' "preinsert" flag is in effect, 2341/// otherwise return false. 2342bool ins_compl_has_preinsert (void ) 2343{ 2344unsigned cur_cot_flags = get_cot_flags (); 2345if (compl_autocomplete && p_ic && !p_inf ) { 2346return false; 2347 } 2348return (!compl_autocomplete 2349 ? (cur_cot_flags & (kOptCotFlagPreinsert |kOptCotFlagFuzzy |kOptCotFlagMenuone )) 2350== (kOptCotFlagPreinsert |kOptCotFlagMenuone ) 2351 : (cur_cot_flags & (kOptCotFlagPreinsert |kOptCotFlagFuzzy )) 2352== kOptCotFlagPreinsert ); 2353} 2354 2355/// Returns true if the pre-insert effect is valid and the cursor is within 2356/// the `compl_ins_end_col` range. 2357bool ins_compl_preinsert_effect (void ) 2358{ 2359if (!ins_compl_has_preinsert ()&& !ins_compl_preinsert_longest ()) { 2360return false; 2361 } 2362 2363return curwin -> w_cursor .col < compl_ins_end_col ; 2364} 2365 2366/// Delete one character before the cursor and show the subset of the matches 2367/// that match the word that is now before the cursor. 2368/// Returns the character to be used, NUL if the work is done and another char 2369/// to be got from the user. 2370int ins_compl_bs (void ) 2371{ 2372if (ins_compl_preinsert_effect ()) { 2373ins_compl_delete (false); 2374 } 2375 2376char * line = get_cursor_line_ptr (); 2377char * p = line + curwin -> w_cursor .col ; 2378MB_PTR_BACK (line ,p ); 2379ptrdiff_t p_off = p - line ; 2380 2381// Stop completion when the whole word was deleted. For Omni completion 2382// allow the word to be deleted, we won't match everything. 2383// Respect the 'backspace' option. 2384if ((int )(p - line )- (int )compl_col < 0 2385|| ((int )(p - line )- (int )compl_col == 0 && !ctrl_x_mode_omni ()) 2386|| ctrl_x_mode_eval () 2387|| (!can_bs (BS_START )&& (int )(p - line )- (int )compl_col 2388- compl_length < 0 )) { 2389return K_BS ; 2390 } 2391 2392// Deleted more than what was used to find matches or didn't finish 2393// finding all matches: need to look for matches all over again. 2394if (curwin -> w_cursor .col <=compl_col + compl_length 2395|| ins_compl_need_restart ()) { 2396ins_compl_restart (); 2397 } 2398 2399// ins_compl_restart() calls update_screen() which may invalidate the pointer 2400// TODO(bfredl): get rid of random update_screen() calls deep inside completion logic 2401line = get_cursor_line_ptr (); 2402 2403API_CLEAR_STRING (compl_leader ); 2404compl_leader = cbuf_to_string (line + compl_col , 2405 (size_t )(p_off - (ptrdiff_t )compl_col )); 2406 2407// Clear selection if a menu item is currently selected in autocompletion 2408if (compl_autocomplete && compl_first_match && !ins_compl_has_preinsert ()) { 2409compl_shown_match = compl_first_match ; 2410 } 2411 2412ins_compl_new_leader (); 2413if (compl_shown_match != NULL ) { 2414// Make sure current match is not a hidden item. 2415compl_curr_match = compl_shown_match ; 2416 } 2417return NUL ; 2418} 2419 2420/// Check if the complete function returned "always" in the "refresh" dictionary item. 2421static bool ins_compl_refresh_always (void ) 2422FUNC_ATTR_PURE 2423{ 2424return (ctrl_x_mode_function ()|| ctrl_x_mode_omni ())&& compl_opt_refresh_always ; 2425} 2426 2427/// Check that we need to find matches again, ins_compl_restart() is to 2428/// be called. 2429static bool ins_compl_need_restart (void ) 2430FUNC_ATTR_PURE 2431{ 2432// Return true if we didn't complete finding matches or when the 2433// "completefunc" returned "always" in the "refresh" dictionary item. 2434return compl_was_interrupted || ins_compl_refresh_always (); 2435} 2436 2437/// Return true if 'autocomplete' option is set 2438bool ins_compl_has_autocomplete (void ) 2439{ 2440// Use buffer-local setting if defined (>= 0), otherwise use global 2441return curbuf -> b_p_ac >=0 ?curbuf -> b_p_ac :p_ac ; 2442} 2443 2444/// Calculate fuzzy score and sort completion matches unless sorting is disabled. 2445static void ins_compl_fuzzy_sort (void ) 2446{ 2447unsigned cur_cot_flags = get_cot_flags (); 2448 2449// Set the fuzzy score in cp_score and sort 2450set_fuzzy_score (); 2451if (!(cur_cot_flags & kOptCotFlagNosort )) { 2452sort_compl_match_list (cp_compare_fuzzy ); 2453// Reset the shown item since sorting reorders items 2454if ((cur_cot_flags & (kOptCotFlagNoinsert |kOptCotFlagNoselect ))== kOptCotFlagNoinsert ) { 2455bool none_selected = compl_shown_match == (compl_shows_dir_forward () 2456 ?compl_first_match :compl_first_match -> cp_prev ); 2457if (!none_selected ) { 2458compl_shown_match = (!compl_autocomplete && compl_shows_dir_forward ()) 2459 ?compl_first_match -> cp_next :compl_first_match ; 2460 } 2461 } 2462 } 2463} 2464 2465/// Called after changing "compl_leader". 2466/// Show the popup menu with a different set of matches. 2467/// May also search for matches again if the previous search was interrupted. 2468static void ins_compl_new_leader (void ) 2469{ 2470ins_compl_del_pum (); 2471ins_compl_delete (true); 2472ins_compl_insert_bytes (compl_leader .data + get_compl_len (),-1 ); 2473compl_used_match = false; 2474 2475int save_w_wrow = curwin -> w_wrow ; 2476int save_w_leftcol = curwin -> w_leftcol ; 2477if (compl_started ) { 2478ins_compl_set_original_text (compl_leader .data ,compl_leader .size ); 2479if (is_cpt_func_refresh_always ()) { 2480cpt_compl_refresh (); 2481 } 2482if (cot_fuzzy ()) { 2483ins_compl_fuzzy_sort (); 2484 } 2485 }else { 2486spell_bad_len = 0 ;// need to redetect bad word 2487// Matches were cleared, need to search for them now. 2488// Set "compl_restarting" to avoid that the first match is inserted. 2489compl_restarting = true; 2490if (ins_compl_has_autocomplete ()) { 2491ins_compl_enable_autocomplete (); 2492 }else { 2493compl_autocomplete = false; 2494 } 2495if (ins_complete (Ctrl_N , false)== FAIL ) { 2496compl_cont_status = 0 ; 2497 } 2498compl_restarting = false; 2499 } 2500 2501compl_enter_selects = !compl_used_match && compl_selected_item != -1 ; 2502 2503// Show the popup menu with a different set of matches. With 2504// 'autocompletedelay' the menu is already visible here, so update it 2505// immediately rather than re-arming the delay, like a zero delay does. 2506if (!compl_interrupted ) { 2507show_pum (save_w_wrow ,save_w_leftcol ); 2508 } 2509 2510// Don't let Enter select the original text when there is no popup menu. 2511if (compl_match_array == NULL ) { 2512compl_enter_selects = false; 2513 }else if (ins_compl_has_preinsert ()&& compl_leader .size > 0 ) { 2514ins_compl_insert (true, false); 2515 }else if (compl_started && ins_compl_preinsert_longest () 2516&& compl_leader .size > 0 && !ins_compl_preinsert_effect ()) { 2517ins_compl_insert (true, true); 2518 } 2519// Don't let Enter select when use user function and refresh_always is set 2520if (ins_compl_refresh_always ()) { 2521compl_enter_selects = false; 2522 } 2523} 2524 2525/// Return the length of the completion, from the completion start column to 2526/// the cursor column. Making sure it never goes below zero. 2527static int get_compl_len (void ) 2528{ 2529int off = (int )curwin -> w_cursor .col - (int )compl_col ; 2530return MAX (0 ,off ); 2531} 2532 2533/// Append one character to the match leader. May reduce the number of 2534/// matches. 2535void ins_compl_addleader (int c ) 2536{ 2537int cc ; 2538 2539if (ins_compl_preinsert_effect ()) { 2540ins_compl_delete (false); 2541 } 2542 2543if (stop_arrow ()== FAIL ) { 2544return ; 2545 } 2546if ((cc = utf_char2len (c ))> 1 ) { 2547char buf [MB_MAXCHAR + 1 ]; 2548 2549utf_char2bytes (c ,buf ); 2550buf [cc ]= NUL ; 2551ins_char_bytes (buf , (size_t )cc ); 2552 }else { 2553ins_char (c ); 2554 } 2555 2556// If we didn't complete finding matches we must search again. 2557if (ins_compl_need_restart ()) { 2558ins_compl_restart (); 2559 } 2560 2561API_CLEAR_STRING (compl_leader ); 2562compl_leader = cbuf_to_string (get_cursor_line_ptr ()+ compl_col , 2563 (size_t )(curwin -> w_cursor .col - compl_col )); 2564ins_compl_new_leader (); 2565} 2566 2567/// Setup for finding completions again without leaving CTRL-X mode. Used when 2568/// BS or a key was typed while still searching for matches. 2569static void ins_compl_restart (void ) 2570{ 2571// update screen before restart. 2572// so if complete is blocked, 2573// will stay to the last popup menu and reduce flicker 2574update_screen ();// TODO(bfredl): no. 2575ins_compl_free (); 2576compl_started = false; 2577compl_matches = 0 ; 2578compl_cont_status = 0 ; 2579compl_cont_mode = 0 ; 2580cpt_sources_clear (); 2581compl_autocomplete = false; 2582compl_from_nonkeyword = false; 2583compl_autostarted = false; 2584compl_num_bests = 0 ; 2585} 2586 2587/// Set the first match, the original text. 2588static void ins_compl_set_original_text (char * str ,size_t len ) 2589FUNC_ATTR_NONNULL_ALL 2590{ 2591// Replace the original text entry. 2592compl_T * match = find_original_text_match (); 2593if (match == NULL ) { 2594return ; 2595 } 2596 2597API_CLEAR_STRING (match -> cp_str ); 2598match -> cp_str = cbuf_to_string (str ,len ); 2599} 2600 2601/// Append one character to the match leader. May reduce the number of 2602/// matches. 2603void ins_compl_addfrommatch (void ) 2604{ 2605int len = (int )curwin -> w_cursor .col - (int )compl_col ; 2606assert (compl_shown_match != NULL ); 2607char * p = compl_shown_match -> cp_str .data ; 2608if ((int )compl_shown_match -> cp_str .size <=len ) {// the match is too short 2609// When still at the original match use the first entry that matches 2610// the leader. 2611if (!match_at_original_text (compl_shown_match )) { 2612return ; 2613 } 2614 2615p = NULL ; 2616size_t plen = 0 ; 2617for (compl_T * cp = compl_shown_match -> cp_next ;cp != NULL 2618&& !is_first_match (cp );cp = cp -> cp_next ) { 2619if (compl_leader .data == NULL 2620|| ins_compl_equal (cp ,compl_leader .data ,compl_leader .size )) { 2621p = cp -> cp_str .data ; 2622plen = cp -> cp_str .size ; 2623break ; 2624 } 2625 } 2626if (p == NULL || (int )plen <=len ) { 2627return ; 2628 } 2629 } 2630p += len ; 2631int c = utf_ptr2char (p ); 2632ins_compl_addleader (c ); 2633} 2634 2635/// Set the CTRL-X completion mode based on the key "c" typed after a CTRL-X. 2636/// Uses the global variables: ctrl_x_mode, edit_submode, edit_submode_pre, 2637/// compl_cont_mode and compl_cont_status. 2638/// 2639/// @return true when the character is not to be inserted. 2640static bool set_ctrl_x_mode (const int c ) 2641{ 2642bool retval = false; 2643 2644switch (c ) { 2645case Ctrl_E : 2646case Ctrl_Y : 2647// scroll the window one line up or down 2648ctrl_x_mode = CTRL_X_SCROLL ; 2649if (!(State & REPLACE_FLAG )) { 2650edit_submode = _ (" (insert) Scroll (^E/^Y)" ); 2651 }else { 2652edit_submode = _ (" (replace) Scroll (^E/^Y)" ); 2653 } 2654edit_submode_pre = NULL ; 2655redraw_mode = true; 2656break ; 2657case Ctrl_L : 2658// complete whole line 2659ctrl_x_mode = CTRL_X_WHOLE_LINE ; 2660break ; 2661case Ctrl_F : 2662// complete filenames 2663ctrl_x_mode = CTRL_X_FILES ; 2664break ; 2665case Ctrl_K : 2666// complete words from a dictionary 2667ctrl_x_mode = CTRL_X_DICTIONARY ; 2668break ; 2669case Ctrl_R : 2670// When CTRL-R is followed by '=', don't trigger register completion 2671// This allows expressions like <C-R>=func()<CR> to work normally 2672if (vpeekc ()== '=' ) { 2673break ; 2674 } 2675ctrl_x_mode = CTRL_X_REGISTER ; 2676break ; 2677case Ctrl_T : 2678// complete words from a thesaurus 2679ctrl_x_mode = CTRL_X_THESAURUS ; 2680break ; 2681case Ctrl_U : 2682// user defined completion 2683ctrl_x_mode = CTRL_X_FUNCTION ; 2684break ; 2685case Ctrl_O : 2686// omni completion 2687ctrl_x_mode = CTRL_X_OMNI ; 2688break ; 2689case 's' : 2690case Ctrl_S : 2691// complete spelling suggestions 2692ctrl_x_mode = CTRL_X_SPELL ; 2693emsg_off ++ ;// Avoid getting the E756 error twice. 2694spell_back_to_badword (); 2695emsg_off -- ; 2696break ; 2697case Ctrl_RSB : 2698// complete tag names 2699ctrl_x_mode = CTRL_X_TAGS ; 2700break ; 2701case Ctrl_I : 2702case K_S_TAB : 2703// complete keywords from included files 2704ctrl_x_mode = CTRL_X_PATH_PATTERNS ; 2705break ; 2706case Ctrl_D : 2707// complete definitions from included files 2708ctrl_x_mode = CTRL_X_PATH_DEFINES ; 2709break ; 2710case Ctrl_V : 2711case Ctrl_Q : 2712// complete vim commands 2713ctrl_x_mode = CTRL_X_CMDLINE ; 2714break ; 2715case Ctrl_Z : 2716// stop completion 2717ctrl_x_mode = CTRL_X_NORMAL ; 2718edit_submode = NULL ; 2719redraw_mode = true; 2720retval = true; 2721break ; 2722case Ctrl_P : 2723case Ctrl_N : 2724// ^X^P means LOCAL expansion if nothing interrupted (eg we 2725// just started ^X mode, or there were enough ^X's to cancel 2726// the previous mode, say ^X^F^X^X^P or ^P^X^X^X^P, see below) 2727// do normal expansion when interrupting a different mode (say 2728// ^X^F^X^P or ^P^X^X^P, see below) 2729// nothing changes if interrupting mode 0, (eg, the flag 2730// doesn't change when going to ADDING mode -- Acevedo 2731if (!(compl_cont_status & CONT_INTRPT )) { 2732compl_cont_status |=CONT_LOCAL ; 2733 }else if (compl_cont_mode != 0 ) { 2734compl_cont_status &= ~CONT_LOCAL ; 2735 } 2736FALLTHROUGH ; 2737default : 2738// If we have typed at least 2 ^X's... for modes != 0, we set 2739// compl_cont_status = 0 (eg, as if we had just started ^X 2740// mode). 2741// For mode 0, we set "compl_cont_mode" to an impossible 2742// value, in both cases ^X^X can be used to restart the same 2743// mode (avoiding ADDING mode). 2744// Undocumented feature: In a mode != 0 ^X^P and ^X^X^P start 2745// 'complete' and local ^P expansions respectively. 2746// In mode 0 an extra ^X is needed since ^X^P goes to ADDING 2747// mode -- Acevedo 2748if (c == Ctrl_X ) { 2749if (compl_cont_mode != 0 ) { 2750compl_cont_status = 0 ; 2751 }else { 2752compl_cont_mode = CTRL_X_NOT_DEFINED_YET ; 2753 } 2754 } 2755ctrl_x_mode = CTRL_X_NORMAL ; 2756edit_submode = NULL ; 2757redraw_mode = true; 2758break ; 2759 } 2760 2761return retval ; 2762} 2763 2764/// Stop insert completion mode 2765static bool ins_compl_stop (const int c ,const int prev_mode ,bool retval ) 2766{ 2767// Remove pre-inserted text when present. 2768if (ins_compl_preinsert_effect ()&& ins_compl_win_active (curwin )) { 2769ins_compl_delete (false); 2770 } 2771 2772// Get here when we have finished typing a sequence of ^N and 2773// ^P or other completion characters in CTRL-X mode. Free up 2774// memory that was used, and make sure we can redo the insert. 2775if (compl_curr_match != NULL || compl_leader .data != NULL || c == Ctrl_E ) { 2776// If any of the original typed text has been changed, eg when 2777// ignorecase is set, we must add back-spaces to the redo 2778// buffer. We add as few as necessary to delete just the part 2779// of the original text that has changed. 2780// When using the longest match, edited the match or used 2781// CTRL-E then don't use the current match. 2782char * ptr = NULL ; 2783if (compl_curr_match != NULL && compl_used_match && c != Ctrl_E ) { 2784ptr = compl_curr_match -> cp_str .data ; 2785 } 2786ins_compl_fixRedoBufForLeader (ptr ); 2787 } 2788 2789bool want_cindent = (get_can_cindent ()&& cindent_on ()); 2790 2791// When completing whole lines: fix indent for 'cindent'. 2792// Otherwise, break line if it's too long. 2793if (compl_cont_mode == CTRL_X_WHOLE_LINE ) { 2794// re-indent the current line 2795if (want_cindent ) { 2796do_c_expr_indent (); 2797want_cindent = false;// don't do it again 2798 } 2799 }else if (!compl_autocomplete || compl_used_match ) { 2800const int prev_col = curwin -> w_cursor .col ; 2801 2802// put the cursor on the last char, for 'tw' formatting 2803if (prev_col > 0 ) { 2804dec_cursor (); 2805 } 2806 2807// only format when something was inserted 2808if (Ins .moved == kInsNone && !Ins .need_undo && c != Ctrl_E ) { 2809insertchar (NUL ,0 ,-1 ); 2810 } 2811 2812if (prev_col > 0 2813&& get_cursor_line_ptr ()[curwin -> w_cursor .col ]!= NUL ) { 2814inc_cursor (); 2815 } 2816 } 2817 2818String word = STRING_INIT ; 2819const bool is_commit = pum_visible ()&& ins_compl_commit_char (c ); 2820// If the popup menu is displayed pressing CTRL-Y means accepting 2821// the selection without inserting anything. When 2822// compl_enter_selects is set the Enter key does the same. 2823// Note: Unlike Ctrl_Y, a commit-char accepts the match but does not consume the key. 2824if ((c == Ctrl_Y || is_commit || (compl_enter_selects 2825&& (c == CAR || c == K_KENTER || c == NL ))) 2826&& pum_visible ()) { 2827word = copy_string (compl_shown_match -> cp_str ,NULL ); 2828if (!is_commit ) { 2829retval = true; 2830 } 2831// May need to remove ComplMatchIns highlight. 2832redrawWinline (curwin ,curwin -> w_cursor .lnum ); 2833 } 2834 2835// When a match was inserted but the pum was never displayed 2836// (eg: only one match with 'completeopt' "menu" without "menuone"), 2837// the user had no opportunity to explicitly accept or dismiss it, 2838// so treat this as an implicit accept (#38160). 2839if (word .data == NULL && c != Ctrl_E && compl_used_match && compl_match_array == NULL 2840&& compl_curr_match != NULL 2841&& compl_curr_match -> cp_str .data != NULL ) { 2842word = copy_string (compl_curr_match -> cp_str ,NULL ); 2843 } 2844 2845// CTRL-E means completion is Ended, go back to the typed text. 2846// but only do this, if the Popup is still visible 2847if (c == Ctrl_E ) { 2848ins_compl_delete (false); 2849char * p = NULL ; 2850size_t plen = 0 ; 2851if (compl_leader .data != NULL ) { 2852p = compl_leader .data ; 2853plen = compl_leader .size ; 2854 }else if (compl_first_match != NULL ) { 2855p = compl_orig_text .data ; 2856plen = compl_orig_text .size ; 2857 } 2858if (p != NULL ) { 2859const int compl_len = get_compl_len (); 2860if ((int )plen > compl_len ) { 2861ins_compl_insert_bytes (p + compl_len , (int )plen - compl_len ); 2862 } 2863 } 2864restore_orig_extmarks (); 2865retval = true; 2866 } 2867 2868auto_format (false, true); 2869 2870// Trigger the CompleteDonePre event to give scripts a chance to 2871// act upon the completion before clearing the info, and restore 2872// ctrl_x_mode, so that complete_info() can be used. 2873ctrl_x_mode = prev_mode ; 2874ins_apply_autocmds (EVENT_COMPLETEDONEPRE ); 2875 2876ins_compl_free (); 2877compl_started = false; 2878compl_matches = 0 ; 2879if (!shortmess (kShmCompletionmenu )) { 2880msg_clr_cmdline ();// necessary for "noshowmode" 2881 } 2882ctrl_x_mode = CTRL_X_NORMAL ; 2883compl_enter_selects = false; 2884if (edit_submode != NULL ) { 2885edit_submode = NULL ; 2886redraw_mode = true; 2887 } 2888compl_autocomplete = false; 2889compl_from_nonkeyword = false; 2890compl_autostarted = false; 2891compl_num_bests = 0 ; 2892compl_ins_end_col = 0 ; 2893 2894if (c == Ctrl_C && bt_cmdwin (curbuf )) { 2895// Avoid the popup menu remains displayed when leaving the 2896// command line window. 2897update_screen (); 2898 } 2899 2900// Indent now if a key was typed that is in 'cinkeys'. 2901if (want_cindent && in_cinkeys (KEY_COMPLETE ,' ' ,inindent (0 ))) { 2902do_c_expr_indent (); 2903 } 2904// Trigger the CompleteDone event to give scripts a chance to act 2905// upon the end of completion. 2906do_autocmd_completedone (c ,prev_mode ,& word ); 2907xfree (word .data ); 2908 2909return retval ; 2910} 2911 2912/// Cancel completion. 2913bool ins_compl_cancel (void ) 2914{ 2915return ins_compl_stop (' ' ,ctrl_x_mode , true); 2916} 2917 2918/// Prepare for Insert mode completion, or stop it. 2919/// Called just after typing a character in Insert mode. 2920/// 2921/// @param c character that was typed 2922/// 2923/// @return true when the character is not to be inserted; 2924bool ins_compl_prep (int c ) 2925{ 2926bool retval = false; 2927const int prev_mode = ctrl_x_mode ; 2928 2929// Forget any previous 'special' messages if this is actually 2930// a ^X mode key - bar ^R, in which case we wait to see what it gives us. 2931if (c != Ctrl_R && vim_is_ctrl_x_key (c )) { 2932edit_submode_extra = NULL ; 2933 } 2934 2935// Ignore end of Select mode mapping and mouse scroll/movement. 2936if (c == K_SELECT || c == K_MOUSEDOWN || c == K_MOUSEUP 2937|| c == K_MOUSELEFT || c == K_MOUSERIGHT || c == K_MOUSEMOVE 2938|| c == K_EVENT || c == K_COMMAND || c == K_LUA ) { 2939return retval ; 2940 } 2941 2942if (ctrl_x_mode == CTRL_X_CMDLINE_CTRL_X && c != Ctrl_X ) { 2943if (c == Ctrl_V || c == Ctrl_Q || c == Ctrl_Z || ins_compl_pum_key (c ) 2944|| !vim_is_ctrl_x_key (c )) { 2945// Not starting another completion mode. 2946ctrl_x_mode = CTRL_X_CMDLINE ; 2947 2948// CTRL-X CTRL-Z should stop completion without inserting anything 2949if (c == Ctrl_Z ) { 2950retval = true; 2951 } 2952 }else { 2953ctrl_x_mode = CTRL_X_CMDLINE ; 2954 2955// Other CTRL-X keys first stop completion, then start another 2956// completion mode. 2957ins_compl_prep (' ' ); 2958ctrl_x_mode = CTRL_X_NOT_DEFINED_YET ; 2959 } 2960 } 2961 2962// Set "compl_get_longest" when finding the first matches. 2963if (ctrl_x_mode_not_defined_yet () 2964|| (ctrl_x_mode_normal ()&& !compl_started )) { 2965compl_get_longest = (get_cot_flags ()& kOptCotFlagLongest )!= 0 ; 2966compl_used_match = true; 2967 } 2968 2969if (ctrl_x_mode_not_defined_yet ()) { 2970// We have just typed CTRL-X and aren't quite sure which CTRL-X mode 2971// it will be yet. Now we decide. 2972retval = set_ctrl_x_mode (c ); 2973 }else if (ctrl_x_mode_not_default ()) { 2974// We're already in CTRL-X mode, do we stay in it? 2975if (c != Ctrl_R && !vim_is_ctrl_x_key (c )) { 2976ctrl_x_mode = ctrl_x_mode_scroll () ?CTRL_X_NORMAL :CTRL_X_FINISHED ; 2977edit_submode = NULL ; 2978 } 2979redraw_mode = true; 2980 } 2981 2982if (compl_started || ctrl_x_mode == CTRL_X_FINISHED ) { 2983// Show error message from attempted keyword completion (probably 2984// 'Pattern not found') until another key is hit, then go back to 2985// showing what mode we are in. 2986redraw_mode = true; 2987if ((ctrl_x_mode_normal () 2988&& c != Ctrl_N 2989&& c != Ctrl_P 2990&& c != Ctrl_R 2991&& !ins_compl_pum_key (c )) 2992|| ctrl_x_mode == CTRL_X_FINISHED ) { 2993retval = ins_compl_stop (c ,prev_mode ,retval ); 2994 } 2995 }else if (ctrl_x_mode == CTRL_X_LOCAL_MSG ) { 2996// Trigger the CompleteDone event to give scripts a chance to act 2997// upon the (possibly failed) completion. 2998do_autocmd_completedone (c ,ctrl_x_mode ,NULL ); 2999 } 3000 3001may_trigger_modechanged (); 3002 3003// reset continue_* if we left expansion-mode, if we stay they'll be 3004// (re)set properly in ins_complete() 3005if (c != Ctrl_R && !vim_is_ctrl_x_key (c )) { 3006compl_cont_status = 0 ; 3007compl_cont_mode = 0 ; 3008 } 3009 3010return retval ; 3011} 3012 3013/// Fix the redo buffer for the completion leader replacing some of the typed 3014/// text. This inserts backspaces and appends the changed text. 3015/// "ptr" is the known leader text or NUL. 3016static void ins_compl_fixRedoBufForLeader (char * ptr_arg ) 3017{ 3018int len = 0 ; 3019char * ptr = ptr_arg ; 3020 3021if (ptr == NULL ) { 3022if (compl_leader .data != NULL ) { 3023ptr = compl_leader .data ; 3024 }else { 3025return ;// nothing to do 3026 } 3027 } 3028if (compl_orig_text .data != NULL ) { 3029char * p = compl_orig_text .data ; 3030// Find length of common prefix between original text and new completion 3031while (p [len ]!= NUL && p [len ]== ptr [len ]) { 3032len ++ ; 3033 } 3034// Adjust length to not break inside a multi-byte character 3035if (len > 0 ) { 3036len -= utf_head_off (p ,p + len ); 3037 } 3038// Add backspace characters for each remaining character in original text 3039for (p += len ;* p != NUL ;MB_PTR_ADV (p )) { 3040redo_append_char (K_BS ); 3041 } 3042 } 3043redo_append_lit (ptr + len ,-1 ); 3044} 3045 3046/// Loops through the list of windows, loaded-buffers or non-loaded-buffers 3047/// (depending on flag) starting from buf and looking for a non-scanned 3048/// buffer (other than curbuf). curbuf is special, if it is called with 3049/// buf=curbuf then it has to be the first call for a given flag/expansion. 3050/// 3051/// Returns the buffer to scan, if any, otherwise returns curbuf -- Acevedo 3052static buf_T * ins_compl_next_buf (buf_T * buf ,int flag ) 3053{ 3054static win_T * wp = NULL ; 3055 3056if (flag == 'w' ) {// just windows 3057if (buf == curbuf || !win_valid (wp )) { 3058// first call for this flag/expansion or window was closed 3059wp = curwin ; 3060 } 3061 3062assert (wp ); 3063while (true) { 3064// Move to next window (wrap to first window if at the end) 3065wp = (wp -> w_next != NULL ) ?wp -> w_next :firstwin ; 3066// Break if we're back at start or found an unscanned buffer (in a focusable window) 3067if (wp == curwin || (!wp -> w_buffer -> b_scanned && wp -> w_config .focusable )) { 3068break ; 3069 } 3070 } 3071buf = wp -> w_buffer ; 3072 }else { 3073// 'b' (just loaded buffers), 'u' (just non-loaded buffers) or 'U' 3074// (unlisted buffers) 3075// When completing whole lines skip unloaded buffers. 3076while (true) { 3077// Move to next buffer (wrap to first buffer if at the end) 3078buf = (buf -> b_next != NULL ) ?buf -> b_next :firstbuf ; 3079// Break if we're back at start buffer 3080if (buf == curbuf ) { 3081break ; 3082 } 3083 3084bool skip_buffer ; 3085// Check buffer conditions based on flag 3086if (flag == 'U' ) { 3087skip_buffer = buf -> b_p_bl ; 3088 }else { 3089skip_buffer = !buf -> b_p_bl || (buf -> b_ml .ml_mfp == NULL )!= (flag == 'u' ); 3090 } 3091 3092// Break if we found a buffer that matches our criteria 3093if (!skip_buffer && !buf -> b_scanned ) { 3094break ; 3095 } 3096 } 3097 } 3098return buf ; 3099} 3100 3101/// Count the number of entries in the 'complete' option value "cpt". 3102/// Each non-empty, comma-separated segment is counted as one entry. 3103static int get_cpt_sources_count (char * cpt ) 3104{ 3105char dummy [LSIZE ]; 3106int count = 0 ; 3107 3108for (char * p = cpt ;* p != NUL ;) { 3109while (* p == ',' || * p == ' ' ) { 3110p ++ ;// Skip delimiters 3111 } 3112if (* p != NUL ) { 3113 (void )copy_option_part (& p ,dummy ,LSIZE ,"," );// Advance p 3114count ++ ; 3115 } 3116 } 3117 3118return count ; 3119} 3120 3121static Callback * cpt_cb ;///< Callback functions associated with F{func} 3122static int cpt_cb_count ;///< Number of cpt callbacks 3123 3124/// Free an array of 'complete' F{func} callbacks and set the pointer to NULL. 3125void clear_cpt_callbacks (Callback ** callbacks ,int count ) 3126{ 3127if (callbacks == NULL || * callbacks == NULL ) { 3128return ; 3129 } 3130 3131for (int i = 0 ;i < count ;i ++ ) { 3132callback_free (& (* callbacks )[i ]); 3133 } 3134 3135XFREE_CLEAR (* callbacks ); 3136} 3137 3138/// Copies a list of Callback structs from src to *dest, clearing any existing 3139/// entries and allocating memory for the destination. 3140static void copy_cpt_callbacks (Callback ** dest ,int * dest_cnt ,Callback * src ,int cnt ) 3141{ 3142clear_cpt_callbacks (dest ,* dest_cnt ); 3143* dest_cnt = 0 ; 3144 3145if (cnt == 0 ) { 3146return ; 3147 } 3148 3149* dest = xcalloc ((size_t )cnt ,sizeof (Callback )); 3150* dest_cnt = cnt ; 3151 3152for (int i = 0 ;i < cnt ;i ++ ) { 3153if (src [i ].type != kCallbackNone ) { 3154callback_copy (& (* dest )[i ],& src [i ]); 3155 } 3156 } 3157} 3158 3159/// Copy global 'complete' F{func} callbacks into the given buffer's local 3160/// callback array. Clears any existing buffer-local callbacks first. 3161void set_buflocal_cpt_callbacks (buf_T * buf ) 3162{ 3163if (buf == NULL ) { 3164return ; 3165 } 3166copy_cpt_callbacks (& buf -> b_p_cpt_cb ,& buf -> b_p_cpt_count ,cpt_cb ,cpt_cb_count ); 3167} 3168 3169/// Parse the 'complete' option value "cpt" and store the callbacks for the 3170/// F{func} entries in a newly allocated array in "*cbp", setting "*cnt" to the 3171/// number of entries. The array has one entry for every item in "cpt", also 3172/// for items that are not a function, so that it can be indexed with the item 3173/// index. Any previous array in "*cbp" is cleared. 3174static void parse_cpt_callbacks (char * cpt ,Callback ** cbp ,int * cnt ) 3175{ 3176clear_cpt_callbacks (cbp ,* cnt ); 3177* cnt = 0 ; 3178 3179int count = get_cpt_sources_count (cpt ); 3180if (count == 0 ) { 3181return ; 3182 } 3183 3184* cbp = xcalloc ((size_t )count ,sizeof (Callback )); 3185* cnt = count ; 3186 3187char buf [LSIZE ]; 3188int idx = 0 ; 3189for (char * p = cpt ;* p != NUL ;) { 3190while (* p == ',' || * p == ' ' ) { 3191p ++ ;// Skip delimiters 3192 } 3193if (* p != NUL ) { 3194size_t slen = copy_option_part (& p ,buf ,LSIZE ,"," );// Advance p 3195if (slen > 0 && buf [0 ]== 'F' && buf [1 ]!= NUL ) { 3196char * caret = vim_strchr (buf ,'^' ); 3197if (caret != NULL ) { 3198* caret = NUL ; 3199 } 3200if (option_set_callback_func (buf + 1 ,& (* cbp )[idx ])!= OK ) { 3201 (* cbp )[idx ].type = kCallbackNone ; 3202 } 3203 } 3204idx ++ ; 3205 } 3206 } 3207} 3208 3209/// Parse 'complete' option and initialize F{func} callbacks. 3210/// Frees any existing callbacks and allocates new ones. 3211int set_cpt_callbacks (optset_T * args ) 3212{ 3213int opt_flags = args -> os_flags ; 3214 3215if (curbuf == NULL ) { 3216return FAIL ; 3217 } 3218 3219// ":setglobal" does not change the buffer-local option value 3220if (!(opt_flags & OPT_GLOBAL )) { 3221parse_cpt_callbacks (curbuf -> b_p_cpt ,& curbuf -> b_p_cpt_cb ,& curbuf -> b_p_cpt_count ); 3222 } 3223 3224// ":setlocal" does not change the global option value 3225if (opt_flags & OPT_LOCAL ) { 3226return OK ; 3227 } 3228 3229// Cache the callbacks for the global value 3230if (opt_flags & OPT_GLOBAL ) { 3231parse_cpt_callbacks (p_cpt ,& cpt_cb ,& cpt_cb_count ); 3232return OK ; 3233 } 3234 3235// set case 3236copy_cpt_callbacks (& cpt_cb ,& cpt_cb_count ,curbuf -> b_p_cpt_cb ,curbuf -> b_p_cpt_count ); 3237return OK ; 3238} 3239 3240/// Mark "copyID" references in an array of F{func} callbacks so that they are 3241/// not garbage collected. 3242bool set_ref_in_cpt_callbacks (Callback * callbacks ,int count ,int copyID ) 3243{ 3244bool abort = false; 3245 3246if (callbacks == NULL ) { 3247return false; 3248 } 3249 3250for (int i = 0 ;i < count ;i ++ ) { 3251abort = abort || set_ref_in_callback (& callbacks [i ],copyID ,NULL ,NULL ); 3252 } 3253return abort ; 3254} 3255 3256/// Mark the global 'completefunc' 'omnifunc' and 'thesaurusfunc' callbacks with 3257/// "copyID" so that they are not garbage collected. 3258bool set_ref_in_insexpand_funcs (int copyID ) 3259{ 3260bool abort = set_ref_in_callback (& p_cfu ,copyID ,NULL ,NULL ); 3261abort = abort || set_ref_in_callback (& p_ofu ,copyID ,NULL ,NULL ); 3262abort = abort || set_ref_in_callback (& p_tsrfu ,copyID ,NULL ,NULL ); 3263abort = abort || set_ref_in_cpt_callbacks (cpt_cb ,cpt_cb_count ,copyID ); 3264 3265return abort ; 3266} 3267 3268/// Get the callback to use for insert mode completion of "type": 'completefunc', 'omnifunc', or 3269/// 'thesaurusfunc'. Returns `kCallbackNone` if the option is empty. 3270static Callback * get_insert_callback (int type ) 3271{ 3272if (type == CTRL_X_FUNCTION ) { 3273return & curbuf -> b_p_cfu ; 3274 } 3275if (type == CTRL_X_OMNI ) { 3276return & curbuf -> b_p_ofu ; 3277 } 3278// CTRL_X_THESAURUS 3279return curbuf -> b_p_tsrfu .type != kCallbackNone ?& curbuf -> b_p_tsrfu :& p_tsrfu ; 3280} 3281 3282/// Execute user defined complete function 'completefunc', 'omnifunc' or 3283/// 'thesaurusfunc', and get matches in "matches". 3284/// 3285/// @param type one of CTRL_X_OMNI or CTRL_X_FUNCTION or CTRL_X_THESAURUS 3286/// @param cb set if triggered by a function in 'cpt' option, otherwise NULL 3287static void expand_by_function (int type ,char * base ,Callback * cb ) 3288{ 3289list_T * matchlist = NULL ; 3290dict_T * matchdict = NULL ; 3291typval_T rettv ; 3292const int save_State = State ; 3293 3294assert (curbuf != NULL ); 3295 3296const bool is_cpt_function = (cb != NULL ); 3297const bool use_sandbox = is_cpt_function && was_set_insecurely (curwin ,kOptComplete ,OPT_LOCAL ); 3298if (!is_cpt_function ) { 3299cb = get_insert_callback (type ); 3300if (cb -> type == kCallbackNone ) { 3301return ; 3302 } 3303 } 3304 3305// Call 'completefunc' to obtain the list of matches. 3306typval_T args [3 ]; 3307args [0 ].v_type = VAR_NUMBER ; 3308args [1 ].v_type = VAR_STRING ; 3309args [2 ].v_type = VAR_UNKNOWN ; 3310args [0 ].vval .v_number = 0 ; 3311args [1 ].vval .v_string = base != NULL ?base :"" ; 3312 3313pos_T pos = curwin -> w_cursor ; 3314// Lock the text to avoid weird things from happening. Also disallow 3315// switching to another window, it should not be needed and may end up in 3316// Insert mode in another buffer. 3317textlock ++ ; 3318if (use_sandbox ) { 3319sandbox ++ ; 3320 } 3321 3322// Call a function, which returns a list or dict. 3323const bool called = callback_call (cb ,2 ,args ,& rettv ); 3324if (use_sandbox ) { 3325sandbox -- ; 3326 } 3327if (called ) { 3328switch (rettv .v_type ) { 3329case VAR_LIST : 3330matchlist = rettv .vval .v_list ; 3331break ; 3332case VAR_DICT : 3333matchdict = rettv .vval .v_dict ; 3334break ; 3335case VAR_SPECIAL : 3336FALLTHROUGH ; 3337default : 3338// TODO(brammool): Give error message? 3339tv_clear (& rettv ); 3340break ; 3341 } 3342 } 3343textlock -- ; 3344 3345curwin -> w_cursor = pos ;// restore the cursor position 3346check_cursor (curwin );// make sure cursor position is valid, just in case 3347validate_cursor (curwin ); 3348if (!equalpos (curwin -> w_cursor ,pos )) { 3349emsg (_ (e_compldel )); 3350 gototheend ; 3351 } 3352 3353if (matchlist != NULL ) { 3354ins_compl_add_list (matchlist ); 3355 }else if (matchdict != NULL ) { 3356ins_compl_add_dict (matchdict ); 3357 } 3358 3359theend : 3360// Restore State, it might have been changed. 3361State = save_State ; 3362 3363if (matchdict != NULL ) { 3364tv_dict_unref (matchdict ); 3365 } 3366if (matchlist != NULL ) { 3367tv_list_unref (matchlist ); 3368 } 3369} 3370 3371static inline int get_user_highlight_id (char * hlname ) 3372{ 3373if (hlname != NULL && * hlname != NUL ) { 3374return syn_check_group (hlname ,strlen (hlname )); 3375 } 3376return 0 ; 3377} 3378 3379/// Add a match to the list of matches from Vimscript object 3380/// 3381/// @param[in] tv Object to get matches from. 3382/// @param[in] dir Completion direction. 3383/// @param[in] fast use fast_breakcheck() instead of os_breakcheck(). 3384/// 3385/// @return NOTDONE if the given string is already in the list of completions, 3386/// otherwise it is added to the list and OK is returned. FAIL will be 3387/// returned in case of error. 3388static int ins_compl_add_tv (typval_T * const tv ,const Direction dir ,bool fast ) 3389FUNC_ATTR_NONNULL_ALL 3390{ 3391const char * word ; 3392bool dup = false; 3393bool empty = false; 3394int flags = fast ?CP_FAST :0 ; 3395bool preselect = false; 3396char * (cptext [CPT_COUNT ]); 3397char * user_abbr_hlname = NULL ; 3398char * user_kind_hlname = NULL ; 3399char * commit_chars = NULL ; 3400int user_hl [2 ]= {0 ,0 }; 3401typval_T user_data ; 3402 3403user_data .v_type = VAR_UNKNOWN ; 3404if (tv -> v_type == VAR_DICT && tv -> vval .v_dict != NULL ) { 3405word = tv_dict_get_string (tv -> vval .v_dict ,"word" , false); 3406cptext [CPT_ABBR ]= tv_dict_get_string (tv -> vval .v_dict ,"abbr" , true); 3407cptext [CPT_MENU ]= tv_dict_get_string (tv -> vval .v_dict ,"menu" , true); 3408cptext [CPT_KIND ]= tv_dict_get_string (tv -> vval .v_dict ,"kind" , true); 3409cptext [CPT_INFO ]= tv_dict_get_string (tv -> vval .v_dict ,"info" , true); 3410commit_chars = tv_dict_get_string (tv -> vval .v_dict ,"commit_chars" , true); 3411 3412user_abbr_hlname = tv_dict_get_string (tv -> vval .v_dict ,"abbr_hlgroup" , false); 3413user_hl [0 ]= get_user_highlight_id (user_abbr_hlname ); 3414 3415user_kind_hlname = tv_dict_get_string (tv -> vval .v_dict ,"kind_hlgroup" , false); 3416user_hl [1 ]= get_user_highlight_id (user_kind_hlname ); 3417 3418tv_dict_get_tv (tv -> vval .v_dict ,"user_data" ,& user_data ); 3419 3420if (tv_dict_get_number (tv -> vval .v_dict ,"icase" )) { 3421flags |=CP_ICASE ; 3422 } 3423dup = (bool )tv_dict_get_number (tv -> vval .v_dict ,"dup" ); 3424empty = (bool )tv_dict_get_number (tv -> vval .v_dict ,"empty" ); 3425preselect = (bool )tv_dict_get_number (tv -> vval .v_dict ,"preselect" ); 3426if (tv_dict_get_string (tv -> vval .v_dict ,"equal" , false)!= NULL 3427&& tv_dict_get_number (tv -> vval .v_dict ,"equal" )) { 3428flags |=CP_EQUAL ; 3429 } 3430 }else { 3431word = tv_get_string_chk (tv ); 3432CLEAR_FIELD (cptext ); 3433 } 3434if (word == NULL || (!empty && * word == NUL )) { 3435free_cptext (cptext ); 3436tv_clear (& user_data ); 3437xfree (commit_chars ); 3438return FAIL ; 3439 } 3440int status = ins_compl_add ((char * )word ,-1 ,NULL ,cptext , true, 3441& user_data ,dir ,flags ,dup ,user_hl ,FUZZY_SCORE_NONE ,preselect , 3442commit_chars ); 3443if (status != OK ) { 3444tv_clear (& user_data ); 3445 } 3446return status ; 3447} 3448 3449/// Add completions from a list. 3450static void ins_compl_add_list (list_T * const list ) 3451{ 3452Direction dir = compl_direction ; 3453 3454// Go through the List with matches and add each of them. 3455TV_LIST_ITER (list ,li , { 3456if (ins_compl_add_tv (TV_LIST_ITEM_TV (li ),dir , true)== OK ) { 3457// If dir was BACKWARD then honor it just once. 3458dir = FORWARD ; 3459 }else if (did_emsg ) { 3460break ; 3461 } 3462 }); 3463} 3464 3465/// Add completions from a dict. 3466static void ins_compl_add_dict (dict_T * dict ) 3467{ 3468// Check for optional "refresh" item. 3469compl_opt_refresh_always = false; 3470dictitem_T * di_refresh = tv_dict_find (dict ,S_LEN ("refresh" )); 3471if (di_refresh != NULL && di_refresh -> di_tv .v_type == VAR_STRING ) { 3472const char * v = di_refresh -> di_tv .vval .v_string ; 3473 3474if (v != NULL && strcmp (v ,"always" )== 0 ) { 3475compl_opt_refresh_always = true; 3476 } 3477 } 3478 3479// Add completions from a "words" list. 3480dictitem_T * di_words = tv_dict_find (dict ,S_LEN ("words" )); 3481if (di_words != NULL && di_words -> di_tv .v_type == VAR_LIST ) { 3482ins_compl_add_list (di_words -> di_tv .vval .v_list ); 3483 } 3484} 3485 3486/// Save extmarks in "compl_orig_text" so that they may be restored when the 3487/// completion is cancelled, or the original text is completed. 3488static void save_orig_extmarks (void ) 3489{ 3490extmark_splice_delete (curbuf ,curwin -> w_cursor .lnum - 1 ,compl_col ,curwin -> w_cursor .lnum - 1 , 3491compl_col + compl_length ,& compl_orig_extmarks , true,kExtmarkUndo ); 3492} 3493 3494static void restore_orig_extmarks (void ) 3495{ 3496for (long i = (int )kv_size (compl_orig_extmarks )- 1 ;i > -1 ;i -- ) { 3497ExtmarkUndoObject undo_info = kv_A (compl_orig_extmarks ,i ); 3498extmark_apply_undo (undo_info , true); 3499 } 3500} 3501 3502/// Start completion for the complete() function. 3503/// 3504/// @param startcol where the matched text starts (1 is first column). 3505/// @param list the list of matches. 3506static void set_completion (colnr_T startcol ,list_T * list ) 3507{ 3508int flags = CP_ORIGINAL_TEXT ; 3509unsigned cur_cot_flags = get_cot_flags (); 3510bool compl_longest = (cur_cot_flags & kOptCotFlagLongest )!= 0 ; 3511bool compl_no_insert = (cur_cot_flags & kOptCotFlagNoinsert )!= 0 ; 3512bool compl_no_select = (cur_cot_flags & kOptCotFlagNoselect )!= 0 ; 3513 3514// If already doing completions stop it. 3515if (compl_started || ctrl_x_mode_not_default ()) { 3516ins_compl_prep (' ' ); 3517 } 3518ins_compl_clear (); 3519ins_compl_free (); 3520compl_get_longest = compl_longest ; 3521 3522compl_direction = FORWARD ; 3523if (startcol > curwin -> w_cursor .col ) { 3524startcol = curwin -> w_cursor .col ; 3525 } 3526compl_col = startcol ; 3527compl_lnum = curwin -> w_cursor .lnum ; 3528compl_length = curwin -> w_cursor .col - startcol ; 3529// compl_pattern doesn't need to be set 3530compl_orig_text = cbuf_to_string (get_cursor_line_ptr ()+ compl_col , 3531 (size_t )compl_length ); 3532save_orig_extmarks (); 3533if (p_ic ) { 3534flags |=CP_ICASE ; 3535 } 3536if (ins_compl_add (compl_orig_text .data , (int )compl_orig_text .size , 3537NULL ,NULL , false,NULL ,0 , 3538flags |CP_FAST , false,NULL ,FUZZY_SCORE_NONE , false,NULL )!= OK ) { 3539return ; 3540 } 3541 3542ctrl_x_mode = CTRL_X_EVAL ; 3543 3544ins_compl_add_list (list ); 3545compl_matches = ins_compl_make_cyclic (); 3546compl_started = true; 3547compl_used_match = true; 3548compl_cont_status = 0 ; 3549int save_w_wrow = curwin -> w_wrow ; 3550int save_w_leftcol = curwin -> w_leftcol ; 3551 3552compl_curr_match = compl_first_match ; 3553bool no_select = compl_no_select || compl_longest ; 3554if (compl_preselect_match && !no_select ) { 3555compl_curr_match = compl_preselect_match -> cp_prev ; 3556ins_complete (compl_no_insert ?K_DOWN :Ctrl_N , false); 3557 }else if (compl_no_insert || no_select ) { 3558ins_complete (K_DOWN , false); 3559if (no_select ) { 3560ins_complete (K_UP , false); 3561 } 3562 }else { 3563ins_complete (Ctrl_N , false); 3564 } 3565compl_enter_selects = compl_no_insert ; 3566 3567// Lazily show the popup menu, unless we got interrupted. 3568if (!compl_interrupted ) { 3569show_pum (save_w_wrow ,save_w_leftcol ); 3570 } 3571 3572may_trigger_modechanged (); 3573ui_flush (); 3574} 3575 3576/// "complete()" function 3577void f_complete (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3578{ 3579if ((State & MODE_INSERT )== 0 ) { 3580emsg (_ ("E785: complete() can only be used in Insert mode" )); 3581return ; 3582 } 3583 3584// Check for undo allowed here, because if something was already inserted 3585// the line was already saved for undo and this check isn't done. 3586if (!undo_allowed (curbuf )) { 3587return ; 3588 } 3589 3590if (argvars [1 ].v_type != VAR_LIST ) { 3591emsg (_ (e_invarg )); 3592 }else { 3593const colnr_T startcol = (colnr_T )tv_get_number_chk (& argvars [0 ],NULL ); 3594if (startcol > 0 ) { 3595set_completion (startcol - 1 ,argvars [1 ].vval .v_list ); 3596 } 3597 } 3598} 3599 3600/// "complete_add()" function 3601void f_complete_add (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3602{ 3603rettv -> vval .v_number = ins_compl_add_tv (& argvars [0 ],0 , false); 3604} 3605 3606/// "complete_check()" function 3607void f_complete_check (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3608{ 3609int saved = RedrawingDisabled ; 3610 3611RedrawingDisabled = 0 ; 3612ins_compl_check_keys (0 , true); 3613rettv -> vval .v_number = ins_compl_interrupted (); 3614RedrawingDisabled = saved ; 3615} 3616 3617/// Return Insert completion mode name string 3618static String ins_compl_mode (void ) 3619{ 3620if (ctrl_x_mode_not_defined_yet ()|| ctrl_x_mode_scroll ()|| compl_started ) { 3621String * mode = & ctrl_x_mode_names [ctrl_x_mode & ~CTRL_X_WANT_IDENT ]; 3622return cbuf_as_string (mode -> data == NULL ?"" :mode -> data ,mode -> size ); 3623 } 3624return cbuf_as_string ("" ,0 ); 3625} 3626 3627/// Assign the sequence number to all the completion matches which don't have 3628/// one assigned yet. 3629static void ins_compl_update_sequence_numbers (void ) 3630{ 3631int number = 0 ; 3632compl_T * match ; 3633 3634if (compl_dir_forward ()) { 3635// Search backwards for the first valid (!= -1) number. 3636// This should normally succeed already at the first loop 3637// cycle, so it's fast! 3638for (match = compl_curr_match -> cp_prev ; 3639match != NULL && !is_first_match (match );match = match -> cp_prev ) { 3640if (match -> cp_number != -1 ) { 3641number = match -> cp_number ; 3642break ; 3643 } 3644 } 3645if (match != NULL ) { 3646// go up and assign all numbers which are not assigned yet 3647for (match = match -> cp_next ; 3648match != NULL && match -> cp_number == -1 ; 3649match = match -> cp_next ) { 3650match -> cp_number = ++ number ; 3651 } 3652 } 3653 }else {// BACKWARD 3654assert (compl_direction == BACKWARD ); 3655// Search forwards (upwards) for the first valid (!= -1) 3656// number. This should normally succeed already at the 3657// first loop cycle, so it's fast! 3658for (match = compl_curr_match -> cp_next ; 3659match != NULL && !is_first_match (match );match = match -> cp_next ) { 3660if (match -> cp_number != -1 ) { 3661number = match -> cp_number ; 3662break ; 3663 } 3664 } 3665if (match != NULL ) { 3666// go down and assign all numbers which are not assigned yet 3667for (match = match -> cp_prev ; 3668match && match -> cp_number == -1 ; 3669match = match -> cp_prev ) { 3670match -> cp_number = ++ number ; 3671 } 3672 } 3673 } 3674} 3675 3676/// Fill the dict of complete_info 3677static void fill_complete_info_dict (dict_T * di ,compl_T * match ,bool add_match ) 3678{ 3679tv_dict_add_str_len (di ,S_LEN ("word" ),match -> cp_str .data , (int )match -> cp_str .size ); 3680tv_dict_add_str (di ,S_LEN ("abbr" ),match -> cp_text [CPT_ABBR ]); 3681tv_dict_add_str (di ,S_LEN ("menu" ),match -> cp_text [CPT_MENU ]); 3682tv_dict_add_str (di ,S_LEN ("kind" ),match -> cp_text [CPT_KIND ]); 3683tv_dict_add_str (di ,S_LEN ("info" ),match -> cp_text [CPT_INFO ]); 3684tv_dict_add_str (di ,S_LEN ("abbr_hlgroup" ),syn_id2name (match -> cp_user_abbr_hl_id )); 3685tv_dict_add_str (di ,S_LEN ("kind_hlgroup" ),syn_id2name (match -> cp_user_kind_hl_id )); 3686if (add_match ) { 3687tv_dict_add_bool (di ,S_LEN ("match" ),match -> cp_in_match_array ); 3688 } 3689if (match -> cp_flags & CP_EQUAL ) { 3690tv_dict_add_nr (di ,S_LEN ("equal" ),1 ); 3691 } 3692if (match -> cp_preselect ) { 3693tv_dict_add_nr (di ,S_LEN ("preselect" ),1 ); 3694 } 3695if (match -> cp_commit_chars != NULL ) { 3696tv_dict_add_str (di ,S_LEN ("commit_chars" ),match -> cp_commit_chars ); 3697 } 3698if (match -> cp_user_data .v_type == VAR_UNKNOWN ) { 3699// Add an empty string for backwards compatibility 3700tv_dict_add_str_len (di ,S_LEN ("user_data" ),"" ,0 ); 3701 }else { 3702tv_dict_add_tv (di ,S_LEN ("user_data" ),& match -> cp_user_data ); 3703 } 3704} 3705 3706/// Get complete information 3707static void get_complete_info (list_T * what_list ,dict_T * retdict ) 3708{ 3709#define CI_WHAT_MODE 0x01 3710#define CI_WHAT_PUM_VISIBLE 0x02 3711#define CI_WHAT_ITEMS 0x04 3712#define CI_WHAT_SELECTED 0x08 3713#define CI_WHAT_COMPLETED 0x10 3714#define CI_WHAT_MATCHES 0x20 3715#define CI_WHAT_PREINSERTED_TEXT 0x40 3716#define CI_WHAT_AUTO 0x80 3717#define CI_WHAT_ALL 0xff 3718int what_flag ; 3719 3720if (what_list == NULL ) { 3721what_flag = CI_WHAT_ALL & ~(CI_WHAT_MATCHES |CI_WHAT_COMPLETED |CI_WHAT_AUTO ); 3722 }else { 3723what_flag = 0 ; 3724for (listitem_T * item = tv_list_first (what_list ) 3725 ;item != NULL 3726 ;item = TV_LIST_ITEM_NEXT (what_list ,item )) { 3727const char * what = tv_get_string (TV_LIST_ITEM_TV (item )); 3728 3729if (strcmp (what ,"mode" )== 0 ) { 3730what_flag |=CI_WHAT_MODE ; 3731 }else if (strcmp (what ,"pum_visible" )== 0 ) { 3732what_flag |=CI_WHAT_PUM_VISIBLE ; 3733 }else if (strcmp (what ,"items" )== 0 ) { 3734what_flag |=CI_WHAT_ITEMS ; 3735 }else if (strcmp (what ,"selected" )== 0 ) { 3736what_flag |=CI_WHAT_SELECTED ; 3737 }else if (strcmp (what ,"completed" )== 0 ) { 3738what_flag |=CI_WHAT_COMPLETED ; 3739 }else if (strcmp (what ,"preinserted_text" )== 0 ) { 3740what_flag |=CI_WHAT_PREINSERTED_TEXT ; 3741 }else if (strcmp (what ,"matches" )== 0 ) { 3742what_flag |=CI_WHAT_MATCHES ; 3743 }else if (strcmp (what ,"auto" )== 0 ) { 3744what_flag |=CI_WHAT_AUTO ; 3745 } 3746 } 3747 } 3748 3749int ret = OK ; 3750if (what_flag & CI_WHAT_MODE ) { 3751String mode = ins_compl_mode (); 3752ret = tv_dict_add_str_len (retdict ,S_LEN ("mode" ),mode .data , (int )mode .size ); 3753 } 3754 3755if (ret == OK && (what_flag & CI_WHAT_PUM_VISIBLE )) { 3756ret = tv_dict_add_nr (retdict ,S_LEN ("pum_visible" ),pum_visible ()); 3757 } 3758 3759if (ret == OK && (what_flag & CI_WHAT_AUTO )) { 3760ret = tv_dict_add_nr (retdict ,S_LEN ("auto" ),compl_autostarted ); 3761 } 3762 3763if (ret == OK && (what_flag & CI_WHAT_PREINSERTED_TEXT )) { 3764char * line = get_cursor_line_ptr (); 3765int len = compl_ins_end_col - curwin -> w_cursor .col ; 3766ret = tv_dict_add_str_len (retdict ,S_LEN ("preinserted_text" ), 3767len > 0 ?line + curwin -> w_cursor .col :"" ,MAX (len ,0 )); 3768 } 3769 3770if (ret == OK && (what_flag & (CI_WHAT_ITEMS |CI_WHAT_SELECTED 3771 |CI_WHAT_MATCHES |CI_WHAT_COMPLETED ))) { 3772list_T * li = NULL ; 3773int selected_idx = -1 ; 3774bool has_items = what_flag & CI_WHAT_ITEMS ; 3775bool has_matches = what_flag & CI_WHAT_MATCHES ; 3776bool has_completed = what_flag & CI_WHAT_COMPLETED ; 3777if (has_items || has_matches ) { 3778li = tv_list_alloc (kListLenMayKnow ); 3779const char * key = (has_matches && !has_items ) ?"matches" :"items" ; 3780ret = tv_dict_add_list (retdict ,key ,strlen (key ),li ); 3781 } 3782if (ret == OK && what_flag & CI_WHAT_SELECTED ) { 3783if (compl_curr_match != NULL && compl_curr_match -> cp_number == -1 ) { 3784ins_compl_update_sequence_numbers (); 3785 } 3786 } 3787if (ret == OK && compl_first_match != NULL ) { 3788int list_idx = 0 ; 3789compl_T * match = compl_first_match ; 3790do { 3791if (!match_at_original_text (match )) { 3792if (has_items || (has_matches && match -> cp_in_match_array )) { 3793dict_T * di = tv_dict_alloc (); 3794tv_list_append_dict (li ,di ); 3795fill_complete_info_dict (di ,match ,has_matches && has_items ); 3796 } 3797if (compl_curr_match != NULL 3798&& compl_curr_match -> cp_number == match -> cp_number ) { 3799selected_idx = list_idx ; 3800 } 3801if (!has_matches || match -> cp_in_match_array ) { 3802list_idx ++ ; 3803 } 3804 } 3805match = match -> cp_next ; 3806 }while (match != NULL && !is_first_match (match )); 3807 } 3808if (ret == OK && (what_flag & CI_WHAT_SELECTED )) { 3809ret = tv_dict_add_nr (retdict ,S_LEN ("selected" ),selected_idx ); 3810win_T * wp = win_float_find (kWinInfo ); 3811if (wp != NULL ) { 3812tv_dict_add_nr (retdict ,S_LEN ("preview_winid" ),wp -> handle ); 3813tv_dict_add_nr (retdict ,S_LEN ("preview_bufnr" ),wp -> w_buffer -> handle ); 3814 } 3815 } 3816if (ret == OK && selected_idx != -1 && has_completed ) { 3817dict_T * di = tv_dict_alloc (); 3818fill_complete_info_dict (di ,compl_curr_match , false); 3819ret = tv_dict_add_dict (retdict ,S_LEN ("completed" ),di ); 3820 } 3821 } 3822 3823 (void )ret ; 3824} 3825 3826/// "complete_info()" function 3827void f_complete_info (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 3828{ 3829tv_dict_alloc_ret (rettv ); 3830 3831list_T * what_list = NULL ; 3832 3833if (argvars [0 ].v_type != VAR_UNKNOWN ) { 3834if (argvars [0 ].v_type != VAR_LIST ) { 3835emsg (_ (e_listreq )); 3836return ; 3837 } 3838what_list = argvars [0 ].vval .v_list ; 3839 } 3840get_complete_info (what_list ,rettv -> vval .v_dict ); 3841} 3842 3843/// Returns true when using a user-defined function for thesaurus completion. 3844static bool thesaurus_func_complete (int type ) 3845{ 3846return type == CTRL_X_THESAURUS 3847&& (curbuf -> b_p_tsrfu .type != kCallbackNone || p_tsrfu .type != kCallbackNone ); 3848} 3849 3850/// Check if 'cpt' list index can be advanced to the next completion source. 3851static bool may_advance_cpt_index (const char * cpt ) 3852{ 3853const char * p = cpt ; 3854 3855if (cpt_sources_index == -1 ) { 3856return false; 3857 } 3858while (* p == ',' || * p == ' ' ) {// Skip delimiters 3859p ++ ; 3860 } 3861return (* p != NUL ); 3862} 3863 3864/// Return value of process_next_cpt_value() 3865enum { 3866INS_COMPL_CPT_OK = 1 , 3867INS_COMPL_CPT_CONT , 3868INS_COMPL_CPT_END , 3869}; 3870 3871/// Process the next 'complete' option value in st->e_cpt. 3872/// 3873/// If successful, the arguments are set as below: 3874/// st->cpt - pointer to the next option value in "st->cpt" 3875/// compl_type_arg - type of insert mode completion to use 3876/// st->found_all - all matches of this type are found 3877/// st->ins_buf - search for completions in this buffer 3878/// st->first_match_pos - position of the first completion match 3879/// st->last_match_pos - position of the last completion match 3880/// st->set_match_pos - true if the first match position should be saved to 3881/// avoid loops after the search wraps around. 3882/// st->dict - name of the dictionary or thesaurus file to search 3883/// st->dict_f - flag specifying whether "dict" is an exact file name or not 3884/// 3885/// @return INS_COMPL_CPT_OK if the next value is processed successfully. 3886/// INS_COMPL_CPT_CONT to skip the current completion source matching 3887/// the "st->e_cpt" option value and process the next matching source. 3888/// INS_COMPL_CPT_END if all the values in "st->e_cpt" are processed. 3889static int process_next_cpt_value (ins_compl_next_state_T * st ,int * compl_type_arg , 3890pos_T * start_match_pos ,bool fuzzy_collect ,bool * advance_cpt_idx ) 3891{ 3892int compl_type = -1 ; 3893int status = INS_COMPL_CPT_OK ; 3894bool skip_source = compl_autocomplete && compl_from_nonkeyword ; 3895 3896st -> found_all = false; 3897* advance_cpt_idx = false; 3898 3899while (* st -> e_cpt == ',' || * st -> e_cpt == ' ' ) { 3900st -> e_cpt ++ ; 3901 } 3902 3903if (* st -> e_cpt == '.' && !curbuf -> b_scanned && !skip_source 3904&& !compl_time_slice_expired ) { 3905st -> ins_buf = curbuf ; 3906st -> first_match_pos = * start_match_pos ; 3907// Move the cursor back one character so that ^N can match the 3908// word immediately after the cursor. 3909if (ctrl_x_mode_normal ()&& (!fuzzy_collect && dec (& st -> first_match_pos )< 0 )) { 3910// Move the cursor to after the last character in the 3911// buffer, so that word at start of buffer is found 3912// correctly. 3913st -> first_match_pos .lnum = st -> ins_buf -> b_ml .ml_line_count ; 3914st -> first_match_pos .col = ml_get_len (st -> first_match_pos .lnum ); 3915 } 3916st -> last_match_pos = st -> first_match_pos ; 3917compl_type = 0 ; 3918 3919// Remember the first match so that the loop stops when we 3920// wrap and come back there a second time. 3921st -> set_match_pos = true; 3922 }else if (!skip_source && !compl_time_slice_expired 3923&& vim_strchr ("buwU" , (uint8_t )(* st -> e_cpt ))!= NULL 3924&& (st -> ins_buf = ins_compl_next_buf (st -> ins_buf ,* st -> e_cpt ))!= curbuf ) { 3925// Scan a buffer, but not the current one. 3926if (st -> ins_buf -> b_ml .ml_mfp != NULL ) {// loaded buffer 3927compl_started = true; 3928st -> first_match_pos .col = st -> last_match_pos .col = 0 ; 3929st -> first_match_pos .lnum = st -> ins_buf -> b_ml .ml_line_count + 1 ; 3930st -> last_match_pos .lnum = 0 ; 3931compl_type = 0 ; 3932 }else {// unloaded buffer, scan like dictionary 3933st -> found_all = true; 3934if (st -> ins_buf -> b_fname == NULL ) { 3935status = INS_COMPL_CPT_CONT ; 3936 gotodone ; 3937 } 3938compl_type = CTRL_X_DICTIONARY ; 3939st -> dict = st -> ins_buf -> b_fname ; 3940st -> dict_f = DICT_EXACT ; 3941 } 3942if (!shortmess (kShmCompletionscan )&& !compl_autocomplete ) { 3943vim_snprintf (IObuff ,IOSIZE ,_ ("Scanning: %s" ), 3944st -> ins_buf -> b_fname == NULL 3945 ?buf_spname (st -> ins_buf ) 3946 :st -> ins_buf -> b_sfname == NULL 3947 ?st -> ins_buf -> b_fname 3948 :st -> ins_buf -> b_sfname ); 3949msg_progress (IObuff ,"nvim.completion" ,"running" ,HLF_R , false, true, false); 3950 } 3951 }else if (* st -> e_cpt == NUL ) { 3952status = INS_COMPL_CPT_END ; 3953 }else { 3954if (ctrl_x_mode_line_or_eval ()) { 3955// compl_type = -1; 3956 }else if (* st -> e_cpt == 'F' || * st -> e_cpt == 'o' ) { 3957compl_type = CTRL_X_FUNCTION ; 3958st -> func_cb = get_callback_if_cpt_func (st -> e_cpt ,cpt_sources_index ); 3959if (!st -> func_cb ) { 3960compl_type = -1 ; 3961 } 3962 }else if (!skip_source ) { 3963if (* st -> e_cpt == 'k' || * st -> e_cpt == 's' ) { 3964if (* st -> e_cpt == 'k' ) { 3965compl_type = CTRL_X_DICTIONARY ; 3966 }else { 3967compl_type = CTRL_X_THESAURUS ; 3968 } 3969if (*++ st -> e_cpt != ',' && * st -> e_cpt != NUL ) { 3970st -> dict = st -> e_cpt ; 3971st -> dict_f = DICT_FIRST ; 3972 } 3973 }else if (* st -> e_cpt == 'i' ) { 3974compl_type = CTRL_X_PATH_PATTERNS ; 3975 }else if (* st -> e_cpt == 'd' ) { 3976compl_type = CTRL_X_PATH_DEFINES ; 3977 }else if (* st -> e_cpt == 'f' ) { 3978compl_type = CTRL_X_BUFNAMES ; 3979 }else if (* st -> e_cpt == ']' || * st -> e_cpt == 't' ) { 3980compl_type = CTRL_X_TAGS ; 3981if (!shortmess (kShmCompletionscan )&& !compl_autocomplete ) { 3982vim_snprintf (IObuff ,IOSIZE ,"%s" ,_ ("Scanning tags." )); 3983msg_progress (IObuff ,"nvim.completion" ,"running" ,HLF_R , false, true, false); 3984 } 3985 } 3986 } 3987 3988// in any case e_cpt is advanced to the next entry 3989copy_option_part (& st -> e_cpt ,IObuff ,IOSIZE ,"," ); 3990* advance_cpt_idx = may_advance_cpt_index (st -> e_cpt ); 3991 3992st -> found_all = true; 3993if (compl_type == -1 ) { 3994status = INS_COMPL_CPT_CONT ; 3995 } 3996 } 3997 3998done : 3999* compl_type_arg = compl_type ; 4000return status ; 4001} 4002 4003/// Get the next set of identifiers or defines matching "compl_pattern" in 4004/// included files. 4005static void get_next_include_file_completion (int compl_type ) 4006{ 4007find_pattern_in_path (compl_pattern .data ,compl_direction , 4008compl_pattern .size , false, false, 4009 ((compl_type == CTRL_X_PATH_DEFINES 4010&& !(compl_cont_status & CONT_SOL )) 4011 ?FIND_DEFINE :FIND_ANY ), 40121 ,ACTION_EXPAND ,1 ,MAXLNUM , false,compl_autocomplete ); 4013} 4014 4015/// Get the next set of words matching "compl_pattern" in dictionary or 4016/// thesaurus files. 4017static void get_next_dict_tsr_completion (int compl_type ,char * dict ,int dict_f ) 4018{ 4019if (thesaurus_func_complete (compl_type )) { 4020expand_by_function (compl_type ,compl_pattern .data ,NULL ); 4021 }else { 4022ins_compl_dictionaries (dict != NULL 4023 ?dict 4024 : (compl_type == CTRL_X_THESAURUS 4025 ? (* curbuf -> b_p_tsr == NUL ?p_tsr :curbuf -> b_p_tsr ) 4026 : (* curbuf -> b_p_dict == NUL ?p_dict :curbuf -> b_p_dict )), 4027compl_pattern .data , 4028dict != NULL ?dict_f :0 , 4029compl_type == CTRL_X_THESAURUS ); 4030 } 4031} 4032 4033/// Get the next set of tag names matching "compl_pattern". 4034static void get_next_tag_completion (void ) 4035{ 4036// set p_ic according to p_ic, p_scs and pat for find_tags(). 4037const int save_p_ic = p_ic ; 4038p_ic = ignorecase (compl_pattern .data ); 4039 4040// Find up to TAG_MANY matches. Avoids that an enormous number 4041// of matches is found when compl_pattern is empty 4042g_tag_at_cursor = true; 4043char ** matches ; 4044int num_matches ; 4045if (find_tags (compl_pattern .data ,& num_matches ,& matches , 4046TAG_REGEXP |TAG_NAMES |TAG_NOIC |TAG_INS_COMP 4047 | (ctrl_x_mode_not_default () ?TAG_VERBOSE :0 ), 4048TAG_MANY ,curbuf -> b_ffname )== OK && num_matches > 0 ) { 4049ins_compl_add_matches (num_matches ,matches ,p_ic ); 4050 } 4051g_tag_at_cursor = false; 4052p_ic = save_p_ic ; 4053} 4054 4055/// Compare function for qsort 4056static int compare_scores (const void * a ,const void * b ) 4057{ 4058int idx_a = * (const int * )a ; 4059int idx_b = * (const int * )b ; 4060int score_a = compl_fuzzy_scores [idx_a ]; 4061int score_b = compl_fuzzy_scores [idx_b ]; 4062return score_a == score_b ? (idx_a == idx_b ?0 : (idx_a < idx_b ?-1 :1 )) 4063 : (score_a > score_b ?-1 :1 ); 4064} 4065 4066/// insert prefix with redraw 4067static void ins_compl_longest_insert (char * prefix ) 4068{ 4069ins_compl_delete (false); 4070ins_compl_insert_bytes (prefix + get_compl_len (),-1 ); 4071compl_longest_end_col = curwin -> w_cursor .col ; 4072ins_redraw (false); 4073} 4074 4075/// Calculate the longest common prefix among the best fuzzy matches 4076/// stored in compl_best_matches, and insert it as the longest. 4077static void fuzzy_longest_match (void ) 4078{ 4079if (compl_num_bests == 0 ) { 4080return ; 4081 } 4082 4083compl_T * nn_compl = compl_first_match -> cp_next -> cp_next ; 4084bool more_candidates = nn_compl && nn_compl != compl_first_match ; 4085 4086compl_T * compl = ctrl_x_mode_whole_line () ?compl_first_match 4087 :compl_first_match -> cp_next ; 4088if (compl_num_bests == 1 ) { 4089// no more candidates insert the match str 4090if (!more_candidates ) { 4091ins_compl_longest_insert (compl -> cp_str .data ); 4092compl_num_bests = 0 ; 4093 } 4094compl_num_bests = 0 ; 4095return ; 4096 } 4097 4098if ((size_t )compl_num_bests > SIZE_MAX /sizeof (compl_T * )) { 4099return ; 4100 } 4101compl_best_matches = (compl_T ** )xmalloc ((size_t )compl_num_bests * sizeof (compl_T * )); 4102 4103for (int i = 0 ;compl != NULL && i < compl_num_bests ;i ++ ) { 4104compl_best_matches [i ]= compl ; 4105compl = compl -> cp_next ; 4106 } 4107 4108char * prefix = compl_best_matches [0 ]-> cp_str .data ; 4109int prefix_len = (int )compl_best_matches [0 ]-> cp_str .size ; 4110 4111for (int i = 1 ;i < compl_num_bests ;i ++ ) { 4112char * match_str = compl_best_matches [i ]-> cp_str .data ; 4113char * prefix_ptr = prefix ; 4114char * match_ptr = match_str ; 4115int j = 0 ; 4116 4117while (j < prefix_len && * match_ptr != NUL && * prefix_ptr != NUL ) { 4118if (strncmp (prefix_ptr ,match_ptr , (size_t )utfc_ptr2len (prefix_ptr ))!= 0 ) { 4119break ; 4120 } 4121 4122MB_PTR_ADV (prefix_ptr ); 4123MB_PTR_ADV (match_ptr ); 4124j ++ ; 4125 } 4126 4127if (j > 0 ) { 4128prefix_len = j ; 4129 } 4130 } 4131 4132char * leader = ins_compl_leader (); 4133size_t leader_len = ins_compl_leader_len (); 4134 4135// skip non-consecutive prefixes 4136if (leader_len > 0 && strncmp (prefix ,leader ,leader_len )!= 0 ) { 4137 gotoend ; 4138 } 4139 4140prefix = xmemdupz (prefix , (size_t )prefix_len ); 4141ins_compl_longest_insert (prefix ); 4142xfree (prefix ); 4143 4144end : 4145xfree (compl_best_matches ); 4146compl_best_matches = NULL ; 4147compl_num_bests = 0 ; 4148} 4149 4150/// Get the next set of filename matching "compl_pattern". 4151static void get_next_filename_completion (void ) 4152{ 4153char ** matches ; 4154int num_matches ; 4155char * leader = ins_compl_leader (); 4156size_t leader_len = ins_compl_leader_len (); 4157bool in_fuzzy_collect = (cot_fuzzy ()&& leader_len > 0 ); 4158bool need_collect_bests = in_fuzzy_collect && compl_get_longest ; 4159int max_score = 0 ; 4160Direction dir = compl_direction ; 4161 4162if (in_fuzzy_collect ) { 4163TO_SLASH (leader ); 4164char * last_sep = strrchr (leader ,PATHSEP ); 4165if (last_sep == NULL ) { 4166// No path separator or separator is the last character, 4167// fuzzy match the whole leader 4168API_CLEAR_STRING (compl_pattern ); 4169compl_pattern = cbuf_to_string ("*" ,1 ); 4170 }else if (* (last_sep + 1 )== NUL ) { 4171in_fuzzy_collect = false; 4172 }else { 4173// Split leader into path and file parts 4174size_t path_len = (size_t )(last_sep - leader )+ 1 ; 4175char * path_with_wildcard = xmalloc (path_len + 2 ); 4176vim_snprintf (path_with_wildcard ,path_len + 2 ,"%*.*s*" , 4177 (int )path_len , (int )path_len ,leader ); 4178API_CLEAR_STRING (compl_pattern ); 4179compl_pattern .data = path_with_wildcard ; 4180compl_pattern .size = path_len + 1 ; 4181 4182// Move leader to the file part 4183leader = last_sep + 1 ; 4184leader_len -= path_len ; 4185 } 4186 } 4187 4188if (expand_wildcards (1 ,& compl_pattern .data ,& num_matches ,& matches , 4189EW_FILE |EW_DIR |EW_ADDSLASH |EW_SILENT )!= OK ) { 4190return ; 4191 } 4192 4193// May change home directory back to "~". 4194tilde_replace (compl_pattern .data ,num_matches ,matches ); 4195#ifdef BACKSLASH_IN_FILENAME 4196if ((curbuf -> b_p_csl [0 ]== NUL && !p_ssl )|| curbuf -> b_p_csl [0 ]== 'b' ) { 4197for (int i = 0 ;i < num_matches ;i ++ ) { 4198for (char * ptr = matches [i ];* ptr ;ptr ++ ) { 4199if (* ptr == '/' ) { 4200* ptr = '\\' ; 4201 } 4202 } 4203 } 4204 } 4205#endif 4206 4207if (in_fuzzy_collect ) { 4208garray_T fuzzy_indices ; 4209ga_init (& fuzzy_indices ,sizeof (int ),10 ); 4210compl_fuzzy_scores = (int * )xmalloc (sizeof (int )* (size_t )num_matches ); 4211 4212for (int i = 0 ;i < num_matches ;i ++ ) { 4213char * ptr = matches [i ]; 4214int score = fuzzy_match_str (ptr ,leader ); 4215if (score != FUZZY_SCORE_NONE ) { 4216GA_APPEND (int ,& fuzzy_indices ,i ); 4217compl_fuzzy_scores [i ]= score ; 4218 } 4219 } 4220 4221// prevent qsort from deref NULL pointer 4222if (fuzzy_indices .ga_len > 0 ) { 4223int * fuzzy_indices_data = (int * )fuzzy_indices .ga_data ; 4224qsort (fuzzy_indices_data , (size_t )fuzzy_indices .ga_len ,sizeof (int ),compare_scores ); 4225 4226for (int i = 0 ;i < fuzzy_indices .ga_len ;i ++ ) { 4227char * match = matches [fuzzy_indices_data [i ]]; 4228int current_score = compl_fuzzy_scores [fuzzy_indices_data [i ]]; 4229if (ins_compl_add (match ,-1 ,NULL ,NULL , false,NULL ,dir , 4230CP_FAST | ((p_fic || p_wic ) ?CP_ICASE :0 ), 4231 false,NULL ,current_score , false,NULL )== OK ) { 4232dir = FORWARD ; 4233 } 4234 4235if (need_collect_bests ) { 4236if (i == 0 || current_score == max_score ) { 4237compl_num_bests ++ ; 4238max_score = current_score ; 4239 } 4240 } 4241 } 4242 4243FreeWild (num_matches ,matches ); 4244 }else if (leader_len > 0 ) { 4245FreeWild (num_matches ,matches ); 4246num_matches = 0 ; 4247 } 4248 4249xfree (compl_fuzzy_scores ); 4250ga_clear (& fuzzy_indices ); 4251 4252if (compl_num_bests > 0 && compl_get_longest ) { 4253fuzzy_longest_match (); 4254 } 4255return ; 4256 } 4257 4258if (num_matches > 0 ) { 4259ins_compl_add_matches (num_matches ,matches ,p_fic || p_wic ); 4260 } 4261} 4262 4263/// Get the next set of command-line completions matching "compl_pattern". 4264static void get_next_cmdline_completion (void ) 4265{ 4266char ** matches ; 4267int num_matches ; 4268if (expand_cmdline (& compl_xp ,compl_pattern .data , 4269 (int )compl_pattern .size ,& num_matches ,& matches )== EXPAND_OK ) { 4270int add_r = OK ; 4271Direction dir = compl_direction ; 4272 4273for (int i = 0 ;i < num_matches && add_r != FAIL ;i ++ ) { 4274char * (cptext [CPT_COUNT ])= {NULL ,NULL ,NULL ,NULL }; 4275 4276if (compl_xp .xp_files_abbr != NULL ) { 4277cptext [CPT_ABBR ]= compl_xp .xp_files_abbr [i ]; 4278 } 4279if (compl_xp .xp_files_kind != NULL ) { 4280cptext [CPT_KIND ]= compl_xp .xp_files_kind [i ]; 4281 } 4282if (compl_xp .xp_files_menu != NULL ) { 4283cptext [CPT_MENU ]= compl_xp .xp_files_menu [i ]; 4284 } 4285if (compl_xp .xp_files_info != NULL ) { 4286cptext [CPT_INFO ]= compl_xp .xp_files_info [i ]; 4287 } 4288 4289add_r = ins_compl_add (matches [i ],-1 ,NULL ,cptext , false,NULL ,dir , 4290CP_FAST , false,NULL ,FUZZY_SCORE_NONE , false,NULL ); 4291if (add_r == OK ) { 4292// if dir was BACKWARD then honor it just once 4293dir = FORWARD ; 4294 } 4295 } 4296FreeWild (num_matches ,matches ); 4297free_xp_files_extra (& compl_xp ,num_matches ); 4298 } 4299} 4300 4301/// Get the next set of spell suggestions matching "compl_pattern". 4302static void get_next_spell_completion (linenr_T lnum ) 4303{ 4304char ** matches ; 4305int num_matches = expand_spelling (lnum ,compl_pattern .data ,& matches ); 4306if (num_matches > 0 ) { 4307ins_compl_add_matches (num_matches ,matches ,p_ic ); 4308 }else { 4309xfree (matches ); 4310 } 4311} 4312 4313/// Return the next word or line from buffer "ins_buf" at position 4314/// "cur_match_pos" for completion. The length of the match is set in "len". 4315/// @param ins_buf buffer being scanned 4316/// @param cur_match_pos current match position 4317/// @param match_len 4318/// @param cont_s_ipos next ^X<> will set initial_pos 4319static char * ins_compl_get_next_word_or_line (buf_T * ins_buf ,pos_T * cur_match_pos ,int * match_len , 4320bool * cont_s_ipos ) 4321{ 4322* match_len = 0 ; 4323char * ptr = ml_get_buf (ins_buf ,cur_match_pos -> lnum )+ cur_match_pos -> col ; 4324int len = ml_get_buf_len (ins_buf ,cur_match_pos -> lnum )- cur_match_pos -> col ; 4325if (ctrl_x_mode_line_or_eval ()) { 4326if (compl_status_adding ()) { 4327if (cur_match_pos -> lnum >=ins_buf -> b_ml .ml_line_count ) { 4328return NULL ; 4329 } 4330ptr = ml_get_buf (ins_buf ,cur_match_pos -> lnum + 1 ); 4331len = ml_get_buf_len (ins_buf ,cur_match_pos -> lnum + 1 ); 4332if (!p_paste ) { 4333char * tmp_ptr = ptr ; 4334ptr = skipwhite (tmp_ptr ); 4335len -= (int )(ptr - tmp_ptr ); 4336 } 4337 } 4338 }else { 4339char * tmp_ptr = ptr ; 4340 4341if (compl_status_adding ()&& compl_length <=len ) { 4342tmp_ptr += compl_length ; 4343// Skip if already inside a word. 4344if (vim_iswordp (tmp_ptr )) { 4345return NULL ; 4346 } 4347// Find start of next word. 4348tmp_ptr = find_word_start (tmp_ptr ); 4349 } 4350// Find end of this word. 4351tmp_ptr = find_word_end (tmp_ptr ); 4352len = (int )(tmp_ptr - ptr ); 4353 4354if (compl_status_adding ()&& len == compl_length ) { 4355if (cur_match_pos -> lnum < ins_buf -> b_ml .ml_line_count ) { 4356// Try next line, if any. the new word will be "join" as if the 4357// normal command "J" was used. IOSIZE is always greater than 4358// compl_length, so the next strncpy always works -- Acevedo 4359strncpy (IObuff ,ptr , (size_t )len );// NOLINT(runtime/printf) 4360ptr = ml_get_buf (ins_buf ,cur_match_pos -> lnum + 1 ); 4361tmp_ptr = ptr = skipwhite (ptr ); 4362// Find start of next word. 4363tmp_ptr = find_word_start (tmp_ptr ); 4364// Find end of next word. 4365tmp_ptr = find_word_end (tmp_ptr ); 4366if (tmp_ptr > ptr ) { 4367if (* ptr != ')' && IObuff [len - 1 ]!= TAB ) { 4368if (IObuff [len - 1 ]!= ' ' ) { 4369IObuff [len ++ ]= ' ' ; 4370 } 4371// IObuf =~ "\k.* ", thus len >= 2 4372if (p_js 4373&& (IObuff [len - 2 ]== '.' 4374|| IObuff [len - 2 ]== '?' 4375|| IObuff [len - 2 ]== '!' )) { 4376IObuff [len ++ ]= ' ' ; 4377 } 4378 } 4379// copy as much as possible of the new word 4380if (tmp_ptr - ptr >=IOSIZE - len ) { 4381tmp_ptr = ptr + IOSIZE - len - 1 ; 4382 } 4383xstrlcpy (IObuff + len ,ptr , (size_t )(IOSIZE - len )); 4384len += (int )(tmp_ptr - ptr ); 4385* cont_s_ipos = true; 4386 } 4387IObuff [len ]= NUL ; 4388ptr = IObuff ; 4389 } 4390if (len == compl_length ) { 4391return NULL ; 4392 } 4393 } 4394 } 4395 4396* match_len = len ; 4397return ptr ; 4398} 4399 4400/// Get the next set of words matching "compl_pattern" for default completion(s) 4401/// (normal ^P/^N and ^X^L). 4402/// Search for "compl_pattern" in the buffer "st->ins_buf" starting from the 4403/// position "st->start_pos" in the "compl_direction" direction. If 4404/// "st->set_match_pos" is true, then set the "st->first_match_pos" and 4405/// "st->last_match_pos". 4406/// 4407/// @return OK if a new next match is found, otherwise FAIL. 4408static int get_next_default_completion (ins_compl_next_state_T * st ,pos_T * start_pos ) 4409{ 4410char * ptr = NULL ; 4411int len = 0 ; 4412bool in_fuzzy_collect = !compl_status_adding ()&& cot_fuzzy ()&& compl_length > 0 ; 4413char * leader = ins_compl_leader (); 4414int score = FUZZY_SCORE_NONE ; 4415const bool in_curbuf = st -> ins_buf == curbuf ; 4416 4417// If 'infercase' is set, don't use 'smartcase' here 4418const int save_p_scs = p_scs ; 4419assert (st -> ins_buf ); 4420if (st -> ins_buf -> b_p_inf ) { 4421p_scs = false; 4422 } 4423 4424// Buffers other than curbuf are scanned from the beginning or the 4425// end but never from the middle, thus setting nowrapscan in this 4426// buffers is a good idea, on the other hand, we always set 4427// wrapscan for curbuf to avoid missing matches -- Acevedo,Webb 4428const int save_p_ws = p_ws ; 4429if (!in_curbuf ) { 4430p_ws = false; 4431 }else if (* st -> e_cpt == '.' ) { 4432p_ws = true; 4433 } 4434bool looped_around = false; 4435int found_new_match = FAIL ; 4436while (true) { 4437bool cont_s_ipos = false; 4438 4439msg_silent ++ ;// Don't want messages for wrapscan. 4440 4441if (in_fuzzy_collect ) { 4442found_new_match = search_for_fuzzy_match (st -> ins_buf , 4443st -> cur_match_pos ,leader ,compl_direction , 4444start_pos ,& len ,& ptr ,& score ); 4445// ctrl_x_mode_line_or_eval() || word-wise search that 4446// has added a word that was at the beginning of the line. 4447 }else if (ctrl_x_mode_whole_line ()|| ctrl_x_mode_eval () 4448|| (compl_cont_status & CONT_SOL )) { 4449found_new_match = search_for_exact_line (st -> ins_buf ,st -> cur_match_pos , 4450compl_direction ,compl_pattern .data ); 4451 }else { 4452found_new_match = searchit (NULL ,st -> ins_buf ,st -> cur_match_pos , 4453NULL ,compl_direction ,compl_pattern .data , 4454compl_pattern .size , 44551 ,SEARCH_KEEP + SEARCH_NFMSG ,RE_LAST ,p_magic ,NULL ); 4456 } 4457msg_silent -- ; 4458if (!compl_started || st -> set_match_pos ) { 4459// set "compl_started" even on fail 4460compl_started = true; 4461st -> first_match_pos = * st -> cur_match_pos ; 4462st -> last_match_pos = * st -> cur_match_pos ; 4463st -> set_match_pos = false; 4464 }else if (st -> first_match_pos .lnum == st -> last_match_pos .lnum 4465&& st -> first_match_pos .col == st -> last_match_pos .col ) { 4466found_new_match = FAIL ; 4467 }else if (compl_dir_forward () 4468&& (st -> prev_match_pos .lnum > st -> cur_match_pos -> lnum 4469|| (st -> prev_match_pos .lnum == st -> cur_match_pos -> lnum 4470&& st -> prev_match_pos .col >=st -> cur_match_pos -> col ))) { 4471if (looped_around ) { 4472found_new_match = FAIL ; 4473 }else { 4474looped_around = true; 4475 } 4476 }else if (!compl_dir_forward () 4477&& (st -> prev_match_pos .lnum < st -> cur_match_pos -> lnum 4478|| (st -> prev_match_pos .lnum == st -> cur_match_pos -> lnum 4479&& st -> prev_match_pos .col <=st -> cur_match_pos -> col ))) { 4480if (looped_around ) { 4481found_new_match = FAIL ; 4482 }else { 4483looped_around = true; 4484 } 4485 } 4486st -> prev_match_pos = * st -> cur_match_pos ; 4487if (found_new_match == FAIL ) { 4488break ; 4489 } 4490 4491// when ADDING, the text before the cursor matches, skip it 4492if (compl_status_adding ()&& in_curbuf 4493&& start_pos -> lnum == st -> cur_match_pos -> lnum 4494&& start_pos -> col == st -> cur_match_pos -> col ) { 4495continue ; 4496 } 4497 4498if (!in_fuzzy_collect ) { 4499ptr = ins_compl_get_next_word_or_line (st -> ins_buf , 4500st -> cur_match_pos ,& len ,& cont_s_ipos ); 4501 } 4502if (ptr == NULL || (ins_compl_has_preinsert () 4503&& strcmp (ptr ,ins_compl_leader ())== 0 )) { 4504continue ; 4505 } 4506 4507if (is_nearest_active ()&& in_curbuf ) { 4508score = st -> cur_match_pos -> lnum - curwin -> w_cursor .lnum ; 4509if (score < 0 ) { 4510score = - score ; 4511 } 4512 } 4513 4514if (ins_compl_add_infercase (ptr ,len ,p_ic , 4515in_curbuf ?NULL :st -> ins_buf -> b_sfname , 45160 ,cont_s_ipos ,score )!= NOTDONE ) { 4517if (in_fuzzy_collect && score == compl_first_match -> cp_next -> cp_score ) { 4518compl_num_bests ++ ; 4519 } 4520found_new_match = OK ; 4521break ; 4522 } 4523 } 4524p_scs = save_p_scs ; 4525p_ws = save_p_ws ; 4526 4527return found_new_match ; 4528} 4529 4530/// Get completion matches from register contents. 4531/// Extracts words from all available registers and adds them to the completion list. 4532static void get_register_completion (void ) 4533{ 4534Direction dir = compl_direction ; 4535bool adding_mode = compl_status_adding (); 4536 4537for (int i = 0 ;i < NUM_REGISTERS ;i ++ ) { 4538int regname = get_register_name (i ); 4539// Skip invalid or black hole register 4540if (!valid_yank_reg (regname , false)|| regname == '_' ) { 4541continue ; 4542 } 4543 4544yankreg_T * reg = copy_register (regname ); 4545 4546if (reg -> y_array == NULL || reg -> y_size == 0 ) { 4547free_register (reg ); 4548xfree (reg ); 4549continue ; 4550 } 4551 4552for (size_t j = 0 ;j < reg -> y_size ;j ++ ) { 4553char * str = reg -> y_array [j ].data ; 4554if (str == NULL ) { 4555continue ; 4556 } 4557 4558if (adding_mode ) { 4559int str_len = (int )strlen (str ); 4560if (str_len == 0 ) { 4561continue ; 4562 } 4563 4564if (!compl_orig_text .data 4565|| (p_ic ?STRNICMP (str ,compl_orig_text .data , 4566compl_orig_text .size )== 0 4567 :strncmp (str ,compl_orig_text .data , 4568compl_orig_text .size )== 0 )) { 4569if (ins_compl_add_infercase (str ,str_len ,p_ic ,NULL , 4570dir , false,FUZZY_SCORE_NONE )== OK ) { 4571dir = FORWARD ; 4572 } 4573 } 4574 }else { 4575// Calculate the safe end of string to avoid null byte issues 4576char * str_end = str + strlen (str ); 4577char * p = str ; 4578 4579// Safely iterate through the string 4580while (p < str_end && * p != NUL ) { 4581char * old_p = p ; 4582p = find_word_start (p ); 4583if (p >=str_end || * p == NUL ) { 4584break ; 4585 } 4586 4587char * word_end = find_word_end (p ); 4588 4589if (word_end <=p ) { 4590word_end = p + utfc_ptr2len (p ); 4591 } 4592 4593if (word_end > str_end ) { 4594word_end = str_end ; 4595 } 4596 4597int len = (int )(word_end - p ); 4598if (len > 0 && (!compl_orig_text .data 4599|| (p_ic ?STRNICMP (p ,compl_orig_text .data , 4600compl_orig_text .size )== 0 4601 :strncmp (p ,compl_orig_text .data , 4602compl_orig_text .size )== 0 ))) { 4603if (ins_compl_add_infercase (p ,len ,p_ic ,NULL , 4604dir , false,FUZZY_SCORE_NONE )== OK ) { 4605dir = FORWARD ; 4606 } 4607 } 4608 4609p = word_end ; 4610 4611if (p <=old_p ) { 4612p = old_p + utfc_ptr2len (old_p ); 4613 } 4614 } 4615 } 4616 } 4617 4618free_register (reg ); 4619xfree (reg ); 4620 } 4621} 4622 4623/// Return the callback function associated with "p" if it refers to a 4624/// user-defined function in the 'complete' option. 4625/// The "idx" parameter is used for indexing callback entries. 4626static Callback * get_callback_if_cpt_func (char * p ,int idx ) 4627{ 4628if (* p == 'o' ) { 4629return & curbuf -> b_p_ofu ; 4630 } 4631 4632if (* p == 'F' ) { 4633if (*++ p != ',' && * p != NUL ) { 4634// 'F{func}' case 4635if (curbuf -> b_p_cpt_cb == NULL || idx < 0 || idx >=curbuf -> b_p_cpt_count ) { 4636return NULL ; 4637 } 4638return curbuf -> b_p_cpt_cb [idx ].type != kCallbackNone 4639 ?& curbuf -> b_p_cpt_cb [idx ] :NULL ; 4640 }else { 4641return & curbuf -> b_p_cfu ;// 'cfu' 4642 } 4643 } 4644 4645return NULL ; 4646} 4647 4648/// get the next set of completion matches for "type". 4649/// @return true if a new match is found, otherwise false. 4650static bool get_next_completion_match (int type ,ins_compl_next_state_T * st ,pos_T * ini ) 4651{ 4652int found_new_match = FAIL ; 4653 4654switch (type ) { 4655case -1 : 4656break ; 4657case CTRL_X_PATH_PATTERNS : 4658case CTRL_X_PATH_DEFINES : 4659get_next_include_file_completion (type ); 4660break ; 4661 4662case CTRL_X_DICTIONARY : 4663case CTRL_X_THESAURUS : 4664get_next_dict_tsr_completion (type ,st -> dict ,st -> dict_f ); 4665st -> dict = NULL ; 4666break ; 4667 4668case CTRL_X_TAGS : 4669get_next_tag_completion (); 4670break ; 4671 4672case CTRL_X_FILES : 4673get_next_filename_completion (); 4674break ; 4675 4676case CTRL_X_CMDLINE : 4677case CTRL_X_CMDLINE_CTRL_X : 4678get_next_cmdline_completion (); 4679break ; 4680 4681case CTRL_X_FUNCTION : 4682if (ctrl_x_mode_normal ()) {// Invoked by a func in 'cpt' option 4683get_cpt_func_completion_matches (st -> func_cb ); 4684 }else { 4685expand_by_function (type ,compl_pattern .data ,NULL ); 4686 } 4687break ; 4688case CTRL_X_OMNI : 4689expand_by_function (type ,compl_pattern .data ,NULL ); 4690break ; 4691 4692case CTRL_X_SPELL : 4693get_next_spell_completion (st -> first_match_pos .lnum ); 4694break ; 4695case CTRL_X_BUFNAMES : 4696get_next_bufname_token (); 4697break ; 4698case CTRL_X_REGISTER : 4699get_register_completion (); 4700break ; 4701 4702default :// normal ^P/^N and ^X^L 4703found_new_match = get_next_default_completion (st ,ini ); 4704if (found_new_match == FAIL && st -> ins_buf == curbuf ) { 4705st -> found_all = true; 4706 } 4707 } 4708 4709// check if compl_curr_match has changed, (e.g. other type of 4710// expansion added something) 4711if (type != 0 && compl_curr_match != compl_old_match ) { 4712found_new_match = OK ; 4713 } 4714 4715return found_new_match ; 4716} 4717 4718static void get_next_bufname_token (void ) 4719{ 4720FOR_ALL_BUFFERS (b ) { 4721if (b -> b_p_bl && b -> b_sfname != NULL ) { 4722char * tail = path_tail (b -> b_sfname ); 4723if (strncmp (tail ,compl_orig_text .data ,compl_orig_text .size )== 0 ) { 4724ins_compl_add (tail , (int )strlen (tail ),NULL ,NULL , false,NULL ,0 , 4725p_ic ?CP_ICASE :0 , false,NULL ,FUZZY_SCORE_NONE , false,NULL ); 4726 } 4727 } 4728 } 4729} 4730 4731/// Strips carets followed by numbers. This suffix typically represents the 4732/// max_matches setting. 4733static void strip_caret_numbers_in_place (char * str ) 4734{ 4735char * read = str ,* write = str ,* p ; 4736 4737if (str == NULL ) { 4738return ; 4739 } 4740 4741while (* read ) { 4742if (* read == '^' ) { 4743p = read + 1 ; 4744while (ascii_isdigit (* p )) { 4745p ++ ; 4746 } 4747if ((* p == ',' || * p == '\0' )&& p != read + 1 ) { 4748read = p ; 4749continue ; 4750 }else { 4751* write ++ = * read ++ ; 4752 } 4753 }else { 4754* write ++ = * read ++ ; 4755 } 4756 } 4757* write = '\0' ; 4758} 4759 4760/// Call functions specified in the 'cpt' option with findstart=1, 4761/// and retrieve the startcol. 4762static void prepare_cpt_compl_funcs (void ) 4763{ 4764// Make a copy of 'cpt' in case the buffer gets wiped out 4765char * cpt = xstrdup (curbuf -> b_p_cpt ); 4766strip_caret_numbers_in_place (cpt ); 4767 4768int idx = 0 ; 4769for (char * p = cpt ;* p ;) { 4770while (* p == ',' || * p == ' ' ) {// Skip delimiters 4771p ++ ; 4772 } 4773if (* p == NUL ) { 4774break ; 4775 } 4776 4777Callback * cb = get_callback_if_cpt_func (p ,idx ); 4778if (cb ) { 4779int startcol ; 4780if (get_userdefined_compl_info (curwin -> w_cursor .col ,cb ,& startcol )== FAIL ) { 4781if (startcol == -3 ) { 4782cpt_sources_array [idx ].cs_refresh_always = false; 4783 }else { 4784startcol = -2 ; 4785 } 4786 }else if (startcol < 0 || startcol > curwin -> w_cursor .col ) { 4787startcol = curwin -> w_cursor .col ; 4788 } 4789cpt_sources_array [idx ].cs_startcol = startcol ; 4790 }else { 4791cpt_sources_array [idx ].cs_startcol = -3 ; 4792 } 4793 4794 (void )copy_option_part (& p ,IObuff ,IOSIZE ,"," );// Advance p 4795idx ++ ; 4796 } 4797 4798xfree (cpt ); 4799} 4800 4801/// Start the timer for the current completion source. 4802static void compl_source_start_timer (int source_idx ) 4803{ 4804if (compl_autocomplete || p_cto > 0 ) { 4805cpt_sources_array [source_idx ].compl_start_tv = os_hrtime (); 4806compl_time_slice_expired = false; 4807 } 4808} 4809 4810/// Safely advance the cpt_sources_index by one. 4811static int advance_cpt_sources_index_safe (void ) 4812{ 4813if (cpt_sources_index >=0 && cpt_sources_index < cpt_sources_count - 1 ) { 4814cpt_sources_index ++ ; 4815return OK ; 4816 } 4817semsg (_ (e_list_index_out_of_range_nr ),cpt_sources_index ); 4818return FAIL ; 4819} 4820 4821/// Get the next expansion(s), using "compl_pattern". 4822/// The search starts at position "ini" in curbuf and in the direction 4823/// compl_direction. 4824/// When "compl_started" is false start at that position, otherwise continue 4825/// where we stopped searching before. 4826/// This may return before finding all the matches. 4827/// Return the total number of matches or -1 if still unknown -- Acevedo 4828static int ins_compl_get_exp (pos_T * ini ) 4829{ 4830static ins_compl_next_state_T st ; 4831static bool st_cleared = false; 4832int found_new_match ; 4833int type = ctrl_x_mode ; 4834bool may_advance_cpt_idx = false; 4835pos_T start_pos = * ini ; 4836 4837assert (curbuf != NULL ); 4838 4839if (!compl_started ) { 4840FOR_ALL_BUFFERS (buf ) { 4841buf -> b_scanned = false; 4842 } 4843if (!st_cleared ) { 4844CLEAR_FIELD (st ); 4845st_cleared = true; 4846 } 4847st .found_all = false; 4848st .ins_buf = curbuf ; 4849xfree (st .e_cpt_copy ); 4850// Make a copy of 'complete', in case the buffer is wiped out. 4851st .e_cpt_copy = xstrdup ((compl_cont_status & CONT_LOCAL ) ?"." :curbuf -> b_p_cpt ); 4852strip_caret_numbers_in_place (st .e_cpt_copy ); 4853st .e_cpt = st .e_cpt_copy ; 4854 4855// In large buffers, timeout may miss nearby matches — search above cursor 4856#define LOOKBACK_LINE_COUNT 1000 4857if (compl_autocomplete && is_nearest_active ()) { 4858start_pos .lnum = MAX (1 ,start_pos .lnum - LOOKBACK_LINE_COUNT ); 4859start_pos .col = 0 ; 4860 } 4861st .last_match_pos = st .first_match_pos = start_pos ; 4862 }else if (st .ins_buf != curbuf && !buf_valid (st .ins_buf )) { 4863st .ins_buf = curbuf ;// In case the buffer was wiped out. 4864 } 4865assert (st .ins_buf != NULL ); 4866 4867compl_old_match = compl_curr_match ;// remember the last current match 4868st .cur_match_pos = compl_dir_forward () ?& st .last_match_pos :& st .first_match_pos ; 4869 4870bool normal_mode_strict = ctrl_x_mode_normal ()&& !ctrl_x_mode_line_or_eval () 4871&& !(compl_cont_status & CONT_LOCAL ) 4872&& cpt_sources_array != NULL ; 4873if (normal_mode_strict ) { 4874cpt_sources_index = 0 ; 4875if (compl_autocomplete || p_cto > 0 ) { 4876compl_source_start_timer (0 ); 4877compl_time_slice_expired = false; 4878compl_timeout_ms = compl_autocomplete 4879 ? (uint64_t )MAX (COMPL_INITIAL_TIMEOUT_MS ,p_act ) 4880 : (uint64_t )p_cto ; 4881 } 4882 } 4883 4884// For ^N/^P loop over all the flags/windows/buffers in 'complete' 4885while (true) { 4886found_new_match = FAIL ; 4887st .set_match_pos = false; 4888 4889// For ^N/^P pick a new entry from e_cpt if compl_started is off, 4890// or if found_all says this entry is done. For ^X^L only use the 4891// entries from 'complete' that look in loaded buffers. 4892if ((ctrl_x_mode_normal ()|| ctrl_x_mode_line_or_eval ()) 4893&& (!compl_started || st .found_all )) { 4894int status = process_next_cpt_value (& st ,& type ,& start_pos , 4895cot_fuzzy (),& may_advance_cpt_idx ); 4896if (status == INS_COMPL_CPT_END ) { 4897break ; 4898 } 4899if (status == INS_COMPL_CPT_CONT ) { 4900if (may_advance_cpt_idx ) { 4901if (!advance_cpt_sources_index_safe ()) { 4902break ; 4903 } 4904compl_source_start_timer (cpt_sources_index ); 4905 } 4906continue ; 4907 } 4908 } 4909 4910uint64_t compl_timeout_save = 0 ; 4911if (normal_mode_strict && type == CTRL_X_FUNCTION 4912&& (compl_autocomplete || p_cto > 0 )) { 4913// LSP servers may sporadically take >1s to respond (e.g., while 4914// loading modules), but other sources might already have matches. 4915// To show results quickly use a short timeout for keyword 4916// completion. Allow longer timeout for non-keyword completion 4917// where only function based sources (e.g. LSP) are active. 4918compl_timeout_save = compl_timeout_ms ; 4919compl_timeout_ms = compl_from_nonkeyword 4920 ?COMPL_FUNC_TIMEOUT_NON_KW_MS :COMPL_FUNC_TIMEOUT_MS ; 4921 } 4922 4923// get the next set of completion matches 4924found_new_match = get_next_completion_match (type ,& st ,& start_pos ); 4925 4926// If complete() was called then compl_pattern has been reset. 4927// The following won't work then, bail out. 4928if (compl_pattern .data == NULL ) { 4929break ; 4930 } 4931 4932if (may_advance_cpt_idx ) { 4933if (!advance_cpt_sources_index_safe ()) { 4934break ; 4935 } 4936compl_source_start_timer (cpt_sources_index ); 4937 } 4938 4939// break the loop for specialized modes (use 'complete' just for the 4940// generic ctrl_x_mode == CTRL_X_NORMAL) or when we've found a new match 4941if ((ctrl_x_mode_not_default ()&& !ctrl_x_mode_line_or_eval ()) 4942|| found_new_match != FAIL ) { 4943if (got_int ) { 4944break ; 4945 } 4946// Fill the popup menu as soon as possible. 4947if (type != -1 ) { 4948ins_compl_check_keys (0 , false); 4949 } 4950 4951if ((ctrl_x_mode_not_default ()&& !ctrl_x_mode_line_or_eval ()) 4952|| compl_interrupted ) { 4953break ; 4954 } 4955compl_started = !compl_time_slice_expired ; 4956 }else { 4957// Mark a buffer scanned when it has been scanned completely 4958if (buf_valid (st .ins_buf )&& (type == 0 || type == CTRL_X_PATH_PATTERNS )) { 4959assert (st .ins_buf ); 4960st .ins_buf -> b_scanned = true; 4961 } 4962 4963compl_started = false; 4964 } 4965 4966// Restore the timeout after collecting matches from function source 4967if (normal_mode_strict && type == CTRL_X_FUNCTION 4968&& (compl_autocomplete || p_cto > 0 )) { 4969compl_timeout_ms = compl_timeout_save ; 4970 } 4971 4972// For `^P` completion, reset `compl_curr_match` to the head to avoid 4973// mixing matches from different sources. 4974if (!compl_dir_forward ()) { 4975while (compl_curr_match -> cp_prev 4976&& !match_at_original_text (compl_curr_match -> cp_prev )) { 4977compl_curr_match = compl_curr_match -> cp_prev ; 4978 } 4979 } 4980 } 4981cpt_sources_index = -1 ; 4982compl_started = true; 4983 4984if ((ctrl_x_mode_normal ()|| ctrl_x_mode_line_or_eval ()) 4985&& * st .e_cpt == NUL ) {// Got to end of 'complete' 4986found_new_match = FAIL ; 4987 } 4988 4989int match_count = -1 ;// total of matches, unknown 4990if (found_new_match == FAIL 4991|| (ctrl_x_mode_not_default ()&& !ctrl_x_mode_line_or_eval ())) { 4992match_count = ins_compl_make_cyclic (); 4993 } 4994 4995if (cot_fuzzy ()&& compl_get_longest && compl_num_bests > 0 ) { 4996fuzzy_longest_match (); 4997 } 4998 4999if (compl_old_match != NULL ) { 5000// If several matches were added (FORWARD) or the search failed and has 5001// just been made cyclic then we have to move compl_curr_match to the 5002// next or previous entry (if any) -- Acevedo 5003compl_curr_match = compl_dir_forward () 5004 ?compl_old_match -> cp_next 5005 :compl_old_match -> cp_prev ; 5006if (compl_curr_match == NULL ) { 5007compl_curr_match = compl_old_match ; 5008 } 5009 } 5010may_trigger_modechanged (); 5011 5012if (match_count > 0 && !ctrl_x_mode_spell ()) { 5013if (is_nearest_active ()&& !ins_compl_has_preinsert ()) { 5014sort_compl_match_list (cp_compare_nearest ); 5015 } 5016 5017if (cot_fuzzy ()&& ins_compl_leader_len ()> 0 ) { 5018ins_compl_fuzzy_sort (); 5019 } 5020 } 5021 5022return match_count ; 5023} 5024 5025/// Update "compl_shown_match" to the actually shown match, it may differ when 5026/// "compl_leader" is used to omit some of the matches. 5027static void ins_compl_update_shown_match (void ) 5028{ 5029 (void )get_leader_for_startcol (NULL , true);// Clear the cache 5030String * leader = get_leader_for_startcol (compl_shown_match , true); 5031 5032while (!ins_compl_equal (compl_shown_match ,leader -> data ,leader -> size ) 5033&& compl_shown_match -> cp_next != NULL 5034&& !is_first_match (compl_shown_match -> cp_next )) { 5035compl_shown_match = compl_shown_match -> cp_next ; 5036leader = get_leader_for_startcol (compl_shown_match , true); 5037 } 5038 5039// If we didn't find it searching forward, and compl_shows_dir is 5040// backward, find the last match. 5041if (compl_shows_dir_backward () 5042&& !ins_compl_equal (compl_shown_match ,leader -> data ,leader -> size ) 5043&& (compl_shown_match -> cp_next == NULL 5044|| is_first_match (compl_shown_match -> cp_next ))) { 5045while (!ins_compl_equal (compl_shown_match ,leader -> data ,leader -> size ) 5046&& compl_shown_match -> cp_prev != NULL 5047&& !is_first_match (compl_shown_match -> cp_prev )) { 5048compl_shown_match = compl_shown_match -> cp_prev ; 5049leader = get_leader_for_startcol (compl_shown_match , true); 5050 } 5051 } 5052} 5053 5054/// Delete the old text being completed. 5055void ins_compl_delete (bool new_leader ) 5056{ 5057// Avoid deleting text that will be reinserted when changing leader. This 5058// allows marks present on the original text to shrink/grow appropriately. 5059int orig_col = 0 ; 5060if (new_leader ) { 5061char * orig = compl_orig_text .data ; 5062char * leader = ins_compl_leader (); 5063while (* orig != NUL && utf_ptr2char (orig )== utf_ptr2char (leader )) { 5064leader += utf_ptr2len (leader ); 5065orig += utf_ptr2len (orig ); 5066 } 5067orig_col = (int )(orig - compl_orig_text .data ); 5068 } 5069 5070// In insert mode: Delete the typed part. 5071// In replace mode: Put the old characters back, if any. 5072int col = compl_col + (compl_status_adding () ?compl_length :orig_col ); 5073 5074if (ins_compl_preinsert_effect ()) { 5075col += (int )ins_compl_leader_len (); 5076curwin -> w_cursor .col = compl_ins_end_col ; 5077 } 5078 5079String remaining = STRING_INIT ; 5080if (curwin -> w_cursor .lnum > compl_lnum ) { 5081if (curwin -> w_cursor .col < get_cursor_line_len ()) { 5082remaining = cbuf_to_string (get_cursor_pos_ptr (), (size_t )get_cursor_pos_len ()); 5083 } 5084 5085while (curwin -> w_cursor .lnum > compl_lnum ) { 5086if (ml_delete (curwin -> w_cursor .lnum )== FAIL ) { 5087if (remaining .data ) { 5088xfree (remaining .data ); 5089 } 5090return ; 5091 } 5092deleted_lines_mark (curwin -> w_cursor .lnum ,1 ); 5093curwin -> w_cursor .lnum -- ; 5094 } 5095// move cursor to end of line 5096curwin -> w_cursor .col = get_cursor_line_len (); 5097 } 5098 5099if ((int )curwin -> w_cursor .col > col ) { 5100if (stop_arrow ()== FAIL ) { 5101if (remaining .data ) { 5102xfree (remaining .data ); 5103 } 5104return ; 5105 } 5106backspace_until_column (col ); 5107compl_ins_end_col = curwin -> w_cursor .col ; 5108 } 5109 5110if (remaining .data != NULL ) { 5111orig_col = curwin -> w_cursor .col ; 5112ins_str (remaining .data ,remaining .size ); 5113curwin -> w_cursor .col = orig_col ; 5114xfree (remaining .data ); 5115 } 5116 5117// TODO(vim): is this sufficient for redrawing? Redrawing everything 5118// causes flicker, thus we can't do that. 5119changed_cline_bef_curs (curwin ); 5120// clear v:completed_item 5121set_vim_var_dict (VV_COMPLETED_ITEM ,tv_dict_alloc_lock (VAR_FIXED )); 5122} 5123 5124/// Insert a completion string that contains newlines. 5125/// The string is split and inserted line by line. 5126static void ins_compl_expand_multiple (char * str ) 5127{ 5128char * start = str ; 5129char * curr = str ; 5130int base_indent = get_indent (); 5131while (* curr != NUL ) { 5132if (* curr == '\n' ) { 5133// Insert the text chunk before newline 5134if (curr > start ) { 5135ins_char_bytes (start , (size_t )(curr - start )); 5136 } 5137 5138// Handle newline 5139open_line (FORWARD ,OPENLINE_KEEPTRAIL |OPENLINE_FORCE_INDENT ,base_indent ,NULL ); 5140start = curr + 1 ; 5141 } 5142curr ++ ; 5143 } 5144 5145// Handle remaining text after last newline (if any) 5146if (curr > start ) { 5147ins_char_bytes (start , (size_t )(curr - start )); 5148 } 5149 5150compl_ins_end_col = curwin -> w_cursor .col ; 5151} 5152 5153/// Find the longest common prefix among the current completion matches. 5154/// Returns a pointer to the first match string, with *prefix_len set to 5155/// the length of the common prefix. 5156/// If "curbuf_only" is true, restrict matches to the current buffer 5157/// ('.' source in 'complete'). 5158static char * find_common_prefix (size_t * prefix_len ,bool curbuf_only ) 5159{ 5160bool is_cpt_completion = (cpt_sources_array != NULL ); 5161 5162if (!is_cpt_completion ) { 5163return NULL ; 5164 } 5165 5166int * match_count = xcalloc ((size_t )cpt_sources_count ,sizeof (int )); 5167 5168 (void )get_leader_for_startcol (NULL , true);// Clear the cache 5169 5170compl_T * compl = compl_first_match ; 5171char * first = NULL ; 5172int len = -1 ; 5173do { 5174String * leader = get_leader_for_startcol (compl , true); 5175 5176// Apply 'smartcase' behavior during normal mode 5177if (ctrl_x_mode_normal ()&& !p_inf && compl_orig_text .data 5178&& !ignorecase (compl_orig_text .data )) { 5179compl -> cp_flags &= ~CP_ICASE ; 5180 } 5181 5182if (!match_at_original_text (compl ) 5183&& (leader -> data == NULL 5184|| ins_compl_equal_sc (compl ,leader -> data ,leader -> size ))) { 5185// Limit number of items from each source if max_items is set. 5186bool match_limit_exceeded = false; 5187int cur_source = compl -> cp_cpt_source_idx ; 5188 5189if (cur_source != -1 ) { 5190match_count [cur_source ]++ ; 5191int max_matches = cpt_sources_array [cur_source ].cs_max_matches ; 5192if (max_matches > 0 && match_count [cur_source ]> max_matches ) { 5193match_limit_exceeded = true; 5194 } 5195 } 5196 5197if (!match_limit_exceeded 5198&& (!curbuf_only || (cur_source != -1 5199&& cpt_sources_array [cur_source ].cs_flag == '.' ))) { 5200if (first == NULL && strncmp (ins_compl_leader (),compl -> cp_str .data , 5201ins_compl_leader_len ())== 0 ) { 5202first = compl -> cp_str .data ; 5203len = (int )strlen (first ); 5204 }else if (first != NULL ) { 5205int j = 0 ;// count in bytes 5206char * s1 = first ; 5207char * s2 = compl -> cp_str .data ; 5208 5209while (j < len && * s1 != NUL && * s2 != NUL ) { 5210if (MB_BYTE2LEN ((uint8_t )(* s1 ))!= MB_BYTE2LEN ((uint8_t )(* s2 )) 5211|| memcmp (s1 ,s2 ,MB_BYTE2LEN ((uint8_t )(* s1 )))!= 0 ) { 5212break ; 5213 } 5214 5215j += MB_BYTE2LEN ((uint8_t )(* s1 )); 5216MB_PTR_ADV (s1 ); 5217MB_PTR_ADV (s2 ); 5218 } 5219len = j ; 5220 5221if (len == 0 ) { 5222break ; 5223 } 5224 } 5225 } 5226 } 5227compl = compl -> cp_next ; 5228 }while (compl != NULL && !is_first_match (compl )); 5229 5230xfree (match_count ); 5231 5232if (len > (int )ins_compl_leader_len ()) { 5233assert (first != NULL ); 5234// Avoid inserting text that duplicates the text already present 5235// after the cursor. 5236if (len == (int )strlen (first )) { 5237char * line = get_cursor_line_ptr (); 5238char * p = line + curwin -> w_cursor .col ; 5239if (p && !ascii_iswhite_or_nul (* p )) { 5240char * end = find_word_end (p ); 5241int text_len = (int )(end - p ); 5242if (text_len > 0 && text_len < (len - (int )ins_compl_leader_len ()) 5243&& strncmp (first + len - text_len ,p , (size_t )text_len )== 0 ) { 5244len -= text_len ; 5245 } 5246 } 5247 } 5248* prefix_len = (size_t )len ; 5249return first ; 5250 } 5251return NULL ; 5252} 5253 5254/// Insert the new text being completed. 5255/// "move_cursor" is used when 'completeopt' includes "preinsert" and when true 5256/// cursor needs to move back from the inserted text to the compl_leader. 5257/// When "insert_prefix" is true the longest common prefix is inserted instead 5258/// of shown match. 5259void ins_compl_insert (bool move_cursor ,bool insert_prefix ) 5260{ 5261int compl_len = get_compl_len (); 5262bool preinsert = ins_compl_has_preinsert (); 5263char * cp_str = compl_shown_match -> cp_str .data ; 5264size_t cp_str_len = compl_shown_match -> cp_str .size ; 5265size_t leader_len = ins_compl_leader_len (); 5266char * has_multiple = strchr (cp_str ,'\n' ); 5267 5268if (insert_prefix ) { 5269cp_str = find_common_prefix (& cp_str_len , false); 5270if (cp_str == NULL ) { 5271cp_str = find_common_prefix (& cp_str_len , true); 5272if (cp_str == NULL ) { 5273cp_str = compl_shown_match -> cp_str .data ; 5274cp_str_len = compl_shown_match -> cp_str .size ; 5275 } 5276 } 5277 }else if (cpt_sources_array != NULL ) { 5278// Since completion sources may provide matches with varying start 5279// positions, insert only the portion of the match that corresponds to the 5280// intended replacement range. 5281int cpt_idx = compl_shown_match -> cp_cpt_source_idx ; 5282if (cpt_idx >=0 && compl_col >=0 ) { 5283int startcol = cpt_sources_array [cpt_idx ].cs_startcol ; 5284if (startcol >=0 && startcol < (int )compl_col ) { 5285int skip = (int )compl_col - startcol ; 5286if ((size_t )skip <=cp_str_len ) { 5287cp_str_len -= (size_t )skip ; 5288cp_str += skip ; 5289 } 5290 } 5291 } 5292 } 5293 5294// Make sure we don't go over the end of the string, this can happen with 5295// illegal bytes. 5296if (compl_len < (int )cp_str_len ) { 5297if (has_multiple ) { 5298ins_compl_expand_multiple (cp_str + compl_len ); 5299 }else { 5300ins_compl_insert_bytes (cp_str + compl_len , 5301insert_prefix ? (int )cp_str_len - compl_len :-1 ); 5302if ((preinsert || insert_prefix )&& move_cursor ) { 5303curwin -> w_cursor .col -= (colnr_T )(cp_str_len - leader_len ); 5304 } 5305 } 5306 } 5307compl_used_match = !(match_at_original_text (compl_shown_match ) 5308|| (preinsert && !insert_prefix )); 5309 5310dict_T * dict = ins_compl_dict_alloc (compl_shown_match ); 5311set_vim_var_dict (VV_COMPLETED_ITEM ,dict ); 5312compl_hi_on_autocompl_longest = insert_prefix && move_cursor ; 5313} 5314 5315/// show the file name for the completion match (if any). Truncate the file 5316/// name to avoid a wait for return. 5317static void ins_compl_show_filename (void ) 5318{ 5319char * const lead = _ ("match in file" ); 5320 5321// In the case of ext_messages, `sc_col` is obsolete. Fortunately, long messages are no longer 5322// disruptive, so truncation could be skipped. But in this particular case, with default 5323// configuration `showmode cmdheight=1`, a multi-line message is shown partially, and a message 5324// that fits into one line is not shown at all. It's better to be consistent: it should not depend 5325// on the exact length of the message whether it is displayed at all. 5326int space = (ui_has (kUIMessages ) ?Columns :sc_col )- vim_strsize (lead )- 2 ; 5327if (space <=0 ) { 5328return ; 5329 } 5330 5331// We need the tail that fits. With double-byte encoding going 5332// back from the end is very slow, thus go from the start and keep 5333// the text that fits in "space" between "s" and "e". 5334char * s ; 5335char * e ; 5336for (s = e = compl_shown_match -> cp_fname ;* e != NUL ;MB_PTR_ADV (e )) { 5337space -= ptr2cells (e ); 5338while (space < 0 ) { 5339space += ptr2cells (s ); 5340MB_PTR_ADV (s ); 5341 } 5342 } 5343if (!compl_autocomplete ) { 5344msg_hist_off = true; 5345vim_snprintf (IObuff ,IOSIZE ,"%s %s%s" ,lead , 5346s > compl_shown_match -> cp_fname ?"<" :"" ,s ); 5347msg (IObuff ,0 ); 5348msg_hist_off = false; 5349redraw_cmdline = false;// don't overwrite! 5350 } 5351} 5352 5353/// Find the appropriate completion item when 'complete' ('cpt') includes 5354/// a 'max_matches' postfix. In this case, we search for a match where 5355/// 'cp_in_match_array' is set, indicating that the match is also present 5356/// in 'compl_match_array'. 5357static compl_T * find_next_match_in_menu (void ) 5358{ 5359bool is_forward = compl_shows_dir_forward (); 5360compl_T * match = compl_shown_match ; 5361 5362do { 5363match = is_forward ?match -> cp_next :match -> cp_prev ; 5364 }while (match -> cp_next && !match -> cp_in_match_array 5365&& !match_at_original_text (match )); 5366return match ; 5367} 5368 5369/// Find the next set of matches for completion. Repeat the completion "todo" 5370/// times. The number of matches found is returned in 'num_matches'. 5371/// 5372/// @param allow_get_expansion If true, then ins_compl_get_exp() may be called to 5373/// get more completions. 5374/// If false, then do nothing when there are no more 5375/// completions in the given direction. 5376/// @param todo repeat completion this many times 5377/// @param advance If true, then completion will move to the first match. 5378/// Otherwise, the original text will be shown. 5379/// 5380/// @return OK on success and -1 if the number of matches are unknown. 5381static int find_next_completion_match (bool allow_get_expansion ,int todo ,bool advance , 5382int * num_matches ) 5383{ 5384bool found_end = false; 5385compl_T * found_compl = NULL ; 5386unsigned cur_cot_flags = get_cot_flags (); 5387bool compl_no_select = (cur_cot_flags & kOptCotFlagNoselect )!= 0 5388|| (compl_autocomplete && !ins_compl_has_preinsert ()); 5389 5390while (-- todo >=0 ) { 5391if (compl_shows_dir_forward ()&& compl_shown_match -> cp_next != NULL ) { 5392if (compl_match_array != NULL ) { 5393compl_shown_match = find_next_match_in_menu (); 5394 }else { 5395compl_shown_match = compl_shown_match -> cp_next ; 5396 } 5397found_end = (compl_first_match != NULL 5398&& (is_first_match (compl_shown_match -> cp_next ) 5399|| is_first_match (compl_shown_match ))); 5400 }else if (compl_shows_dir_backward () 5401&& compl_shown_match -> cp_prev != NULL ) { 5402found_end = is_first_match (compl_shown_match ); 5403if (compl_match_array != NULL ) { 5404compl_shown_match = find_next_match_in_menu (); 5405 }else { 5406compl_shown_match = compl_shown_match -> cp_prev ; 5407 } 5408found_end |=is_first_match (compl_shown_match ); 5409 }else { 5410if (!allow_get_expansion ) { 5411if (advance ) { 5412if (compl_shows_dir_backward ()) { 5413compl_pending -= todo + 1 ; 5414 }else { 5415compl_pending += todo + 1 ; 5416 } 5417 } 5418return -1 ; 5419 } 5420 5421if (!compl_no_select && advance ) { 5422if (compl_shows_dir_backward ()) { 5423compl_pending -- ; 5424 }else { 5425compl_pending ++ ; 5426 } 5427 } 5428 5429// Find matches. 5430* num_matches = ins_compl_get_exp (& compl_startpos ); 5431 5432// handle any pending completions 5433while (compl_pending != 0 && compl_direction == compl_shows_dir 5434&& advance ) { 5435if (compl_pending > 0 && compl_shown_match -> cp_next != NULL ) { 5436compl_shown_match = compl_shown_match -> cp_next ; 5437compl_pending -- ; 5438 }else if (compl_pending < 0 && compl_shown_match -> cp_prev != NULL ) { 5439compl_shown_match = compl_shown_match -> cp_prev ; 5440compl_pending ++ ; 5441 }else { 5442break ; 5443 } 5444 } 5445found_end = false; 5446 } 5447 5448String * leader = get_leader_for_startcol (compl_shown_match , false); 5449 5450if (!match_at_original_text (compl_shown_match ) 5451&& leader -> data != NULL 5452&& !ins_compl_equal (compl_shown_match ,leader -> data ,leader -> size ) 5453&& !(cot_fuzzy ()&& compl_shown_match -> cp_score != FUZZY_SCORE_NONE )) { 5454todo ++ ; 5455 }else { 5456// Remember a matching item. 5457found_compl = compl_shown_match ; 5458 } 5459 5460// Stop at the end of the list when we found a usable match. 5461if (found_end ) { 5462if (found_compl != NULL ) { 5463compl_shown_match = found_compl ; 5464break ; 5465 } 5466todo = 1 ;// use first usable match after wrapping around 5467 } 5468 } 5469 5470return OK ; 5471} 5472 5473/// Fill in the next completion in the current direction. 5474/// If "allow_get_expansion" is true, then we may call ins_compl_get_exp() to 5475/// get more completions. If it is false, then we just do nothing when there 5476/// are no more completions in a given direction. The latter case is used when 5477/// we are still in the middle of finding completions, to allow browsing 5478/// through the ones found so far. 5479/// @return the total number of matches, or -1 if still unknown -- webb. 5480/// 5481/// compl_curr_match is currently being used by ins_compl_get_exp(), so we use 5482/// compl_shown_match here. 5483/// 5484/// Note that this function may be called recursively once only. First with 5485/// "allow_get_expansion" true, which calls ins_compl_get_exp(), which in turn 5486/// calls this function with "allow_get_expansion" false. 5487/// 5488/// @param count Repeat completion this many times; should be at least 1 5489/// @param insert_match Insert the newly selected match 5490static int ins_compl_next (bool allow_get_expansion ,int count ,bool insert_match ) 5491{ 5492int num_matches = -1 ; 5493int todo = count ; 5494const bool started = compl_started ; 5495buf_T * const orig_curbuf = curbuf ; 5496unsigned cur_cot_flags = get_cot_flags (); 5497bool compl_no_insert = (cur_cot_flags & kOptCotFlagNoinsert )!= 0 5498|| (compl_autocomplete && !ins_compl_has_preinsert ()); 5499bool compl_preinsert = ins_compl_has_preinsert (); 5500 5501// When user complete function return -1 for findstart which is next 5502// time of 'always', compl_shown_match become NULL. 5503if (compl_shown_match == NULL ) { 5504return -1 ; 5505 } 5506 5507if (compl_leader .data != NULL 5508&& !match_at_original_text (compl_shown_match ) 5509&& !cot_fuzzy ()) { 5510// Update "compl_shown_match" to the actually shown match 5511ins_compl_update_shown_match (); 5512 } 5513 5514if (allow_get_expansion && insert_match 5515&& (!compl_get_longest || compl_used_match )) { 5516// Delete old text to be replaced 5517ins_compl_delete (false); 5518 } 5519 5520// When finding the longest common text we stick at the original text, 5521// don't let CTRL-N or CTRL-P move to the first match. 5522bool advance = count != 1 || !allow_get_expansion || !compl_get_longest ; 5523 5524// When restarting the search don't insert the first match either. 5525if (compl_restarting ) { 5526advance = false; 5527compl_restarting = false; 5528 } 5529 5530// Repeat this for when <PageUp> or <PageDown> is typed. But don't wrap 5531// around. 5532if (find_next_completion_match (allow_get_expansion ,todo ,advance , 5533& num_matches )== -1 ) { 5534return -1 ; 5535 } 5536 5537if (curbuf != orig_curbuf ) { 5538// In case some completion function switched buffer, don't want to 5539// insert the completion elsewhere. 5540return -1 ; 5541 } 5542 5543// Insert the text of the new completion, or the compl_leader. 5544if (!started && ins_compl_preinsert_longest ()) { 5545ins_compl_insert (true, true); 5546 }else if (compl_no_insert && !started && !compl_preinsert ) { 5547ins_compl_insert_bytes (compl_orig_text .data + get_compl_len (),-1 ); 5548compl_used_match = false; 5549restore_orig_extmarks (); 5550 }else if (insert_match ) { 5551if (!compl_get_longest || compl_used_match ) { 5552bool preinsert_longest = ins_compl_preinsert_longest () 5553&& match_at_original_text (compl_shown_match );// none selected 5554ins_compl_insert (compl_preinsert || preinsert_longest ,preinsert_longest ); 5555 }else { 5556assert (compl_leader .data != NULL ); 5557ins_compl_insert_bytes (compl_leader .data + get_compl_len (),-1 ); 5558 } 5559if (strequal (compl_shown_match -> cp_str .data ,compl_orig_text .data )) { 5560restore_orig_extmarks (); 5561 } 5562 }else { 5563compl_used_match = false; 5564 } 5565 5566if (!allow_get_expansion ) { 5567// redraw to show the user what was inserted 5568update_screen ();// TODO(bfredl): no! 5569 5570// display the updated popup menu 5571ins_compl_show_pum (); 5572 5573// Delete old text to be replaced, since we're still searching and 5574// don't want to match ourselves! 5575ins_compl_delete (false); 5576 } 5577 5578// Enter will select a match when the match wasn't inserted and the popup 5579// menu is visible. 5580if (compl_no_insert && !started && !match_at_original_text (compl_shown_match )) { 5581compl_enter_selects = true; 5582 }else { 5583compl_enter_selects = !insert_match && compl_match_array != NULL ; 5584 } 5585 5586// Show the file name for the match (if any) 5587if (compl_shown_match -> cp_fname != NULL ) { 5588ins_compl_show_filename (); 5589 } 5590 5591return num_matches ; 5592} 5593 5594/// Check if the current completion source exceeded its timeout. If so, stop 5595/// collecting, and halve the timeout. 5596static void check_elapsed_time (void ) 5597{ 5598uint64_t start_tv = cpt_sources_array [cpt_sources_index ].compl_start_tv ; 5599uint64_t elapsed_ms = (os_hrtime ()- start_tv ) /1000000 ; 5600 5601if (elapsed_ms > compl_timeout_ms ) { 5602compl_time_slice_expired = true; 5603DECAY_COMPL_TIMEOUT (); 5604 } 5605} 5606 5607/// Call this while finding completions, to check whether the user has hit a key 5608/// that should change the currently displayed completion, or exit completion 5609/// mode. Also, when compl_pending is not zero, show a completion as soon as 5610/// possible. -- webb 5611/// 5612/// @param frequency specifies out of how many calls we actually check. 5613/// @param in_compl_func true when called from complete_check(), don't set 5614/// compl_curr_match. 5615void ins_compl_check_keys (int frequency ,bool in_compl_func ) 5616{ 5617static int count = 0 ; 5618 5619// Don't check when reading keys from a script, :normal or feedkeys(). 5620// That would break the test scripts. But do check for keys when called 5621// from complete_check(). 5622if (!in_compl_func && (using_script ()|| ex_normal_busy )) { 5623return ; 5624 } 5625 5626// Only do this at regular intervals 5627if (++ count < frequency ) { 5628return ; 5629 } 5630count = 0 ; 5631 5632// Check for a typed key. Do use mappings, otherwise vim_is_ctrl_x_key() 5633// can't do its work correctly. 5634int c = vpeekc_any (); 5635if (c != NUL && !test_disable_char_avail ) { 5636if (vim_is_ctrl_x_key (c )&& c != Ctrl_X && c != Ctrl_R ) { 5637c = safe_vgetc ();// Eat the character 5638compl_shows_dir = ins_compl_key2dir (c ); 5639ins_compl_next (false,ins_compl_key2count (c ),c != K_UP && c != K_DOWN ); 5640 }else { 5641// Need to get the character to have KeyTyped set. We'll put it 5642// back with vungetc() below. But skip K_IGNORE. 5643c = safe_vgetc (); 5644if (c != K_IGNORE ) { 5645// Typed keys that get mapped lose KeyTyped. Still let 5646// complete_check() interrupt, except during @r replay. 5647if (c != Ctrl_R && (KeyTyped || (in_compl_func && reg_executing == 0 ))) { 5648compl_interrupted = true; 5649 } 5650 5651vungetc (c ); 5652 } 5653 } 5654 }else { 5655bool normal_mode_strict = ctrl_x_mode_normal ()&& !ctrl_x_mode_line_or_eval () 5656&& !(compl_cont_status & CONT_LOCAL ) 5657&& cpt_sources_array != NULL && cpt_sources_index >=0 ; 5658if (normal_mode_strict && (compl_autocomplete || p_cto > 0 )) { 5659check_elapsed_time (); 5660 } 5661 } 5662 5663if (compl_pending 5664&& !got_int 5665&& !(cot_flags & (kOptCotFlagNoinsert |kOptCotFlagFuzzy )) 5666&& (!compl_autocomplete || ins_compl_has_preinsert ())) { 5667// Insert the first match immediately and advance compl_shown_match, 5668// before finding other matches. 5669int todo = compl_pending > 0 ?compl_pending :- compl_pending ; 5670 5671compl_pending = 0 ; 5672ins_compl_next (false,todo , true); 5673 } 5674} 5675 5676/// Decide the direction of Insert mode complete from the key typed. 5677/// Returns BACKWARD or FORWARD. 5678static int ins_compl_key2dir (int c ) 5679{ 5680if (c == K_EVENT || c == K_COMMAND || c == K_LUA ) { 5681return pum_want .item < compl_selected_item ?BACKWARD :FORWARD ; 5682 } 5683if (c == Ctrl_P || c == Ctrl_L 5684|| c == K_PAGEUP || c == K_KPAGEUP 5685|| c == K_S_UP || c == K_UP ) { 5686return BACKWARD ; 5687 } 5688return FORWARD ; 5689} 5690 5691/// Check that "c" is a valid completion key only while the popup menu is shown 5692/// 5693/// @param c character to check 5694static bool ins_compl_pum_key (int c ) 5695FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT 5696{ 5697return pum_visible ()&& (c == K_PAGEUP || c == K_KPAGEUP || c == K_S_UP 5698|| c == K_PAGEDOWN || c == K_KPAGEDOWN 5699|| c == K_S_DOWN || c == K_UP || c == K_DOWN ); 5700} 5701 5702/// Decide the number of completions to move forward. 5703/// Returns 1 for most keys, height of the popup menu for page-up/down keys. 5704static int ins_compl_key2count (int c ) 5705{ 5706if (c == K_EVENT || c == K_COMMAND || c == K_LUA ) { 5707int offset = pum_want .item - compl_selected_item ; 5708return abs (offset ); 5709 } 5710 5711if (ins_compl_pum_key (c )&& c != K_UP && c != K_DOWN ) { 5712int h = pum_get_height (); 5713if (h > 3 ) { 5714h -= 2 ;// keep some context 5715 } 5716return h ; 5717 } 5718return 1 ; 5719} 5720 5721/// Check that completion with "c" should insert the match, false if only 5722/// to change the currently selected completion. 5723/// 5724/// @param c character to check 5725static bool ins_compl_use_match (int c ) 5726FUNC_ATTR_CONST FUNC_ATTR_WARN_UNUSED_RESULT 5727{ 5728switch (c ) { 5729case K_UP : 5730case K_DOWN : 5731case K_PAGEDOWN : 5732case K_KPAGEDOWN : 5733case K_S_DOWN : 5734case K_PAGEUP : 5735case K_KPAGEUP : 5736case K_S_UP : 5737return false; 5738case K_EVENT : 5739case K_COMMAND : 5740case K_LUA : 5741return pum_want .active && pum_want .insert ; 5742 } 5743return true; 5744} 5745 5746/// Get the pattern, column and length for normal completion (CTRL-N CTRL-P 5747/// completion) 5748/// Sets the global variables: compl_col, compl_length and compl_pattern. 5749/// Uses the global variables: compl_cont_status and ctrl_x_mode 5750static int get_normal_compl_info (char * line ,int startcol ,colnr_T curs_col ) 5751{ 5752if ((compl_cont_status & CONT_SOL )|| ctrl_x_mode_path_defines ()) { 5753if (!compl_status_adding ()) { 5754while (-- startcol >=0 && vim_isIDc ((uint8_t )line [startcol ])) {} 5755compl_col += ++ startcol ; 5756compl_length = curs_col - startcol ; 5757 } 5758if (p_ic ) { 5759compl_pattern = cstr_as_string (str_foldcase (line + compl_col , 5760compl_length ,NULL ,0 )); 5761 }else { 5762compl_pattern = cbuf_to_string (line + compl_col , (size_t )compl_length ); 5763 } 5764 }else if (compl_status_adding ()) { 5765char * prefix = "\\<" ; 5766size_t prefixlen = STRLEN_LITERAL ("\\<" ); 5767 5768if (!vim_iswordp (line + compl_col ) 5769|| (compl_col > 0 5770&& (vim_iswordp (mb_prevptr (line ,line + compl_col ))))) { 5771prefix = "" ; 5772prefixlen = 0 ; 5773 } 5774 5775// we need up to 2 extra chars for the prefix 5776size_t n = quote_meta (NULL ,line + compl_col ,compl_length )+ prefixlen ; 5777compl_pattern .data = xmalloc (n ); 5778STRCPY (compl_pattern .data ,prefix ); 5779quote_meta (compl_pattern .data + prefixlen ,line + compl_col ,compl_length ); 5780compl_pattern .size = n - 1 ; 5781 }else if (-- startcol < 0 5782|| !vim_iswordp (mb_prevptr (line ,line + startcol + 1 ))) { 5783// Match any word of at least two chars 5784compl_pattern = cbuf_to_string (S_LEN ("\\<\\k\\k" )); 5785compl_col += curs_col ; 5786compl_length = 0 ; 5787compl_from_nonkeyword = true; 5788 }else { 5789// Search the point of change class of multibyte character 5790// or not a word single byte character backward. 5791startcol -= utf_head_off (line ,line + startcol ); 5792int base_class = mb_get_class (line + startcol ); 5793while (-- startcol >=0 ) { 5794int head_off = utf_head_off (line ,line + startcol ); 5795if (base_class != mb_get_class (line + startcol - head_off )) { 5796break ; 5797 } 5798startcol -= head_off ; 5799 } 5800 5801compl_col += ++ startcol ; 5802compl_length = (int )curs_col - startcol ; 5803if (compl_length == 1 ) { 5804// Only match word with at least two chars -- webb 5805// there's no need to call quote_meta, 5806// xmalloc(7) is enough -- Acevedo 5807compl_pattern .data = xmalloc (7 ); 5808STRCPY (compl_pattern .data ,"\\<" ); 5809quote_meta (compl_pattern .data + 2 ,line + compl_col ,1 ); 5810strcat (compl_pattern .data ,"\\k" ); 5811compl_pattern .size = strlen (compl_pattern .data ); 5812 }else { 5813size_t n = quote_meta (NULL ,line + compl_col ,compl_length )+ 2 ; 5814compl_pattern .data = xmalloc (n ); 5815STRCPY (compl_pattern .data ,"\\<" ); 5816quote_meta (compl_pattern .data + 2 ,line + compl_col ,compl_length ); 5817compl_pattern .size = n - 1 ; 5818 } 5819 } 5820 5821// Call functions in 'complete' with 'findstart=1' 5822if (ctrl_x_mode_normal ()&& !(compl_cont_status & CONT_LOCAL )) { 5823// ^N completion, not complete() or ^X^N 5824setup_cpt_sources (); 5825prepare_cpt_compl_funcs (); 5826 } 5827 5828return OK ; 5829} 5830 5831/// Get the pattern, column and length for whole line completion or for the 5832/// complete() function. 5833/// Sets the global variables: compl_col, compl_length and compl_pattern. 5834static int get_wholeline_compl_info (char * line ,colnr_T curs_col ) 5835{ 5836compl_col = (colnr_T )getwhitecols (line ); 5837compl_length = (int )curs_col - (int )compl_col ; 5838if (compl_length < 0 ) {// cursor in indent: empty pattern 5839compl_length = 0 ; 5840 } 5841if (p_ic ) { 5842compl_pattern = cstr_as_string (str_foldcase (line + compl_col , 5843compl_length ,NULL ,0 )); 5844 }else { 5845compl_pattern = cbuf_to_string (line + compl_col , (size_t )compl_length ); 5846 } 5847 5848return OK ; 5849} 5850 5851/// Get the pattern, column and length for filename completion. 5852/// Sets the global variables: compl_col, compl_length and compl_pattern. 5853static int get_filename_compl_info (char * line ,int startcol ,colnr_T curs_col ) 5854{ 5855// Go back to just before the first filename character. 5856if (startcol > 0 ) { 5857char * p = line + startcol ; 5858 5859MB_PTR_BACK (line ,p ); 5860while (p > line && vim_isfilec (utf_ptr2char (p ))) { 5861MB_PTR_BACK (line ,p ); 5862 } 5863bool p_is_filec = false; 5864#ifdef MSWIN 5865// check for drive letters on mswin 5866if (p > line && path_has_drive_letter (p - 1 ,line + startcol - (p - 1 ))) { 5867p -= p == line + 1 ?1 :2 ; 5868p_is_filec = true; 5869 } 5870#endif 5871p_is_filec = p_is_filec || vim_isfilec (utf_ptr2char (p )); 5872 5873if (p == line && p_is_filec ) { 5874startcol = 0 ; 5875 }else { 5876startcol = (int )(p - line )+ 1 ; 5877 } 5878 } 5879 5880compl_col += startcol ; 5881compl_length = (int )curs_col - startcol ; 5882compl_pattern = cstr_as_string (addstar (line + compl_col , 5883 (size_t )compl_length ,EXPAND_FILES )); 5884 5885return OK ; 5886} 5887 5888/// Get the pattern, column and length for command-line completion. 5889/// Sets the global variables: compl_col, compl_length and compl_pattern. 5890static int get_cmdline_compl_info (char * line ,colnr_T curs_col ) 5891{ 5892compl_pattern = cbuf_to_string (line , (size_t )curs_col ); 5893set_cmd_context (& compl_xp ,compl_pattern .data , 5894 (int )compl_pattern .size ,curs_col , false); 5895if (compl_xp .xp_context == EXPAND_LUA ) { 5896nlua_expand_pat (& compl_xp ); 5897 } 5898if (compl_xp .xp_context == EXPAND_UNSUCCESSFUL 5899|| compl_xp .xp_context == EXPAND_NOTHING ) { 5900// No completion possible, use an empty pattern to get a 5901// "pattern not found" message. 5902compl_col = curs_col ; 5903 }else { 5904compl_col = (int )(compl_xp .xp_pattern - compl_pattern .data ); 5905 } 5906compl_length = curs_col - compl_col ; 5907 5908return OK ; 5909} 5910 5911/// Set global variables related to completion: 5912/// compl_col, compl_length, compl_pattern, and cpt_compl_pattern. 5913static void set_compl_globals (int startcol ,colnr_T curs_col ,bool is_cpt_compl ) 5914{ 5915if (is_cpt_compl ) { 5916API_CLEAR_STRING (cpt_compl_pattern ); 5917if (startcol < compl_col ) { 5918prepend_startcol_text (& cpt_compl_pattern ,& compl_orig_text ,startcol ); 5919return ; 5920 }else { 5921cpt_compl_pattern = copy_string (compl_orig_text ,NULL ); 5922 } 5923 }else { 5924if (startcol < 0 || startcol > curs_col ) { 5925startcol = curs_col ; 5926 } 5927 5928// Re-obtain line in case it has changed 5929char * line = ml_get (curwin -> w_cursor .lnum ); 5930int len = curs_col - startcol ; 5931 5932compl_pattern = cbuf_to_string (line + startcol , (size_t )len ); 5933compl_col = startcol ; 5934compl_length = len ; 5935 } 5936} 5937 5938/// Get the pattern, column and length for user defined completion ('omnifunc', 5939/// 'completefunc' and 'thesaurusfunc') 5940/// Uses the global variable: spell_bad_len 5941/// 5942/// @param cb set if triggered by a function in the 'cpt' option, otherwise NULL 5943/// @param startcol when not NULL, contains the column returned by function. 5944static int get_userdefined_compl_info (colnr_T curs_col ,Callback * cb ,int * startcol ) 5945{ 5946// Call user defined function 'completefunc' with "a:findstart" 5947// set to 1 to obtain the length of text to use for completion. 5948const int save_State = State ; 5949 5950const bool is_cpt_function = (cb != NULL ); 5951const bool use_sandbox = is_cpt_function && was_set_insecurely (curwin ,kOptComplete ,OPT_LOCAL ); 5952if (!is_cpt_function ) { 5953cb = get_insert_callback (ctrl_x_mode ); 5954if (cb -> type == kCallbackNone ) { 5955semsg (_ (e_notset ),ctrl_x_mode_function () ?"completefunc" :"omnifunc" ); 5956return FAIL ; 5957 } 5958 } 5959 5960typval_T args [3 ]; 5961args [0 ].v_type = VAR_NUMBER ; 5962args [1 ].v_type = VAR_STRING ; 5963args [2 ].v_type = VAR_UNKNOWN ; 5964args [0 ].vval .v_number = 1 ; 5965args [1 ].vval .v_string = "" ; 5966 5967pos_T pos = curwin -> w_cursor ; 5968textlock ++ ; 5969if (use_sandbox ) { 5970sandbox ++ ; 5971 } 5972colnr_T col = (colnr_T )callback_call_retnr (cb ,2 ,args ); 5973if (use_sandbox ) { 5974sandbox -- ; 5975 } 5976textlock -- ; 5977 5978State = save_State ; 5979curwin -> w_cursor = pos ;// restore the cursor position 5980check_cursor (curwin );// make sure cursor position is valid, just in case 5981validate_cursor (curwin ); 5982if (!equalpos (curwin -> w_cursor ,pos )) { 5983emsg (_ (e_compldel )); 5984return FAIL ; 5985 } 5986 5987if (startcol != NULL ) { 5988* startcol = col ; 5989 } 5990 5991// Return value -2 means the user complete function wants to cancel the 5992// complete without an error, do the same if the function did not execute 5993// successfully. 5994if (col == -2 || aborting ()) { 5995return FAIL ; 5996 } 5997 5998// Return value -3 does the same as -2 and leaves CTRL-X mode. 5999if (col == -3 ) { 6000if (is_cpt_function ) { 6001return FAIL ; 6002 } 6003ctrl_x_mode = CTRL_X_NORMAL ; 6004edit_submode = NULL ; 6005if (!shortmess (kShmCompletionmenu )) { 6006msg_clr_cmdline (); 6007 } 6008return FAIL ; 6009 } 6010 6011// Reset extended parameters of completion, when starting new 6012// completion. 6013compl_opt_refresh_always = false; 6014 6015if (!is_cpt_function ) { 6016set_compl_globals (col ,curs_col , false); 6017 } 6018return OK ; 6019} 6020 6021/// Get the pattern, column and length for spell completion. 6022/// Sets the global variables: compl_col, compl_length and compl_pattern. 6023/// Uses the global variable: spell_bad_len 6024static int get_spell_compl_info (int startcol ,colnr_T curs_col ) 6025{ 6026if (spell_bad_len > 0 ) { 6027assert (spell_bad_len <=INT_MAX ); 6028compl_col = curs_col - (int )spell_bad_len ; 6029 }else { 6030compl_col = spell_word_start (startcol ); 6031 } 6032if (compl_col >= (colnr_T )startcol ) { 6033compl_length = 0 ; 6034compl_col = curs_col ; 6035 }else { 6036spell_expand_check_cap (compl_col ); 6037compl_length = (int )curs_col - compl_col ; 6038 } 6039// Need to obtain "line" again, it may have become invalid. 6040char * line = ml_get (curwin -> w_cursor .lnum ); 6041compl_pattern = cbuf_to_string (line + compl_col , (size_t )compl_length ); 6042 6043return OK ; 6044} 6045 6046/// Get the completion pattern, column and length. 6047/// 6048/// @param startcol start column number of the completion pattern/text 6049/// @param cur_col current cursor column 6050/// 6051/// On return, "line_invalid" is set to true, if the current line may have 6052/// become invalid and needs to be fetched again. 6053/// 6054/// @return OK on success. 6055static int compl_get_info (char * line ,int startcol ,colnr_T curs_col ,bool * line_invalid ) 6056{ 6057if (ctrl_x_mode_normal ()|| ctrl_x_mode_register () 6058|| ((ctrl_x_mode & CTRL_X_WANT_IDENT ) 6059&& !thesaurus_func_complete (ctrl_x_mode ))) { 6060if (get_normal_compl_info (line ,startcol ,curs_col )!= OK ) { 6061return FAIL ; 6062 } 6063* line_invalid = true;// 'cpt' func may have invalidated "line" 6064 }else if (ctrl_x_mode_line_or_eval ()) { 6065return get_wholeline_compl_info (line ,curs_col ); 6066 }else if (ctrl_x_mode_files ()) { 6067return get_filename_compl_info (line ,startcol ,curs_col ); 6068 }else if (ctrl_x_mode == CTRL_X_CMDLINE ) { 6069return get_cmdline_compl_info (line ,curs_col ); 6070 }else if (ctrl_x_mode_function ()|| ctrl_x_mode_omni () 6071|| thesaurus_func_complete (ctrl_x_mode )) { 6072if (get_userdefined_compl_info (curs_col ,NULL ,NULL )!= OK ) { 6073return FAIL ; 6074 } 6075* line_invalid = true;// "line" may have become invalid 6076 }else if (ctrl_x_mode_spell ()) { 6077if (get_spell_compl_info (startcol ,curs_col )== FAIL ) { 6078return FAIL ; 6079 } 6080* line_invalid = true;// "line" may have become invalid 6081 }else { 6082internal_error ("ins_complete()" ); 6083return FAIL ; 6084 } 6085 6086return OK ; 6087} 6088 6089/// Continue an interrupted completion mode search in "line". 6090/// 6091/// If this same ctrl_x_mode has been interrupted use the text from 6092/// "compl_startpos" to the cursor as a pattern to add a new word instead of 6093/// expand the one before the cursor, in word-wise if "compl_startpos" is not in 6094/// the same line as the cursor then fix it (the line has been split because it 6095/// was longer than 'tw'). if SOL is set then skip the previous pattern, a word 6096/// at the beginning of the line has been inserted, we'll look for that. 6097static void ins_compl_continue_search (char * line ) 6098{ 6099// it is a continued search 6100compl_cont_status &= ~CONT_INTRPT ;// remove INTRPT 6101if (ctrl_x_mode_normal () 6102|| ctrl_x_mode_path_patterns () 6103|| ctrl_x_mode_path_defines ()) { 6104if (compl_startpos .lnum != curwin -> w_cursor .lnum ) { 6105// line (probably) wrapped, set compl_startpos to the 6106// first non_blank in the line, if it is not a wordchar 6107// include it to get a better pattern, but then we don't 6108// want the "\\<" prefix, check it below. 6109compl_col = (colnr_T )getwhitecols (line ); 6110compl_startpos .col = compl_col ; 6111compl_startpos .lnum = curwin -> w_cursor .lnum ; 6112compl_cont_status &= ~CONT_SOL ;// clear SOL if present 6113 }else { 6114// S_IPOS was set when we inserted a word that was at the 6115// beginning of the line, which means that we'll go to SOL 6116// mode but first we need to redefine compl_startpos 6117if (compl_cont_status & CONT_S_IPOS ) { 6118compl_cont_status |=CONT_SOL ; 6119compl_startpos .col = (colnr_T )(skipwhite (line + compl_length + compl_startpos .col )- line ); 6120 } 6121compl_col = compl_startpos .col ; 6122 } 6123compl_length = curwin -> w_cursor .col - (int )compl_col ; 6124// IObuff is used to add a "word from the next line" would we 6125// have enough space? just being paranoid 6126#define MIN_SPACE 75 6127if (compl_length > (IOSIZE - MIN_SPACE )) { 6128compl_cont_status &= ~CONT_SOL ; 6129compl_length = (IOSIZE - MIN_SPACE ); 6130compl_col = curwin -> w_cursor .col - compl_length ; 6131 } 6132compl_cont_status |=CONT_ADDING |CONT_N_ADDS ; 6133if (compl_length < 1 ) { 6134compl_cont_status &=CONT_LOCAL ; 6135 } 6136 }else if (ctrl_x_mode_line_or_eval ()|| ctrl_x_mode_register ()) { 6137compl_cont_status = CONT_ADDING |CONT_N_ADDS ; 6138 }else { 6139compl_cont_status = 0 ; 6140 } 6141} 6142 6143/// start insert mode completion 6144static int ins_compl_start (void ) 6145{ 6146const bool save_did_ai = Ins .did_ai ; 6147 6148// First time we hit ^N or ^P (in a row, I mean) 6149 6150Ins .did_ai = false; 6151Ins .did_si = false; 6152Ins .can_si = false; 6153Ins .can_si_back = false; 6154if (stop_arrow ()== FAIL ) { 6155Ins .did_ai = save_did_ai ; 6156return FAIL ; 6157 } 6158 6159char * line = ml_get (curwin -> w_cursor .lnum ); 6160colnr_T curs_col = curwin -> w_cursor .col ; 6161compl_pending = 0 ; 6162compl_lnum = curwin -> w_cursor .lnum ; 6163 6164if ((compl_cont_status & CONT_INTRPT )== CONT_INTRPT 6165&& compl_cont_mode == ctrl_x_mode ) { 6166// this same ctrl-x_mode was interrupted previously. Continue the 6167// completion. 6168ins_compl_continue_search (line ); 6169 }else { 6170compl_cont_status &=CONT_LOCAL ; 6171 } 6172 6173int startcol = 0 ;// column where searched text starts 6174if (!compl_status_adding ()) {// normal expansion 6175compl_cont_mode = ctrl_x_mode ; 6176if (ctrl_x_mode_not_default ()) { 6177// Remove LOCAL if ctrl_x_mode != CTRL_X_NORMAL 6178compl_cont_status = 0 ; 6179 } 6180compl_cont_status |=CONT_N_ADDS ; 6181compl_startpos = curwin -> w_cursor ; 6182startcol = (int )curs_col ; 6183compl_col = 0 ; 6184 } 6185 6186// Work out completion pattern and original text -- webb 6187bool line_invalid = false; 6188if (compl_get_info (line ,startcol ,curs_col ,& line_invalid )== FAIL ) { 6189if (ctrl_x_mode_function ()|| ctrl_x_mode_omni () 6190|| thesaurus_func_complete (ctrl_x_mode )) { 6191// restore Ins.did_ai, so that adding comment leader works 6192Ins .did_ai = save_did_ai ; 6193 } 6194return FAIL ; 6195 } 6196// If "line" was changed while getting completion info get it again. 6197if (line_invalid ) { 6198line = ml_get (curwin -> w_cursor .lnum ); 6199 } 6200 6201if (compl_status_adding ()) { 6202if (!shortmess (kShmCompletionmenu )) { 6203edit_submode_pre = _ (" Adding" ); 6204 } 6205if (ctrl_x_mode_line_or_eval ()) { 6206// Insert a new line, keep indentation but ignore 'comments'. 6207char * old = curbuf -> b_p_com ; 6208 6209curbuf -> b_p_com = "" ; 6210compl_startpos .lnum = curwin -> w_cursor .lnum ; 6211compl_startpos .col = compl_col ; 6212ins_eol ('\r' ); 6213curbuf -> b_p_com = old ; 6214compl_length = 0 ; 6215compl_col = curwin -> w_cursor .col ; 6216compl_lnum = curwin -> w_cursor .lnum ; 6217 } 6218 }else { 6219edit_submode_pre = NULL ; 6220compl_startpos .col = compl_col ; 6221 } 6222 6223if (!shortmess (kShmCompletionmenu )&& !compl_autocomplete ) { 6224if (compl_cont_status & CONT_LOCAL ) { 6225edit_submode = _ (ctrl_x_msgs [CTRL_X_LOCAL_MSG ]); 6226 }else { 6227edit_submode = _ (CTRL_X_MSG (ctrl_x_mode )); 6228 } 6229 } 6230 6231// If any of the original typed text has been changed we need to fix 6232// the redo buffer. 6233ins_compl_fixRedoBufForLeader (NULL ); 6234 6235// Always add completion for the original text. 6236API_CLEAR_STRING (compl_orig_text ); 6237kv_destroy (compl_orig_extmarks ); 6238compl_orig_text = cbuf_to_string (line + compl_col , (size_t )compl_length ); 6239save_orig_extmarks (); 6240int flags = CP_ORIGINAL_TEXT ; 6241if (p_ic ) { 6242flags |=CP_ICASE ; 6243 } 6244if (ins_compl_add (compl_orig_text .data , (int )compl_orig_text .size , 6245NULL ,NULL , false,NULL ,0 , 6246flags , false,NULL ,FUZZY_SCORE_NONE , false,NULL )!= OK ) { 6247API_CLEAR_STRING (compl_pattern ); 6248API_CLEAR_STRING (compl_orig_text ); 6249kv_destroy (compl_orig_extmarks ); 6250Ins .did_ai = save_did_ai ; 6251return FAIL ; 6252 } 6253 6254// showmode might reset the internal line pointers, so it must 6255// be called before line = ml_get(), or when this address is no 6256// longer needed. -- Acevedo. 6257if (!shortmess (kShmCompletionmenu )&& !compl_autocomplete ) { 6258edit_submode_extra = _ ("-- Searching..." ); 6259edit_submode_highl = HLF_COUNT ; 6260showmode (); 6261edit_submode_extra = NULL ; 6262ui_flush (); 6263 } 6264 6265Ins .did_ai = save_did_ai ; 6266return OK ; 6267} 6268 6269/// display the completion status message 6270static void ins_compl_show_statusmsg (void ) 6271{ 6272// we found no match if the list has only the "compl_orig_text"-entry 6273if (is_first_match (compl_first_match -> cp_next )) { 6274edit_submode_extra = compl_status_adding ()&& compl_length > 1 6275 ?_ ("Hit end of paragraph" ) :_ ("Pattern not found" ); 6276edit_submode_highl = HLF_E ; 6277 } 6278 6279if (edit_submode_extra == NULL ) { 6280if (match_at_original_text (compl_curr_match )) { 6281edit_submode_extra = _ ("Back at original" ); 6282edit_submode_highl = HLF_W ; 6283 }else if (compl_cont_status & CONT_S_IPOS ) { 6284edit_submode_extra = _ ("Word from other line" ); 6285edit_submode_highl = HLF_COUNT ; 6286 }else if (compl_curr_match -> cp_next == compl_curr_match -> cp_prev ) { 6287edit_submode_extra = _ ("The only match" ); 6288edit_submode_highl = HLF_COUNT ; 6289compl_curr_match -> cp_number = 1 ; 6290 }else { 6291// Update completion sequence number when needed. 6292if (compl_curr_match -> cp_number == -1 ) { 6293ins_compl_update_sequence_numbers (); 6294 } 6295 6296// The match should always have a sequence number now, this is 6297// just a safety check. 6298if (compl_curr_match -> cp_number != -1 ) { 6299// Space for 10 text chars. + 2x10-digit no.s = 31. 6300// Translations may need more than twice that. 6301static char match_ref [81 ]; 6302 6303if (compl_matches > 0 ) { 6304vim_snprintf (match_ref ,sizeof (match_ref ), 6305_ ("match %d of %d" ), 6306compl_curr_match -> cp_number ,compl_matches ); 6307 }else { 6308vim_snprintf (match_ref ,sizeof (match_ref ), 6309_ ("match %d" ), 6310compl_curr_match -> cp_number ); 6311 } 6312edit_submode_extra = match_ref ; 6313edit_submode_highl = HLF_R ; 6314if (dollar_vcol >=0 ) { 6315curs_columns (curwin , false); 6316 } 6317 } 6318 } 6319 } 6320 6321// Show a message about what (completion) mode we're in. 6322redraw_mode = true; 6323if (!shortmess (kShmCompletionmenu )) { 6324if (edit_submode_extra != NULL ) { 6325if (!p_smd ) { 6326msg_hist_off = true; 6327msg_ext_set_kind ("completion" ); 6328msg (edit_submode_extra , (edit_submode_highl < HLF_COUNT 6329 ? (int )edit_submode_highl + 1 :0 )); 6330msg_hist_off = false; 6331 } 6332 }else { 6333msg_clr_cmdline ();// necessary for "noshowmode" 6334 } 6335 } 6336} 6337 6338/// Do Insert mode completion. 6339/// Called when character "c" was typed, which has a meaning for completion. 6340/// Returns OK if completion was done, FAIL if something failed. 6341int ins_complete (int c ,bool enable_pum ) 6342{ 6343compl_direction = ins_compl_key2dir (c ); 6344int insert_match = ins_compl_use_match (c ); 6345 6346if (!compl_started ) { 6347// Only what the automatic trigger armed counts as started by Vim. 6348compl_autostarted = compl_autostart_pending ; 6349compl_autostart_pending = false; 6350if (ins_compl_start ()== FAIL ) { 6351return FAIL ; 6352 } 6353 }else if (insert_match && stop_arrow ()== FAIL ) { 6354return FAIL ; 6355 } 6356 6357compl_curr_win = curwin ; 6358compl_curr_buf = curwin -> w_buffer ; 6359compl_shown_match = compl_curr_match ; 6360compl_shows_dir = compl_direction ; 6361compl_num_bests = 0 ; 6362 6363// Find next match (and following matches). 6364int save_w_wrow = curwin -> w_wrow ; 6365int save_w_leftcol = curwin -> w_leftcol ; 6366int n = ins_compl_next (true,ins_compl_key2count (c ),insert_match ); 6367 6368// Reset autocompletion timer expiry flag 6369if (compl_autocomplete ) { 6370compl_time_slice_expired = false; 6371 } 6372 6373if (n > 1 ) {// all matches have been found 6374compl_matches = n ; 6375 } 6376compl_curr_match = compl_shown_match ; 6377compl_direction = compl_shows_dir ; 6378 6379// Eat the ESC that vgetc() returns after a CTRL-C to avoid leaving Insert 6380// mode. 6381if (got_int && !global_busy ) { 6382vgetc (); 6383got_int = false; 6384 } 6385 6386// we found no match if the list has only the "compl_orig_text"-entry 6387bool no_matches_found = is_first_match (compl_first_match -> cp_next ); 6388if (no_matches_found ) { 6389// remove N_ADDS flag, so next ^X<> won't try to go to ADDING mode, 6390// because we couldn't expand anything at first place, but if we used 6391// ^P, ^N, ^X^I or ^X^D we might want to add-expand a single-char-word 6392// (such as M in M'exico) if not tried already. -- Acevedo 6393if (compl_length > 1 6394|| compl_status_adding () 6395|| (ctrl_x_mode_not_default () 6396&& !ctrl_x_mode_path_patterns () 6397&& !ctrl_x_mode_path_defines ())) { 6398compl_cont_status &= ~CONT_N_ADDS ; 6399 } 6400 } 6401 6402if (compl_curr_match -> cp_flags & CP_CONT_S_IPOS ) { 6403compl_cont_status |=CONT_S_IPOS ; 6404 }else { 6405compl_cont_status &= ~CONT_S_IPOS ; 6406 } 6407 6408if (!shortmess (kShmCompletionmenu )&& !compl_autocomplete ) { 6409ins_compl_show_statusmsg (); 6410 } 6411 6412if (!shortmess (kShmCompletionscan )&& !compl_autocomplete ) { 6413// End the "Scanning..." progress-msg. ins_compl_show_statusmsg() already reported the result. 6414msg_progress (NULL ,"nvim.completion" ,"success" ,0 , false, false, false); 6415 } 6416 6417// Show the popup menu, unless we got interrupted. 6418if (enable_pum && !compl_interrupted ) { 6419show_pum (save_w_wrow ,save_w_leftcol ); 6420 } 6421compl_was_interrupted = compl_interrupted ; 6422compl_interrupted = false; 6423 6424return OK ; 6425} 6426 6427/// Enable autocompletion 6428void ins_compl_enable_autocomplete (void ) 6429{ 6430compl_autocomplete = true; 6431compl_get_longest = false; 6432} 6433 6434/// Disable autocompletion 6435void ins_compl_disable_autocomplete (void ) 6436{ 6437compl_autocomplete = false; 6438} 6439 6440/// Remember that Vim is about to start a completion by itself, rather than 6441/// because a key was typed to ask for one. 6442void ins_compl_arm_autostart (void ) 6443{ 6444compl_autostart_pending = true; 6445} 6446 6447/// Forget what the automatic trigger armed, another key was typed since. 6448void ins_compl_disarm_autostart (void ) 6449{ 6450compl_autostart_pending = false; 6451} 6452 6453/// Arm the 'autocompletedelay' timer when the delay is in effect. 6454/// Return true when the popup should be deferred, false to trigger it now. 6455bool ins_compl_arm_autocomplete_delay (void ) 6456{ 6457if (p_acl > 0 ) { 6458compl_autocomplete_start_tv = os_hrtime (); 6459compl_autocomplete_pending = true; 6460return true; 6461 } 6462return false; 6463} 6464 6465/// Clear the pending 'autocompletedelay' state. 6466void ins_compl_clear_autocomplete_delay (void ) 6467{ 6468compl_autocomplete_pending = false; 6469} 6470 6471/// Return true while waiting for 'autocompletedelay' to expire. 6472bool ins_compl_autocomplete_pending (void ) 6473{ 6474return compl_autocomplete_pending ; 6475} 6476 6477/// Return the time in msec since the 'autocompletedelay' was armed. 6478int64_t ins_compl_autocomplete_elapsed (void ) 6479{ 6480return (int64_t )((os_hrtime ()- compl_autocomplete_start_tv ) /1000000 ); 6481} 6482 6483/// Remove (if needed) and show the popup menu 6484static void show_pum (int prev_w_wrow ,int prev_w_leftcol ) 6485{ 6486// RedrawingDisabled may be set when invoked through complete(). 6487int n = RedrawingDisabled ; 6488RedrawingDisabled = 0 ; 6489 6490// If the cursor moved or the display scrolled we need to remove the pum 6491// first. 6492setcursor (); 6493if (prev_w_wrow != curwin -> w_wrow || prev_w_leftcol != curwin -> w_leftcol ) { 6494ins_compl_del_pum (); 6495 } 6496 6497ins_compl_show_pum (); 6498setcursor (); 6499RedrawingDisabled = n ; 6500} 6501 6502// Looks in the first "len" chars. of "src" for search-metachars. 6503// If dest is not NULL the chars. are copied there quoting (with 6504// a backslash) the metachars, and dest would be NUL terminated. 6505// Returns the length (needed) of dest 6506static unsigned quote_meta (char * dest ,char * src ,int len ) 6507{ 6508unsigned m = (unsigned )len + 1 ;// one extra for the NUL 6509 6510for (;-- len >=0 ;src ++ ) { 6511switch (* src ) { 6512case '.' : 6513case '*' : 6514case '[' : 6515if (ctrl_x_mode_dictionary ()|| ctrl_x_mode_thesaurus ()) { 6516break ; 6517 } 6518FALLTHROUGH ; 6519case '~' : 6520if (!p_magic ) {// quote these only if magic is set 6521break ; 6522 } 6523FALLTHROUGH ; 6524case '\\' : 6525if (ctrl_x_mode_dictionary ()|| ctrl_x_mode_thesaurus ()) { 6526break ; 6527 } 6528FALLTHROUGH ; 6529case '^' :// currently it's not needed. 6530case '$' : 6531m ++ ; 6532if (dest != NULL ) { 6533* dest ++ = '\\' ; 6534 } 6535break ; 6536 } 6537if (dest != NULL ) { 6538* dest ++ = * src ; 6539 } 6540// Copy remaining bytes of a multibyte character. 6541const int mb_len = utfc_ptr2len (src )- 1 ; 6542if (mb_len > 0 && len >=mb_len ) { 6543for (int i = 0 ;i < mb_len ;i ++ ) { 6544len -- ; 6545src ++ ; 6546if (dest != NULL ) { 6547* dest ++ = * src ; 6548 } 6549 } 6550 } 6551 } 6552if (dest != NULL ) { 6553* dest = NUL ; 6554 } 6555 6556return m ; 6557} 6558 6559#ifdef EXITFREE 6560void free_insexpand_stuff (void ) 6561{ 6562API_CLEAR_STRING (compl_orig_text ); 6563kv_destroy (compl_orig_extmarks ); 6564callback_free (& p_cfu ); 6565callback_free (& p_ofu ); 6566callback_free (& p_tsrfu ); 6567clear_cpt_callbacks (& cpt_cb ,cpt_cb_count ); 6568} 6569#endif 6570 6571/// Called when starting CTRL_X_SPELL mode: Move backwards to a previous badly 6572/// spelled word, if there is one. 6573static void spell_back_to_badword (void ) 6574{ 6575pos_T tpos = curwin -> w_cursor ; 6576spell_bad_len = spell_move_to (curwin ,BACKWARD ,SMT_ALL , true,NULL ); 6577if (curwin -> w_cursor .col != tpos .col ) { 6578start_arrow (& tpos , true,NUL ); 6579 } 6580} 6581 6582/// Reset the info associated with completion sources. 6583static void cpt_sources_clear (void ) 6584{ 6585XFREE_CLEAR (cpt_sources_array ); 6586cpt_sources_index = -1 ; 6587cpt_sources_count = 0 ; 6588} 6589 6590/// Setup completion sources. 6591static void setup_cpt_sources (void ) 6592{ 6593cpt_sources_clear (); 6594 6595int count = get_cpt_sources_count (curbuf -> b_p_cpt ); 6596if (count == 0 ) { 6597return ; 6598 } 6599 6600cpt_sources_array = xcalloc ((size_t )count ,sizeof (cpt_source_T )); 6601 6602char buf [LSIZE ]; 6603int idx = 0 ; 6604for (char * p = curbuf -> b_p_cpt ;* p ;) { 6605while (* p == ',' || * p == ' ' ) {// Skip delimiters 6606p ++ ; 6607 } 6608if (* p ) {// If not end of string, count this segment 6609cpt_sources_array [idx ].cs_flag = * p ; 6610memset (buf ,0 ,LSIZE ); 6611size_t slen = copy_option_part (& p ,buf ,LSIZE ,"," );// Advance p 6612if (slen > 0 ) { 6613char * caret = vim_strchr (buf ,'^' ); 6614if (caret != NULL ) { 6615cpt_sources_array [idx ].cs_max_matches = atoi (caret + 1 ); 6616 } 6617 } 6618idx ++ ; 6619 } 6620 } 6621 6622cpt_sources_count = count ; 6623} 6624 6625/// Return true if any of the completion sources have 'refresh' set to 'always'. 6626static bool is_cpt_func_refresh_always (void ) 6627{ 6628for (int i = 0 ;i < cpt_sources_count ;i ++ ) { 6629if (cpt_sources_array [i ].cs_refresh_always ) { 6630return true; 6631 } 6632 } 6633return false; 6634} 6635 6636/// Make the completion list non-cyclic. 6637static void ins_compl_make_linear (void ) 6638{ 6639if (compl_first_match == NULL || compl_first_match -> cp_prev == NULL ) { 6640return ; 6641 } 6642compl_T * m = compl_first_match -> cp_prev ; 6643m -> cp_next = NULL ; 6644compl_first_match -> cp_prev = NULL ; 6645} 6646 6647/// Remove the matches linked to the current completion source (as indicated by 6648/// cpt_sources_index) from the completion list. 6649static void remove_old_matches (void ) 6650{ 6651bool shown_match_removed = false; 6652bool forward = (compl_first_match -> cp_cpt_source_idx < 0 ); 6653 6654if (cpt_sources_index < 0 ) { 6655return ; 6656 } 6657 6658compl_direction = forward ?FORWARD :BACKWARD ; 6659compl_shows_dir = compl_direction ; 6660 6661// When 'fuzzy' is enabled, items are not ordered by their original source 6662// order (cpt_sources_index). So, remove items one by one. 6663for (compl_T * current = compl_first_match ;current != NULL ;) { 6664if (current -> cp_cpt_source_idx == cpt_sources_index ) { 6665compl_T * to_delete = current ; 6666 6667if (!shown_match_removed && compl_shown_match == current ) { 6668shown_match_removed = true; 6669 } 6670 6671// Avoid dangling pointer when preselect match is removed. 6672if (to_delete == compl_preselect_match ) { 6673compl_preselect_match = NULL ; 6674 } 6675 6676current = current -> cp_next ; 6677 6678if (to_delete == compl_first_match ) {// node to remove is at head 6679compl_first_match = to_delete -> cp_next ; 6680compl_first_match -> cp_prev = NULL ; 6681 }else if (to_delete -> cp_next == NULL ) {// node to remove is at tail 6682to_delete -> cp_prev -> cp_next = NULL ; 6683 }else {// node is in the moddle 6684to_delete -> cp_prev -> cp_next = to_delete -> cp_next ; 6685to_delete -> cp_next -> cp_prev = to_delete -> cp_prev ; 6686 } 6687ins_compl_item_free (to_delete ); 6688 }else { 6689current = current -> cp_next ; 6690 } 6691 } 6692 6693// Re-assign compl_shown_match if necessary 6694if (shown_match_removed ) { 6695if (forward ) { 6696compl_shown_match = compl_first_match ; 6697 }else {// Last node will have the prefix that is being completed 6698compl_T * current ; 6699for (current = compl_first_match ;current -> cp_next != NULL ; 6700current = current -> cp_next ) {} 6701compl_shown_match = current ; 6702 } 6703 } 6704 6705// Re-assign compl_curr_match 6706compl_curr_match = compl_first_match ; 6707for (compl_T * current = compl_first_match ;current != NULL ;) { 6708if ((forward ?current -> cp_cpt_source_idx < cpt_sources_index 6709 :current -> cp_cpt_source_idx > cpt_sources_index )) { 6710compl_curr_match = forward ?current :current -> cp_next ; 6711current = current -> cp_next ; 6712 }else { 6713break ; 6714 } 6715 } 6716} 6717 6718/// Retrieve completion matches using the callback function "cb" and store the 6719/// 'refresh:always' flag. 6720static void get_cpt_func_completion_matches (Callback * cb ) 6721{ 6722cpt_source_T * cpt_src = & cpt_sources_array [cpt_sources_index ]; 6723int startcol = cpt_src -> cs_startcol ; 6724 6725if (startcol == -2 || startcol == -3 ) { 6726return ; 6727 } 6728 6729set_compl_globals (startcol ,curwin -> w_cursor .col , true); 6730 6731// Insert the leader string (previously removed) before expansion. 6732// This prevents flicker when `func` (e.g. an LSP client) is slow and 6733// calls 'sleep', which triggers ui_flush(). 6734if (!cpt_src -> cs_refresh_always ) { 6735ins_compl_insert_bytes (ins_compl_leader (),-1 ); 6736 } 6737 6738expand_by_function (0 ,cpt_compl_pattern .data ,cb ); 6739 6740if (!cpt_src -> cs_refresh_always ) { 6741ins_compl_delete (false); 6742 } 6743 6744cpt_src -> cs_refresh_always = compl_opt_refresh_always ; 6745compl_opt_refresh_always = false; 6746} 6747 6748/// Retrieve completion matches from functions in the 'cpt' option where the 6749/// 'refresh:always' flag is set. 6750static void cpt_compl_refresh (void ) 6751{ 6752// Make the completion list linear (non-cyclic) 6753ins_compl_make_linear (); 6754// Make a copy of 'cpt' in case the buffer gets wiped out 6755char * cpt = xstrdup (curbuf -> b_p_cpt ); 6756strip_caret_numbers_in_place (cpt ); 6757 6758cpt_sources_index = 0 ; 6759for (char * p = cpt ;* p ;) { 6760while (* p == ',' || * p == ' ' ) {// Skip delimiters 6761p ++ ; 6762 } 6763if (* p == NUL ) { 6764break ; 6765 } 6766 6767if (cpt_sources_array [cpt_sources_index ].cs_refresh_always ) { 6768Callback * cb = get_callback_if_cpt_func (p ,cpt_sources_index ); 6769if (cb ) { 6770remove_old_matches (); 6771int startcol ; 6772int ret = get_userdefined_compl_info (curwin -> w_cursor .col ,cb ,& startcol ); 6773if (ret == FAIL ) { 6774if (startcol == -3 ) { 6775cpt_sources_array [cpt_sources_index ].cs_refresh_always = false; 6776 }else { 6777startcol = -2 ; 6778 } 6779 }else if (startcol < 0 || startcol > curwin -> w_cursor .col ) { 6780startcol = curwin -> w_cursor .col ; 6781 } 6782cpt_sources_array [cpt_sources_index ].cs_startcol = startcol ; 6783if (ret == OK ) { 6784compl_source_start_timer (cpt_sources_index ); 6785get_cpt_func_completion_matches (cb ); 6786 } 6787 } 6788 } 6789 6790 (void )copy_option_part (& p ,IObuff ,IOSIZE ,"," );// Advance p 6791if (may_advance_cpt_index (p )) { 6792 (void )advance_cpt_sources_index_safe (); 6793 } 6794 } 6795cpt_sources_index = -1 ; 6796 6797xfree (cpt ); 6798// Make the list cyclic 6799compl_matches = ins_compl_make_cyclic (); 6800} 6801 6802/// "preinserted()" function 6803void f_preinserted (typval_T * argvars ,typval_T * rettv ,EvalFuncData fptr ) 6804{ 6805if (ins_compl_preinsert_effect ()) { 6806rettv -> vval .v_number = 1 ; 6807 } 6808}