robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// cmdexpand.c: functions for command-line completion 2 3#include <assert.h> 4#include <stdbool.h> 5#include <stdint.h> 6#include <stdio.h> 7#include <stdlib.h> 8#include <string.h> 9#include <uv.h> 10 11#include "nvim/api/private/defs.h" 12#include "nvim/api/private/helpers.h" 13#include "nvim/arglist.h" 14#include "nvim/ascii_defs.h" 15#include "nvim/autocmd.h" 16#include "nvim/buffer.h" 17#include "nvim/buffer_defs.h" 18#include "nvim/charset.h" 19#include "nvim/cmdexpand.h" 20#include "nvim/cmdhist.h" 21#include "nvim/drawscreen.h" 22#include "nvim/errors.h" 23#include "nvim/eval.h" 24#include "nvim/eval/funcs.h" 25#include "nvim/eval/typval.h" 26#include "nvim/eval/typval_defs.h" 27#include "nvim/eval/userfunc.h" 28#include "nvim/eval/vars.h" 29#include "nvim/ex_cmds.h" 30#include "nvim/ex_cmds_defs.h" 31#include "nvim/ex_docmd.h" 32#include "nvim/ex_getln.h" 33#include "nvim/fuzzy.h" 34#include "nvim/garray.h" 35#include "nvim/garray_defs.h" 36#include "nvim/gettext_defs.h" 37#include "nvim/globals.h" 38#include "nvim/grid.h" 39#include "nvim/hashtab.h" 40#include "nvim/hashtab_defs.h" 41#include "nvim/help.h" 42#include "nvim/highlight.h" 43#include "nvim/highlight_defs.h" 44#include "nvim/highlight_group.h" 45#include "nvim/input.h" 46#include "nvim/insexpand.h" 47#include "nvim/keycodes.h" 48#include "nvim/lua/executor.h" 49#include "nvim/macros_defs.h" 50#include "nvim/mapping.h" 51#include "nvim/mbyte.h" 52#include "nvim/mbyte_defs.h" 53#include "nvim/memline.h" 54#include "nvim/memory.h" 55#include "nvim/menu.h" 56#include "nvim/message.h" 57#include "nvim/option.h" 58#include "nvim/option_vars.h" 59#include "nvim/os/fs.h" 60#include "nvim/os/lang.h" 61#include "nvim/os/os.h" 62#include "nvim/os/os_defs.h" 63#include "nvim/path.h" 64#include "nvim/popupmenu.h" 65#include "nvim/profile.h" 66#include "nvim/regexp.h" 67#include "nvim/runtime.h" 68#include "nvim/runtime_defs.h" 69#include "nvim/search.h" 70#include "nvim/sign.h" 71#include "nvim/statusline.h" 72#include "nvim/strings.h" 73#include "nvim/syntax.h" 74#include "nvim/tag.h" 75#include "nvim/types_defs.h" 76#include "nvim/ui.h" 77#include "nvim/ui_defs.h" 78#include "nvim/usercmd.h" 79#include "nvim/vim_defs.h" 80#include "nvim/window.h" 81 82/// Type used by call_user_expand_func 83typedef void * (* user_expand_func_T )(const char * ,int ,typval_T * ); 84 85#include "cmdexpand.c.generated.h" 86 87static bool cmd_showtail ;///< Only show path tail in lists ? 88static bool may_expand_pattern = false; 89static pos_T pre_incsearch_pos ;///< Cursor position when incsearch started 90 91/// "compl_match_array" points the currently displayed list of entries in the 92/// popup menu. It is NULL when there is no popup menu. 93static pumitem_T * compl_match_array = NULL ; 94static int compl_match_arraysize ; 95/// First column in cmdline of the matched item for completion. 96static int compl_startcol ; 97static int compl_selected ; 98/// cmdline before expansion 99static String cmdline_orig = STRING_INIT ; 100 101#define SHOW_MATCH (m ) (showtail ? showmatches_gettail(matches[m], false) : matches[m]) 102 103/// Returns true if fuzzy completion is supported for a given cmdline completion 104/// context. 105static bool cmdline_fuzzy_completion_supported (const expand_T * const xp ) 106FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 107{ 108switch (xp -> xp_context ) { 109case EXPAND_BOOL_SETTINGS : 110case EXPAND_COLORS : 111case EXPAND_COMPILER : 112case EXPAND_DIRECTORIES : 113case EXPAND_DIRS_IN_CDPATH : 114case EXPAND_FILES : 115case EXPAND_FILES_IN_PATH : 116case EXPAND_FILETYPE : 117case EXPAND_FILETYPECMD : 118case EXPAND_FINDFUNC : 119case EXPAND_HELP : 120case EXPAND_KEYMAP : 121case EXPAND_LUA : 122case EXPAND_OLD_SETTING : 123case EXPAND_STRING_SETTING : 124case EXPAND_SETTING_SUBTRACT : 125case EXPAND_OWNSYNTAX : 126case EXPAND_PACKADD : 127case EXPAND_RUNTIME : 128case EXPAND_SHELLCMD : 129case EXPAND_SHELLCMDLINE : 130case EXPAND_TAGS : 131case EXPAND_TAGS_LISTFILES : 132case EXPAND_USER_LIST : 133case EXPAND_USER_LUA : 134return false; 135 136default : 137break ; 138 } 139 140return wop_flags & kOptWopFlagFuzzy ; 141} 142 143/// Returns true if fuzzy completion for cmdline completion is enabled and 144/// "fuzzystr" is not empty. If search pattern is empty, then don't use fuzzy 145/// matching. 146bool cmdline_fuzzy_complete (const char * const fuzzystr ) 147FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE 148{ 149return (wop_flags & kOptWopFlagFuzzy )&& * fuzzystr != NUL ; 150} 151 152/// Sort function for the completion matches. 153/// <SNR> functions should be sorted to the end. 154static int sort_func_compare (const void * s1 ,const void * s2 ) 155{ 156char * p1 = * (char ** )s1 ; 157char * p2 = * (char ** )s2 ; 158 159if (* p1 != '<' && * p2 == '<' ) { 160return -1 ; 161 } 162if (* p1 == '<' && * p2 != '<' ) { 163return 1 ; 164 } 165return strcmp (p1 ,p2 ); 166} 167 168/// Escape special characters in the cmdline completion matches. 169static void wildescape (expand_T * xp ,const char * str ,int numfiles ,char ** files ) 170{ 171char * p ; 172const int vse_what = xp -> xp_context == EXPAND_BUFFERS ?VSE_BUFFER :VSE_NONE ; 173 174if (xp -> xp_context == EXPAND_FILES 175|| xp -> xp_context == EXPAND_FILES_IN_PATH 176|| xp -> xp_context == EXPAND_SHELLCMD 177|| xp -> xp_context == EXPAND_BUFFERS 178|| xp -> xp_context == EXPAND_DIRECTORIES 179|| xp -> xp_context == EXPAND_DIRS_IN_CDPATH ) { 180// Insert a backslash into a file name before a space, \, %, # 181// and wildmatch characters, except '~'. 182for (int i = 0 ;i < numfiles ;i ++ ) { 183// for ":set path=" we need to escape spaces twice 184if (xp -> xp_backslash & XP_BS_THREE ) { 185char * pat = (xp -> xp_backslash & XP_BS_COMMA ) ?" ," :" " ; 186p = vim_strsave_escaped (files [i ],pat ); 187xfree (files [i ]); 188files [i ]= p ; 189#ifdef BACKSLASH_IN_FILENAME 190p = vim_strsave_escaped (files [i ]," " ); 191xfree (files [i ]); 192files [i ]= p ; 193#endif 194 }else if (xp -> xp_backslash & XP_BS_COMMA ) { 195if (vim_strchr (files [i ],',' )!= NULL ) { 196p = vim_strsave_escaped (files [i ],"," ); 197xfree (files [i ]); 198files [i ]= p ; 199 } 200 } 201#ifdef BACKSLASH_IN_FILENAME 202p = vim_strsave_fnameescape (files [i ],vse_what ); 203#else 204p = vim_strsave_fnameescape (files [i ],xp -> xp_shell ?VSE_SHELL :vse_what ); 205#endif 206xfree (files [i ]); 207files [i ]= p ; 208 209// If 'str' starts with "\~", replace "~" at start of 210// files[i] with "\~". 211if (str [0 ]== '\\' && str [1 ]== '~' && files [i ][0 ]== '~' ) { 212escape_fname (& files [i ]); 213 } 214 } 215xp -> xp_backslash = XP_BS_NONE ; 216 217// If the first file starts with a '+' escape it. Otherwise it 218// could be seen as "+cmd". 219if (* files [0 ]== '+' ) { 220escape_fname (& files [0 ]); 221 } 222 }else if (xp -> xp_context == EXPAND_TAGS ) { 223// Insert a backslash before characters in a tag name that 224// would terminate the ":tag" command. 225for (int i = 0 ;i < numfiles ;i ++ ) { 226p = vim_strsave_escaped (files [i ],"\\|\"" ); 227xfree (files [i ]); 228files [i ]= p ; 229 } 230 } 231} 232 233/// Escape special characters in the cmdline completion matches. 234static void ExpandEscape (expand_T * xp ,char * str ,int numfiles ,char ** files ,int options ) 235{ 236// May change home directory back to "~" 237if (options & WILD_HOME_REPLACE ) { 238tilde_replace (str ,numfiles ,files ); 239 } 240 241if (options & WILD_ESCAPE ) { 242wildescape (xp ,str ,numfiles ,files ); 243 } 244} 245 246/// Return FAIL if this is not an appropriate context in which to do 247/// completion of anything, return OK if it is (even if there are no matches). 248/// For the caller, this means that the character is just passed through like a 249/// normal character (instead of being expanded). This allows :s/^I^D etc. 250/// 251/// @param options extra options for ExpandOne() 252/// @param escape if true, escape the returned matches 253int nextwild (expand_T * xp ,int type ,int options ,bool escape ) 254{ 255CmdlineInfo * const ccline = get_cmdline_info (); 256char * p ; 257bool from_wildtrigger_func = options & WILD_FUNC_TRIGGER ; 258bool wild_navigate = (type == WILD_NEXT || type == WILD_PREV 259|| type == WILD_PAGEUP || type == WILD_PAGEDOWN 260|| type == WILD_PUM_WANT ); 261 262if (xp -> xp_numfiles == -1 ) { 263pre_incsearch_pos = xp -> xp_pre_incsearch_pos ; 264if (ccline -> input_fn && ccline -> xp_context == EXPAND_COMMANDS ) { 265// Expand commands typed in input() function 266set_cmd_context (xp ,ccline -> cmdbuff ,ccline -> cmdlen ,ccline -> cmdpos , false); 267 }else { 268may_expand_pattern = options & WILD_MAY_EXPAND_PATTERN ; 269set_expand_context (xp ); 270may_expand_pattern = false; 271 } 272if (xp -> xp_context == EXPAND_LUA ) { 273nlua_expand_pat (xp ); 274 } 275cmd_showtail = expand_showtail (xp ); 276 } 277 278if (xp -> xp_context == EXPAND_UNSUCCESSFUL ) { 279beep_flush (); 280return OK ;// Something illegal on command line 281 } 282if (xp -> xp_context == EXPAND_NOTHING ) { 283// Caller can use the character as a normal char instead 284return FAIL ; 285 } 286 287int i = (int )(xp -> xp_pattern - ccline -> cmdbuff ); 288assert (ccline -> cmdpos >=i ); 289xp -> xp_pattern_len = (size_t )ccline -> cmdpos - (size_t )i ; 290 291// Skip showing matches if prefix is invalid during wildtrigger() 292if (from_wildtrigger_func && xp -> xp_context == EXPAND_COMMANDS 293&& xp -> xp_pattern_len == 0 ) { 294return FAIL ; 295 } 296 297// If cmd_silent is set then don't show the dots, because redrawcmd() below 298// won't remove them. 299if (!cmd_silent && !from_wildtrigger_func && !wild_navigate 300&& !(ui_has (kUICmdline )|| ui_has (kUIWildmenu ))) { 301msg_puts ("..." );// show that we are busy 302ui_flush (); 303 } 304 305if (wild_navigate ) { 306// Get next/previous match for a previous expanded pattern. 307p = ExpandOne (xp ,NULL ,NULL ,0 ,type ); 308 }else { 309char * tmp ; 310if (cmdline_fuzzy_completion_supported (xp ) 311|| xp -> xp_context == EXPAND_PATTERN_IN_BUF ) { 312// Don't modify the search string 313tmp = xstrnsave (xp -> xp_pattern ,xp -> xp_pattern_len ); 314 }else { 315tmp = addstar (xp -> xp_pattern ,xp -> xp_pattern_len ,xp -> xp_context ); 316 } 317// Translate string into pattern and expand it. 318const int use_options = (options 319 |WILD_USE_COMPLETESLASH 320 |WILD_HOME_REPLACE 321 |WILD_ADD_SLASH 322 |WILD_SILENT 323 | (escape ?WILD_ESCAPE :0 ) 324 | (p_wic ?WILD_ICASE :0 )); 325p = ExpandOne (xp ,tmp ,xstrnsave (& ccline -> cmdbuff [i ],xp -> xp_pattern_len ), 326use_options ,type ); 327xfree (tmp ); 328// Longest match: make sure it is not shorter, happens with :help. 329if (p != NULL && type == WILD_LONGEST ) { 330int j ; 331for (j = 0 ; (size_t )j < xp -> xp_pattern_len ;j ++ ) { 332char c = ccline -> cmdbuff [i + j ]; 333if (c == '*' || c == '?' ) { 334break ; 335 } 336 } 337if ((int )strlen (p )< j ) { 338XFREE_CLEAR (p ); 339 } 340 } 341 } 342 343// Save cmdline before inserting selected item 344if (!wild_navigate && ccline -> cmdbuff != NULL ) { 345xfree (cmdline_orig .data ); 346cmdline_orig = cstrn_to_string (ccline -> cmdbuff , (size_t )ccline -> cmdlen ); 347 } 348 349if (p != NULL && !got_int && !(options & (WILD_NOSELECT |WILD_NOINSERT ))) { 350size_t plen = strlen (p ); 351int difflen = (int )plen - (int )(xp -> xp_pattern_len ); 352if (ccline -> cmdlen + difflen + 4 > ccline -> cmdbufflen ) { 353realloc_cmdbuff (ccline -> cmdlen + difflen + 4 ); 354xp -> xp_pattern = ccline -> cmdbuff + i ; 355 } 356assert (ccline -> cmdpos <=ccline -> cmdlen ); 357memmove (& ccline -> cmdbuff [ccline -> cmdpos + difflen ], 358& ccline -> cmdbuff [ccline -> cmdpos ], 359 (size_t )ccline -> cmdlen - (size_t )ccline -> cmdpos + 1 ); 360memmove (& ccline -> cmdbuff [i ],p ,plen ); 361ccline -> cmdlen += difflen ; 362ccline -> cmdpos += difflen ; 363 } 364 365redrawcmd (); 366cursorcmd (); 367 368// When expanding a ":map" command and no matches are found, assume that 369// the key is supposed to be inserted literally 370if (xp -> xp_context == EXPAND_MAPPINGS && p == NULL ) { 371return FAIL ; 372 } 373 374if (xp -> xp_numfiles <=0 && p == NULL ) { 375beep_flush (); 376 }else if (xp -> xp_numfiles == 1 && !(options & (WILD_NOSELECT |WILD_NOINSERT )) 377&& !wild_navigate ) { 378// free expanded pattern 379ExpandOne (xp ,NULL ,NULL ,0 ,WILD_FREE ); 380 } 381 382xfree (p ); 383 384return OK ; 385} 386 387/// Create completion popup menu with items from "matches". 388static void cmdline_pum_create (const CmdlineInfo * ccline ,expand_T * xp ,char ** matches , 389int numMatches ,bool showtail ,bool cmdline_unchanged ) 390FUNC_ATTR_NONNULL_ARG (1 ,2 ) 391{ 392assert (numMatches >=0 ); 393// Add all the completion matches 394compl_match_array = xmalloc (sizeof (pumitem_T )* (size_t )numMatches ); 395compl_match_arraysize = numMatches ; 396for (int i = 0 ;i < numMatches ;i ++ ) { 397compl_match_array [i ]= (pumitem_T ){ 398 .pum_text = (xp -> xp_files_abbr != NULL && xp -> xp_files_abbr [i ]!= NULL ) 399 ?xp -> xp_files_abbr [i ] :SHOW_MATCH (i ), 400 .pum_info = xp -> xp_files_info != NULL ?xp -> xp_files_info [i ] :NULL , 401 .pum_extra = xp -> xp_files_menu != NULL ?xp -> xp_files_menu [i ] :NULL , 402 .pum_kind = xp -> xp_files_kind != NULL ?xp -> xp_files_kind [i ] :NULL , 403 .pum_user_abbr_hlattr = -1 , 404 .pum_user_kind_hlattr = -1 , 405 }; 406 } 407 408// Compute the popup menu starting column 409char * endpos = showtail ?showmatches_gettail (xp -> xp_pattern ,cmdline_unchanged ) :xp -> xp_pattern ; 410if (ui_has (kUICmdline )&& cmdline_win == NULL ) { 411compl_startcol = (int )(endpos - ccline -> cmdbuff ); 412 }else { 413compl_startcol = cmd_screencol ((int )(endpos - ccline -> cmdbuff )); 414 } 415} 416 417void cmdline_pum_display (bool changed_array ) 418{ 419pum_display (compl_match_array ,compl_match_arraysize ,compl_selected , 420changed_array ,compl_startcol ); 421} 422 423/// Returns true if the cmdline completion popup menu is being displayed. 424bool cmdline_pum_active (void ) 425{ 426return pum_visible ()&& compl_match_array != NULL ; 427} 428 429/// Remove the cmdline completion popup menu (if present), free the list of items. 430void cmdline_pum_remove (bool defer_redraw ) 431{ 432pum_undisplay (!defer_redraw ); 433XFREE_CLEAR (compl_match_array ); 434compl_match_arraysize = 0 ; 435} 436 437void cmdline_pum_cleanup (CmdlineInfo * cclp ) 438{ 439cmdline_pum_remove (false); 440wildmenu_cleanup (cclp ); 441} 442 443/// Returns the current cmdline completion pattern. 444char * cmdline_compl_pattern (void ) 445{ 446expand_T * xp = get_cmdline_info ()-> xpc ; 447return xp == NULL ?NULL :xp -> xp_orig ; 448} 449 450/// Returns true if fuzzy cmdline completion is active, false otherwise. 451bool cmdline_compl_is_fuzzy (void ) 452{ 453expand_T * xp = get_cmdline_info ()-> xpc ; 454return xp != NULL && cmdline_fuzzy_completion_supported (xp ); 455} 456 457/// Checks whether popup menu should be used for cmdline completion wildmenu. 458/// 459/// @param wildmenu whether wildmenu is needed by current 'wildmode' part 460static bool cmdline_compl_use_pum (bool need_wildmenu ) 461{ 462return ((need_wildmenu && (wop_flags & kOptWopFlagPum ) 463&& !(ui_has (kUICmdline )&& cmdline_win == NULL )) 464|| ui_has (kUIWildmenu )|| (ui_has (kUICmdline )&& ui_has (kUIPopupmenu ))); 465} 466 467/// Return the number of characters that should be skipped in the wildmenu 468/// These are backslashes used for escaping. Do show backslashes in help tags 469/// and in search pattern completion matches. 470static int skip_wildmenu_char (expand_T * xp ,char * s ) 471{ 472if ((rem_backslash (s )&& xp -> xp_context != EXPAND_HELP 473&& xp -> xp_context != EXPAND_PATTERN_IN_BUF ) 474|| ((xp -> xp_context == EXPAND_MENUS || xp -> xp_context == EXPAND_MENUNAMES ) 475&& (s [0 ]== '\t' || (s [0 ]== '\\' && s [1 ]!= NUL )))) { 476#ifndef BACKSLASH_IN_FILENAME 477// TODO(bfredl): Why in the actual fuck are we special casing the 478// shell variety deep in the redraw logic? Shell special snowflakiness 479// should already be eliminated multiple layers before reaching the 480// screen infracstructure. 481if (xp -> xp_shell && csh_like_shell ()&& s [1 ]== '\\' && s [2 ]== '!' ) { 482return 2 ; 483 } 484#endif 485return 1 ; 486 } 487return 0 ; 488} 489 490/// Get the length of an item as it will be shown in the status line. 491static int wildmenu_match_len (expand_T * xp ,char * s ) 492{ 493int len = 0 ; 494 495int emenu = (xp -> xp_context == EXPAND_MENUS 496|| xp -> xp_context == EXPAND_MENUNAMES ); 497 498// Check for menu separators - replace with '|'. 499if (emenu && menu_is_separator (s )) { 500return 1 ; 501 } 502 503while (* s != NUL ) { 504s += skip_wildmenu_char (xp ,s ); 505len += ptr2cells (s ); 506MB_PTR_ADV (s ); 507 } 508 509return len ; 510} 511 512/// Show wildchar matches in the status line. 513/// Show at least the "match" item. 514/// We start at item "first_match" in the list and show all matches that fit. 515/// 516/// If inversion is possible we use it. Else '=' characters are used. 517/// 518/// @param matches list of matches 519static void redraw_wildmenu (expand_T * xp ,int num_matches ,char ** matches ,int match ,bool showtail ) 520{ 521bool highlight = true; 522char * selstart = NULL ; 523int selstart_col = 0 ; 524char * selend = NULL ; 525static int first_match = 0 ; 526bool add_left = false; 527int i ,l ; 528 529if (matches == NULL ) {// interrupted completion? 530return ; 531 } 532 533char * buf = xmalloc ((size_t )Columns * MB_MAXBYTES + 1 ); 534 535if (match == -1 ) {// don't show match but original text 536match = 0 ; 537highlight = false; 538 } 539// count 1 for the ending ">" 540int clen = wildmenu_match_len (xp ,SHOW_MATCH (match ))+ 3 ;// length in screen cells 541if (match == 0 ) { 542first_match = 0 ; 543 }else if (match < first_match ) { 544// jumping left, as far as we can go 545first_match = match ; 546add_left = true; 547 }else { 548// check if match fits on the screen 549for (i = first_match ;i < match ;i ++ ) { 550clen += wildmenu_match_len (xp ,SHOW_MATCH (i ))+ 2 ; 551 } 552if (first_match > 0 ) { 553clen += 2 ; 554 } 555// jumping right, put match at the left 556if (clen > Columns ) { 557first_match = match ; 558// if showing the last match, we can add some on the left 559clen = 2 ; 560for (i = match ;i < num_matches ;i ++ ) { 561clen += wildmenu_match_len (xp ,SHOW_MATCH (i ))+ 2 ; 562if (clen >=Columns ) { 563break ; 564 } 565 } 566if (i == num_matches ) { 567add_left = true; 568 } 569 } 570 } 571if (add_left ) { 572while (first_match > 0 ) { 573clen += wildmenu_match_len (xp ,SHOW_MATCH (first_match - 1 ))+ 2 ; 574if (clen >=Columns ) { 575break ; 576 } 577first_match -- ; 578 } 579 } 580 581int len ; 582hlf_T group ; 583schar_T fillchar = fillchar_status (& group ,curwin ); 584int attr = win_hl_attr (curwin , (int )group ); 585 586if (first_match == 0 ) { 587* buf = NUL ; 588len = 0 ; 589 }else { 590STRCPY (buf ,"< " ); 591len = 2 ; 592 } 593clen = len ; 594 595i = first_match ; 596while (clen + wildmenu_match_len (xp ,SHOW_MATCH (i ))+ 2 < Columns ) { 597if (i == match ) { 598selstart = buf + len ; 599selstart_col = clen ; 600 } 601 602char * s = SHOW_MATCH (i ); 603// Check for menu separators - replace with '|' 604int emenu = (xp -> xp_context == EXPAND_MENUS || xp -> xp_context == EXPAND_MENUNAMES ); 605if (emenu && menu_is_separator (s )) { 606STRCPY (buf + len ,transchar ('|' )); 607l = (int )strlen (buf + len ); 608len += l ; 609clen += l ; 610 }else { 611for (;* s != NUL ;s ++ ) { 612s += skip_wildmenu_char (xp ,s ); 613clen += ptr2cells (s ); 614if ((l = utfc_ptr2len (s ))> 1 ) { 615strncpy (buf + len ,s , (size_t )l );// NOLINT(runtime/printf) 616s += l - 1 ; 617len += l ; 618 }else { 619STRCPY (buf + len ,transchar_byte ((uint8_t )(* s ))); 620len += (int )strlen (buf + len ); 621 } 622 } 623 } 624if (i == match ) { 625selend = buf + len ; 626 } 627 628* (buf + len ++ )= ' ' ; 629* (buf + len ++ )= ' ' ; 630clen += 2 ; 631if (++ i == num_matches ) { 632break ; 633 } 634 } 635 636if (i != num_matches ) { 637* (buf + len ++ )= '>' ; 638clen ++ ; 639 } 640 641buf [len ]= NUL ; 642 643int row = cmdline_row - 1 ; 644if (row >=0 ) { 645if (wild_menu_showing == 0 ) { 646if (msg_scrolled > 0 ) { 647// Put the wildmenu just above the command line. If there is 648// no room, scroll the screen one line up. 649if (cmdline_row == Rows - 1 ) { 650msg_scroll_up (false, false); 651msg_scrolled ++ ; 652 }else { 653cmdline_row ++ ; 654row ++ ; 655 } 656wild_menu_showing = WM_SCROLLED ; 657 }else { 658// Create status line if needed by setting 'laststatus' to 2. 659// Set 'winminheight' to zero to avoid that the window is 660// resized. 661if (lastwin -> w_status_height == 0 && global_stl_height ()== 0 ) { 662save_p_ls = (int )p_ls ; 663save_p_wmh = (int )p_wmh ; 664p_ls = 2 ; 665p_wmh = 0 ; 666last_status (false); 667 } 668wild_menu_showing = WM_SHOWN ; 669 } 670 } 671 672// Tricky: wildmenu can be drawn either over a status line, or at empty 673// scrolled space in the message output 674grid_line_start ((wild_menu_showing == WM_SCROLLED ) ?& msg_grid_adj :& default_gridview ,row ); 675 676grid_line_puts (0 ,buf ,-1 ,attr ); 677if (selstart != NULL && highlight ) { 678* selend = NUL ; 679grid_line_puts (selstart_col ,selstart ,-1 ,HL_ATTR (HLF_WM )); 680 } 681 682grid_line_fill (clen ,Columns ,fillchar ,attr ); 683 684grid_line_flush (); 685 } 686 687win_redraw_last_status (topframe ); 688xfree (buf ); 689} 690 691/// Get the next or prev cmdline completion match. The index of the match is set 692/// in "xp->xp_selected" 693static char * get_next_or_prev_match (int mode ,expand_T * xp ) 694{ 695// When no matches found, return NULL 696if (xp -> xp_numfiles <=0 ) { 697return NULL ; 698 } 699 700int findex = xp -> xp_selected ; 701 702if (mode == WILD_PREV ) { 703// Select the last entry if at original text 704if (findex == -1 ) { 705findex = xp -> xp_numfiles ; 706 } 707// Otherwise select the previous entry 708findex -- ; 709 }else if (mode == WILD_NEXT ) { 710// Select the next entry 711findex ++ ; 712 }else if (mode == WILD_PAGEUP || mode == WILD_PAGEDOWN ) { 713// Get the height of popup menu (used for both PAGEUP and PAGEDOWN) 714int ht = pum_get_height (); 715if (ht > 3 ) { 716ht -= 2 ; 717 } 718 719if (mode == WILD_PAGEUP ) { 720if (findex == 0 ) { 721// at the first entry, don't select any entries 722findex = -1 ; 723 }else if (findex < 0 ) { 724// no entry is selected. select the last entry 725findex = xp -> xp_numfiles - 1 ; 726 }else { 727// go up by the pum height 728findex = MAX (findex - ht ,0 ); 729 } 730 }else {// mode == WILD_PAGEDOWN 731if (findex == xp -> xp_numfiles - 1 ) { 732// at the last entry, don't select any entries 733findex = -1 ; 734 }else if (findex < 0 ) { 735// no entry is selected. select the first entry 736findex = 0 ; 737 }else { 738// go down by the pum height 739findex = MIN (findex + ht ,xp -> xp_numfiles - 1 ); 740 } 741 } 742 }else {// mode == WILD_PUM_WANT 743assert (pum_want .active ); 744findex = pum_want .item ; 745 } 746 747// Handle wrapping around 748if (findex < 0 || findex >=xp -> xp_numfiles ) { 749// If original text exists, return to it when wrapping around 750if (xp -> xp_orig != NULL ) { 751findex = -1 ; 752 }else { 753// Wrap around to opposite end 754findex = (findex < 0 ) ?xp -> xp_numfiles - 1 :0 ; 755 } 756 } 757 758// Display matches on screen 759if (p_wmnu ) { 760if (compl_match_array ) { 761compl_selected = findex ; 762cmdline_pum_display (false); 763 }else if (cmdline_compl_use_pum (true)) { 764cmdline_pum_create (get_cmdline_info (),xp ,xp -> xp_files ,xp -> xp_numfiles , 765cmd_showtail , false); 766compl_selected = findex ; 767pum_clear (); 768cmdline_pum_display (true); 769 }else { 770redraw_wildmenu (xp ,xp -> xp_numfiles ,xp -> xp_files ,findex ,cmd_showtail ); 771 } 772 } 773 774xp -> xp_selected = findex ; 775// Return the original text or the selected match 776return xstrdup (findex == -1 ?xp -> xp_orig :xp -> xp_files [findex ]); 777} 778 779/// Start the command-line expansion and get the matches. 780static char * ExpandOne_start (int mode ,expand_T * xp ,char * str ,int options ) 781{ 782int non_suf_match ;// number without matching suffix 783char * ss = NULL ; 784 785// Do the expansion. 786if (ExpandFromContext (xp ,str ,& xp -> xp_files ,& xp -> xp_numfiles ,options )== FAIL ) { 787#ifdef FNAME_ILLEGAL 788// Illegal file name has been silently skipped. But when there 789// are wildcards, the real problem is that there was no match, 790// causing the pattern to be added, which has illegal characters. 791if (!(options & WILD_SILENT )&& (options & WILD_LIST_NOTFOUND )) { 792semsg (_ (e_nomatch2 ),str ); 793 } 794#endif 795 }else if (xp -> xp_numfiles == 0 ) { 796if (!(options & WILD_SILENT )) { 797semsg (_ (e_nomatch2 ),str ); 798 } 799 }else { 800// Escape the matches for use on the command line. 801ExpandEscape (xp ,str ,xp -> xp_numfiles ,xp -> xp_files ,options ); 802 803// Check for matching suffixes in file names. 804if (mode != WILD_ALL && mode != WILD_ALL_KEEP && mode != WILD_LONGEST ) { 805if (xp -> xp_numfiles ) { 806non_suf_match = xp -> xp_numfiles ; 807 }else { 808non_suf_match = 1 ; 809 } 810if ((xp -> xp_context == EXPAND_FILES 811|| xp -> xp_context == EXPAND_DIRECTORIES ) 812&& xp -> xp_numfiles > 1 ) { 813// More than one match; check suffix. 814// The files will have been sorted on matching suffix in 815// expand_wildcards, only need to check the first two. 816non_suf_match = 0 ; 817for (int i = 0 ;i < 2 ;i ++ ) { 818if (match_suffix (xp -> xp_files [i ])) { 819non_suf_match ++ ; 820 } 821 } 822 } 823if (non_suf_match != 1 ) { 824// Can we ever get here unless it's while expanding 825// interactively? If not, we can get rid of this all 826// together. Don't really want to wait for this message 827// (and possibly have to hit return to continue!). 828if (!(options & WILD_SILENT )) { 829emsg (_ (e_toomany )); 830 }else if (!(options & WILD_NO_BEEP )) { 831beep_flush (); 832 } 833 } 834if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE )) { 835ss = xstrdup (xp -> xp_files [0 ]); 836 } 837 } 838 } 839 840return ss ; 841} 842 843/// Return the longest common part in the list of cmdline completion matches. 844static char * find_longest_match (expand_T * xp ,int options ) 845{ 846size_t len = 0 ; 847 848for (size_t mb_len ;xp -> xp_files [0 ][len ];len += mb_len ) { 849mb_len = (size_t )utfc_ptr2len (& xp -> xp_files [0 ][len ]); 850int c0 = utf_ptr2char (& xp -> xp_files [0 ][len ]); 851int i ; 852for (i = 1 ;i < xp -> xp_numfiles ;i ++ ) { 853int ci = utf_ptr2char (& xp -> xp_files [i ][len ]); 854 855if (p_fic && (xp -> xp_context == EXPAND_DIRECTORIES 856|| xp -> xp_context == EXPAND_FILES 857|| xp -> xp_context == EXPAND_SHELLCMD 858|| xp -> xp_context == EXPAND_BUFFERS )) { 859if (mb_tolower (c0 )!= mb_tolower (ci )) { 860break ; 861 } 862 }else if (c0 != ci ) { 863break ; 864 } 865 } 866if (i < xp -> xp_numfiles ) { 867if (!(options & WILD_NO_BEEP )) { 868vim_beep (kOptBoFlagWildmode ); 869 } 870break ; 871 } 872 } 873 874return xmemdupz (xp -> xp_files [0 ],len ); 875} 876 877void free_xp_files_extra (expand_T * xp ,int numfiles ) 878{ 879if (xp -> xp_files_abbr != NULL ) { 880FreeWild (numfiles ,xp -> xp_files_abbr ); 881xp -> xp_files_abbr = NULL ; 882 } 883if (xp -> xp_files_kind != NULL ) { 884FreeWild (numfiles ,xp -> xp_files_kind ); 885xp -> xp_files_kind = NULL ; 886 } 887if (xp -> xp_files_menu != NULL ) { 888FreeWild (numfiles ,xp -> xp_files_menu ); 889xp -> xp_files_menu = NULL ; 890 } 891if (xp -> xp_files_info != NULL ) { 892FreeWild (numfiles ,xp -> xp_files_info ); 893xp -> xp_files_info = NULL ; 894 } 895} 896 897/// Do wildcard expansion on the string "str". 898/// Chars that should not be expanded must be preceded with a backslash. 899/// Return a pointer to allocated memory containing the new string. 900/// Return NULL for failure. 901/// 902/// "orig" is the originally expanded string, copied to allocated memory. It 903/// should either be kept in "xp->xp_orig" or freed. When "mode" is WILD_NEXT 904/// or WILD_PREV "orig" should be NULL. 905/// 906/// Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode" 907/// is WILD_EXPAND_FREE or WILD_ALL. 908/// 909/// mode = WILD_FREE: just free previously expanded matches 910/// mode = WILD_EXPAND_FREE: normal expansion, do not keep matches 911/// mode = WILD_EXPAND_KEEP: normal expansion, keep matches 912/// mode = WILD_NEXT: use next match in multiple match, wrap to first 913/// mode = WILD_PREV: use previous match in multiple match, wrap to first 914/// mode = WILD_ALL: return all matches concatenated 915/// mode = WILD_LONGEST: return longest matched part 916/// mode = WILD_ALL_KEEP: get all matches, keep matches 917/// mode = WILD_APPLY: apply the item selected in the cmdline completion 918/// popup menu and close the menu. 919/// mode = WILD_CANCEL: cancel and close the cmdline completion popup and 920/// use the original text. 921/// mode = WILD_PUM_WANT: use the match at index pum_want.item 922/// 923/// options = WILD_LIST_NOTFOUND: list entries without a match 924/// options = WILD_HOME_REPLACE: do home_replace() for buffer names 925/// options = WILD_USE_NL: Use '\n' for WILD_ALL 926/// options = WILD_NO_BEEP: Don't beep for multiple matches 927/// options = WILD_ADD_SLASH: add a slash after directory names 928/// options = WILD_KEEP_ALL: don't remove 'wildignore' entries 929/// options = WILD_SILENT: don't print warning messages 930/// options = WILD_ESCAPE: put backslash before special chars 931/// options = WILD_ICASE: ignore case for files 932/// 933/// The variables xp->xp_context and xp->xp_backslash must have been set! 934/// 935/// @param orig allocated copy of original of expanded string 936char * ExpandOne (expand_T * xp ,char * str ,char * orig ,int options ,int mode ) 937{ 938char * ss = NULL ; 939bool orig_saved = false; 940 941// first handle the case of using an old match 942if (mode == WILD_NEXT || mode == WILD_PREV 943|| mode == WILD_PAGEUP || mode == WILD_PAGEDOWN 944|| mode == WILD_PUM_WANT ) { 945return get_next_or_prev_match (mode ,xp ); 946 } 947 948if (mode == WILD_CANCEL ) { 949ss = xstrdup (xp -> xp_orig ?xp -> xp_orig :"" ); 950 }else if (mode == WILD_APPLY ) { 951ss = xstrdup (xp -> xp_selected == -1 952 ? (xp -> xp_orig ?xp -> xp_orig :"" ) 953 :xp -> xp_files [xp -> xp_selected ]); 954 } 955 956// free old names 957if (xp -> xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST ) { 958FreeWild (xp -> xp_numfiles ,xp -> xp_files ); 959free_xp_files_extra (xp ,xp -> xp_numfiles ); 960xp -> xp_numfiles = -1 ; 961XFREE_CLEAR (xp -> xp_orig ); 962 963// The entries from xp_files may be used in the PUM, remove it. 964if (compl_match_array != NULL ) { 965cmdline_pum_remove (false); 966 } 967 } 968xp -> xp_selected = (options & WILD_NOSELECT ) ?-1 :0 ; 969 970if (mode == WILD_FREE ) {// only release file name 971return NULL ; 972 } 973 974if (xp -> xp_numfiles == -1 && mode != WILD_APPLY && mode != WILD_CANCEL ) { 975xfree (xp -> xp_orig ); 976xp -> xp_orig = orig ; 977orig_saved = true; 978 979ss = ExpandOne_start (mode ,xp ,str ,options ); 980 } 981 982// Find longest common part 983if (mode == WILD_LONGEST && xp -> xp_numfiles > 0 ) { 984ss = find_longest_match (xp ,options ); 985xp -> xp_selected = -1 ;// next p_wc gets first one 986 } 987 988// Concatenate all matching names. Unless interrupted, this can be slow 989// and the result probably won't be used. 990if (mode == WILD_ALL && xp -> xp_numfiles > 0 && !got_int ) { 991size_t ss_size = 0 ; 992char * prefix = "" ; 993char * suffix = (options & WILD_USE_NL ) ?"\n" :" " ; 994const int n = xp -> xp_numfiles - 1 ; 995 996if (xp -> xp_prefix == XP_PREFIX_NO ) { 997prefix = "no" ; 998ss_size = STRLEN_LITERAL ("no" )* (size_t )n ; 999 }else if (xp -> xp_prefix == XP_PREFIX_INV ) { 1000prefix = "inv" ; 1001ss_size = STRLEN_LITERAL ("inv" )* (size_t )n ; 1002 } 1003 1004for (int i = 0 ;i < xp -> xp_numfiles ;i ++ ) { 1005ss_size += strlen (xp -> xp_files [i ])+ 1 ;// +1 for the suffix 1006 } 1007ss_size ++ ;// +1 for the NUL 1008 1009ss = xmalloc (ss_size ); 1010* ss = NUL ; 1011char * ssp = ss ; 1012for (int i = 0 ;i < xp -> xp_numfiles ;i ++ ) { 1013if (i > 0 ) { 1014ssp = xstpcpy (ssp ,prefix ); 1015 } 1016ssp = xstpcpy (ssp ,xp -> xp_files [i ]); 1017if (i < n ) { 1018ssp = xstpcpy (ssp ,suffix ); 1019 } 1020assert (ssp < ss + ss_size ); 1021 } 1022 } 1023 1024if (mode == WILD_EXPAND_FREE || mode == WILD_ALL ) { 1025ExpandCleanup (xp ); 1026 } 1027 1028// Free "orig" if it wasn't stored in "xp->xp_orig". 1029if (!orig_saved ) { 1030xfree (orig ); 1031 } 1032 1033return ss ; 1034} 1035 1036/// Prepare an expand structure for use. 1037void ExpandInit (expand_T * xp ) 1038FUNC_ATTR_NONNULL_ALL 1039{ 1040CLEAR_POINTER (xp ); 1041xp -> xp_backslash = XP_BS_NONE ; 1042xp -> xp_prefix = XP_PREFIX_NONE ; 1043xp -> xp_numfiles = -1 ; 1044} 1045 1046/// Cleanup an expand structure after use. 1047void ExpandCleanup (expand_T * xp ) 1048{ 1049if (xp -> xp_numfiles >=0 ) { 1050free_xp_files_extra (xp ,xp -> xp_numfiles ); 1051FreeWild (xp -> xp_numfiles ,xp -> xp_files ); 1052xp -> xp_numfiles = -1 ; 1053 } 1054XFREE_CLEAR (xp -> xp_orig ); 1055} 1056 1057void clear_cmdline_orig (void ) 1058{ 1059API_CLEAR_STRING (cmdline_orig ); 1060} 1061 1062/// Display one line of completion matches. Multiple matches are displayed in 1063/// each line (used by wildmode=list and CTRL-D) 1064/// 1065/// @param matches list of completion match names 1066/// @param numMatches number of completion matches in "matches" 1067/// @param lines number of output lines 1068/// @param linenr line number of matches to display 1069/// @param maxlen maximum number of characters in each line 1070/// @param showtail display only the tail of the full path of a file name 1071static void showmatches_oneline (expand_T * xp ,char ** matches ,int numMatches ,int lines ,int linenr , 1072int maxlen ,bool showtail ) 1073{ 1074char * p ; 1075int lastlen = 999 ; 1076for (int j = linenr ;j < numMatches ;j += lines ) { 1077if (xp -> xp_context == EXPAND_TAGS_LISTFILES ) { 1078msg_outtrans (matches [j ],HLF_D , false); 1079p = matches [j ]+ strlen (matches [j ])+ 1 ; 1080msg_advance (maxlen + 1 ); 1081msg_puts (p ); 1082msg_advance (maxlen + 3 ); 1083msg_outtrans_long (p + 2 ,HLF_D ); 1084break ; 1085 } 1086for (int i = maxlen - lastlen ;-- i >=0 ;) { 1087msg_putchar (' ' ); 1088 } 1089bool isdir ; 1090if (xp -> xp_context == EXPAND_FILES 1091|| xp -> xp_context == EXPAND_SHELLCMD 1092|| xp -> xp_context == EXPAND_BUFFERS ) { 1093// highlight directories 1094if (xp -> xp_numfiles != -1 ) { 1095// Expansion was done before and special characters 1096// were escaped, need to halve backslashes. Also 1097// $HOME has been replaced with ~/. 1098char * exp_path = expand_env_save_opt (matches [j ], true,NULL ); 1099char * path = exp_path != NULL ?exp_path :matches [j ]; 1100char * halved_slash = backslash_halve_save (path ); 1101isdir = os_isdir (halved_slash ); 1102xfree (exp_path ); 1103if (halved_slash != path ) { 1104xfree (halved_slash ); 1105 } 1106 }else { 1107// Expansion was done here, file names are literal. 1108isdir = os_isdir (matches [j ]); 1109 } 1110if (showtail ) { 1111p = SHOW_MATCH (j ); 1112 }else { 1113home_replace (NULL ,matches [j ],NameBuff ,MAXPATHL , true); 1114p = NameBuff ; 1115 } 1116 }else { 1117isdir = false; 1118p = SHOW_MATCH (j ); 1119 } 1120lastlen = msg_outtrans (p ,isdir ?HLF_D :0 , false); 1121 } 1122if (msg_col > 0 ) {// when not wrapped around 1123msg_clr_eos (); 1124msg_putchar ('\n' ); 1125 } 1126} 1127 1128/// Show the matches in a popup menu, with the first one selected unless 1129/// "noselect" is set. 1130static inline void show_pum_matches (CmdlineInfo * ccline ,expand_T * xp ,char ** matches , 1131int numMatches ,bool showtail ,bool noselect , 1132bool cmdline_unchanged ) 1133{ 1134cmdline_pum_create (ccline ,xp ,matches ,numMatches ,showtail ,cmdline_unchanged ); 1135compl_selected = noselect ?-1 :0 ; 1136pum_clear (); 1137cmdline_pum_display (true); 1138} 1139 1140/// Display completion matches. 1141/// Returns EXPAND_NOTHING when the character that triggered expansion should be 1142/// inserted as a normal character. 1143int showmatches (expand_T * xp ,bool display_wildmenu ,bool display_list ,int wim_flags_arg ) 1144{ 1145CmdlineInfo * const ccline = get_cmdline_info (); 1146int numMatches ; 1147char ** matches ; 1148int maxlen ; 1149int lines ; 1150int columns ; 1151bool showtail ; 1152bool noselect = (wim_flags_arg & kOptWimFlagNoselect ); 1153bool noinsert = (wim_flags_arg & kOptWimFlagNoinsert ); 1154bool cmdline_unchanged = noselect || noinsert ; 1155 1156if (xp -> xp_numfiles == -1 ) { 1157set_expand_context (xp ); 1158if (xp -> xp_context == EXPAND_LUA ) { 1159nlua_expand_pat (xp ); 1160 } 1161int retval = expand_cmdline (xp ,ccline -> cmdbuff ,ccline -> cmdpos , 1162& numMatches ,& matches ); 1163if (retval != EXPAND_OK ) { 1164return retval ; 1165 } 1166showtail = expand_showtail (xp ); 1167 }else { 1168numMatches = xp -> xp_numfiles ; 1169matches = xp -> xp_files ; 1170showtail = cmd_showtail ; 1171 } 1172 1173if (cmdline_compl_use_pum (display_wildmenu && !display_list )) { 1174show_pum_matches (ccline ,xp ,matches ,numMatches ,showtail ,noselect ,cmdline_unchanged ); 1175return EXPAND_OK ; 1176 } 1177 1178if (display_list ) { 1179msg_didany = false;// lines_left will be set 1180msg_start ();// prepare for paging 1181if (!ui_has (kUIMessages )) { 1182msg_putchar ('\n' ); 1183 } 1184ui_flush (); 1185cmdline_row = msg_row ; 1186msg_didany = false;// lines_left will be set again 1187msg_ext_set_kind ("wildlist" ); 1188msg_start ();// prepare for paging 1189 } 1190 1191if (got_int ) { 1192got_int = false;// only interrupt the completion, not the cmd line 1193 }else if (display_wildmenu && !display_list ) { 1194redraw_wildmenu (xp ,numMatches ,matches ,noselect ?-1 :0 , 1195showtail );// display statusbar menu 1196 }else if (display_list ) { 1197// find the length of the longest file name 1198maxlen = 0 ; 1199for (int i = 0 ;i < numMatches ;i ++ ) { 1200int len ; 1201if (!showtail && (xp -> xp_context == EXPAND_FILES 1202|| xp -> xp_context == EXPAND_SHELLCMD 1203|| xp -> xp_context == EXPAND_BUFFERS )) { 1204home_replace (NULL ,matches [i ],NameBuff ,MAXPATHL , true); 1205len = vim_strsize (NameBuff ); 1206 }else { 1207len = vim_strsize (SHOW_MATCH (i )); 1208 } 1209maxlen = MAX (maxlen ,len ); 1210 } 1211 1212if (xp -> xp_context == EXPAND_TAGS_LISTFILES ) { 1213lines = numMatches ; 1214 }else { 1215// compute the number of columns and lines for the listing 1216maxlen += 2 ;// two spaces between file names 1217columns = (Columns + 2 ) /maxlen ; 1218if (columns < 1 ) { 1219columns = 1 ; 1220 } 1221lines = (numMatches + columns - 1 ) /columns ; 1222 } 1223 1224if (xp -> xp_context == EXPAND_TAGS_LISTFILES ) { 1225msg_puts_hl (_ ("tagname" ),HLF_T , false); 1226msg_clr_eos (); 1227msg_advance (maxlen - 3 ); 1228msg_puts_hl (_ (" kind file\n" ),HLF_T , false); 1229 } 1230 1231// list the files line by line 1232for (int i = 0 ;i < lines ;i ++ ) { 1233showmatches_oneline (xp ,matches ,numMatches ,lines ,i ,maxlen ,showtail ); 1234if (got_int ) { 1235got_int = false; 1236break ; 1237 } 1238 } 1239 1240// we redraw the command below the lines that we have just listed 1241// This is a bit tricky, but it saves a lot of screen updating. 1242cmdline_row = msg_row ;// will put it back later 1243 } 1244 1245// "list" and "full" in the same 'wildmode' phase: the matches are listed 1246// above and shown in the menu as well. 1247if (display_wildmenu && display_list ) { 1248if (cmdline_compl_use_pum (true)) { 1249show_pum_matches (ccline ,xp ,matches ,numMatches ,showtail ,noselect ,cmdline_unchanged ); 1250 }else { 1251redraw_wildmenu (xp ,numMatches ,matches ,noselect ?-1 :0 ,showtail ); 1252 } 1253 } 1254 1255if (xp -> xp_numfiles == -1 ) { 1256FreeWild (numMatches ,matches ); 1257free_xp_files_extra (xp ,numMatches ); 1258 } 1259 1260return EXPAND_OK ; 1261} 1262 1263/// path_tail() version for showmatches() and redraw_wildmenu(): 1264/// Return the tail of file name path "s", ignoring a trailing "/". 1265static char * showmatches_gettail (char * s ,bool eager ) 1266{ 1267char * t = s ; 1268bool had_sep = false; 1269 1270for (char * p = s ;* p != NUL ;) { 1271if (vim_ispathsep (* p ) 1272#ifdef BACKSLASH_IN_FILENAME 1273&& !rem_backslash (p ) 1274#endif 1275 ) { 1276if (eager ) { 1277t = p + 1 ; 1278 }else { 1279had_sep = true; 1280 } 1281 }else if (had_sep ) { 1282t = p ; 1283had_sep = false; 1284 } 1285MB_PTR_ADV (p ); 1286 } 1287return t ; 1288} 1289 1290/// Return true if we only need to show the tail of completion matches. 1291/// When not completing file names or there is a wildcard in the path false is 1292/// returned. 1293static bool expand_showtail (expand_T * xp ) 1294{ 1295// When not completing file names a "/" may mean something different. 1296if (xp -> xp_context != EXPAND_FILES 1297&& xp -> xp_context != EXPAND_SHELLCMD 1298&& xp -> xp_context != EXPAND_DIRECTORIES ) { 1299return false; 1300 } 1301 1302char * end = path_tail (xp -> xp_pattern ); 1303if (end == xp -> xp_pattern ) {// there is no path separator 1304return false; 1305 } 1306 1307for (char * s = xp -> xp_pattern ;s < end ;s ++ ) { 1308// Skip escaped wildcards. Only when the backslash is not a path 1309// separator, on DOS the '*' "path\*\file" must not be skipped. 1310if (rem_backslash (s )) { 1311s ++ ; 1312 }else if (vim_strchr ("*?[" , (uint8_t )(* s ))!= NULL ) { 1313return false; 1314 } 1315 } 1316return true; 1317} 1318 1319/// Prepare a string for expansion. 1320/// 1321/// When expanding file names: The string will be used with expand_wildcards(). 1322/// Copy "fname[len]" into allocated memory and add a '*' at the end. 1323/// When expanding other names: The string will be used with regcomp(). Copy 1324/// the name into allocated memory and prepend "^". 1325/// 1326/// @param context EXPAND_FILES etc. 1327char * addstar (char * fname ,size_t len ,int context ) 1328FUNC_ATTR_NONNULL_RET 1329{ 1330char * retval ; 1331 1332if (context != EXPAND_FILES 1333&& context != EXPAND_FILES_IN_PATH 1334&& context != EXPAND_SHELLCMD 1335&& context != EXPAND_DIRECTORIES 1336&& context != EXPAND_DIRS_IN_CDPATH ) { 1337// Matching will be done internally (on something other than files). 1338// So we convert the file-matching-type wildcards into our kind for 1339// use with vim_regcomp(). First work out how long it will be: 1340 1341// For help tags the translation is done in find_help_tags(). 1342// For a tag pattern starting with "/" no translation is needed. 1343if (context == EXPAND_FINDFUNC 1344|| context == EXPAND_HELP 1345|| context == EXPAND_COLORS 1346|| context == EXPAND_COMPILER 1347|| context == EXPAND_OWNSYNTAX 1348|| context == EXPAND_FILETYPE 1349|| context == EXPAND_KEYMAP 1350|| context == EXPAND_PACKADD 1351|| context == EXPAND_RUNTIME 1352|| ((context == EXPAND_TAGS_LISTFILES || context == EXPAND_TAGS ) 1353&& fname [0 ]== '/' ) 1354|| context == EXPAND_CHECKHEALTH 1355|| context == EXPAND_LSP 1356|| context == EXPAND_LOG 1357|| context == EXPAND_PACKDEL 1358|| context == EXPAND_PACKUPDATE 1359|| context == EXPAND_MARKS 1360|| context == EXPAND_LUA ) { 1361retval = xstrnsave (fname ,len ); 1362 }else { 1363size_t new_len = len + 2 ;// +2 for '^' at start, NUL at end 1364for (size_t i = 0 ;i < len ;i ++ ) { 1365if (fname [i ]== '*' || fname [i ]== '~' ) { 1366new_len ++ ;// '*' needs to be replaced by ".*" 1367// '~' needs to be replaced by "\~" 1368 } 1369// Buffer names are like file names. "." should be literal 1370if (context == EXPAND_BUFFERS && fname [i ]== '.' ) { 1371new_len ++ ;// "." becomes "\." 1372 } 1373// Custom expansion takes care of special things, match 1374// backslashes literally (perhaps also for other types?) 1375if ((context == EXPAND_USER_DEFINED 1376|| context == EXPAND_USER_LIST )&& fname [i ]== '\\' ) { 1377new_len ++ ;// '\' becomes "\\" 1378 } 1379 } 1380retval = xmalloc (new_len ); 1381 { 1382retval [0 ]= '^' ; 1383size_t j = 1 ; 1384for (size_t i = 0 ;i < len ;i ++ ,j ++ ) { 1385// Skip backslash. But why? At least keep it for custom 1386// expansion. 1387if (context != EXPAND_USER_DEFINED 1388&& context != EXPAND_USER_LIST 1389&& fname [i ]== '\\' 1390&& ++ i == len ) { 1391break ; 1392 } 1393 1394switch (fname [i ]) { 1395case '*' : 1396retval [j ++ ]= '.' ; 1397break ; 1398case '~' : 1399retval [j ++ ]= '\\' ; 1400break ; 1401case '?' : 1402retval [j ]= '.' ; 1403continue ; 1404case '.' : 1405if (context == EXPAND_BUFFERS ) { 1406retval [j ++ ]= '\\' ; 1407 } 1408break ; 1409case '\\' : 1410if (context == EXPAND_USER_DEFINED 1411|| context == EXPAND_USER_LIST ) { 1412retval [j ++ ]= '\\' ; 1413 } 1414break ; 1415 } 1416retval [j ]= fname [i ]; 1417 } 1418retval [j ]= NUL ; 1419 } 1420 } 1421 }else { 1422retval = xmalloc (len + 4 ); 1423xmemcpyz (retval ,fname ,len ); 1424 1425// Don't add a star to *, ~, ~user, $var or `cmd`. 1426// * would become **, which walks the whole tree. 1427// ~ would be at the start of the file name, but not the tail. 1428// $ could be anywhere in the tail. 1429// ` could be anywhere in the file name. 1430// When the name ends in '$' don't add a star, remove the '$'. 1431char * tail = path_tail (retval ); 1432int ends_in_star = (len > 0 && retval [len - 1 ]== '*' ); 1433#ifndef BACKSLASH_IN_FILENAME 1434for (ssize_t k = (ssize_t )len - 2 ;k >=0 ;k -- ) { 1435if (retval [k ]!= '\\' ) { 1436break ; 1437 } 1438ends_in_star = !ends_in_star ; 1439 } 1440#endif 1441if ((* retval != '~' || tail != retval ) 1442&& !ends_in_star 1443&& vim_strchr (tail ,'$' )== NULL 1444&& vim_strchr (retval ,'`' )== NULL ) { 1445retval [len ++ ]= '*' ; 1446 }else if (len > 0 && retval [len - 1 ]== '$' ) { 1447len -- ; 1448 } 1449retval [len ]= NUL ; 1450 } 1451return retval ; 1452} 1453 1454/// Must parse the command line so far to work out what context we are in. 1455/// Completion can then be done based on that context. 1456/// This routine sets the variables: 1457/// xp->xp_pattern The start of the pattern to be expanded within 1458/// the command line (ends at the cursor). 1459/// xp->xp_context The type of thing to expand. Will be one of: 1460/// 1461/// EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on 1462/// the command line, like an unknown command. Caller 1463/// should beep. 1464/// EXPAND_NOTHING Unrecognised context for completion, use char like 1465/// a normal char, rather than for completion. eg 1466/// :s/^I/ 1467/// EXPAND_COMMANDS Cursor is still touching the command, so complete 1468/// it. 1469/// EXPAND_BUFFERS Complete file names for :buf and :sbuf commands. 1470/// EXPAND_FILES After command with EX_XFILE set, or after setting 1471/// with kOptFlagExpand set. eg :e ^I, :w>>^I 1472/// EXPAND_DIRECTORIES In some cases this is used instead of the latter 1473/// when we know only directories are of interest. 1474/// E.g. :set dir=^I and :cd ^I 1475/// EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd". 1476/// EXPAND_SETTINGS Complete variable names. eg :set d^I 1477/// EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I 1478/// EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I 1479/// EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect 1480/// EXPAND_HELP Complete tags from the file 'helpfile'/tags 1481/// EXPAND_EVENTS Complete event names 1482/// EXPAND_SYNTAX Complete :syntax command arguments 1483/// EXPAND_HIGHLIGHT Complete highlight (syntax) group names 1484/// EXPAND_AUGROUP Complete autocommand group names 1485/// EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I 1486/// EXPAND_MAPPINGS Complete mapping and abbreviation names, 1487/// eg :unmap a^I , :cunab x^I 1488/// EXPAND_FUNCTIONS Complete internal or user defined function names, 1489/// eg :call sub^I 1490/// EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I 1491/// EXPAND_EXPRESSION Complete internal or user defined function/variable 1492/// names in expressions, eg :while s^I 1493/// EXPAND_ENV_VARS Complete environment variable names 1494/// EXPAND_USER Complete user names 1495/// EXPAND_PATTERN_IN_BUF Complete pattern in '/', '?', ':s', ':g', etc. 1496void set_expand_context (expand_T * xp ) 1497{ 1498CmdlineInfo * const ccline = get_cmdline_info (); 1499 1500// Handle search commands: '/' or '?' 1501if ((ccline -> cmdfirstc == '/' || ccline -> cmdfirstc == '?' ) 1502&& may_expand_pattern ) { 1503xp -> xp_context = EXPAND_PATTERN_IN_BUF ; 1504xp -> xp_search_dir = (ccline -> cmdfirstc == '/' ) ?FORWARD :BACKWARD ; 1505xp -> xp_pattern = ccline -> cmdbuff ; 1506xp -> xp_pattern_len = (size_t )ccline -> cmdpos ; 1507Search .first_line = 0 ;// Search entire buffer 1508return ; 1509 } 1510 1511// Only handle ':', '>', or '=' command-lines, or expression input 1512if (ccline -> cmdfirstc != ':' 1513&& ccline -> cmdfirstc != '>' && ccline -> cmdfirstc != '=' 1514&& !ccline -> input_fn ) { 1515xp -> xp_context = EXPAND_NOTHING ; 1516return ; 1517 } 1518 1519// Fallback to command-line expansion 1520set_cmd_context (xp ,ccline -> cmdbuff ,ccline -> cmdlen ,ccline -> cmdpos , true); 1521} 1522 1523/// Sets the index of a built-in or user defined command "cmd" in eap->cmdidx. 1524/// For user defined commands, the completion context is set in "xp" and the 1525/// completion flags in "complp". 1526/// 1527/// @return a pointer to the text after the command or NULL for failure. 1528static const char * set_cmd_index (const char * cmd ,exarg_T * eap ,expand_T * xp ,int * complp ) 1529{ 1530const char * p = NULL ; 1531const bool fuzzy = cmdline_fuzzy_complete (cmd ); 1532 1533// Isolate the command and search for it in the command table. 1534// Exceptions: 1535// - the 'k' command can directly be followed by any character, but do 1536// accept "keepmarks", "keepalt" and "keepjumps". Bypass also when 1537// 'ignorecase' is set so a lowercase ":kz" still completes a user 1538// command like :Kz, and for fuzzy matching as that can find 1539// matches anywhere in the command name. 1540// - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r' 1541if (!fuzzy && !p_ic && (* cmd == 'k' && cmd [1 ]!= 'e' )) { 1542eap -> cmdidx = CMD_k ; 1543p = cmd + 1 ; 1544 }else { 1545p = cmd ; 1546while (ASCII_ISALPHA (* p )|| * p == '*' ) {// Allow * wild card 1547p ++ ; 1548 } 1549// a user command may contain digits 1550if (ASCII_ISUPPER (cmd [0 ])) { 1551while (ASCII_ISALNUM (* p )|| * p == '*' ) { 1552p ++ ; 1553 } 1554 } 1555// for python 3.x: ":py3*" commands completion 1556if (cmd [0 ]== 'p' && cmd [1 ]== 'y' && p == cmd + 2 && * p == '3' ) { 1557p ++ ; 1558while (ASCII_ISALPHA (* p )|| * p == '*' ) { 1559p ++ ; 1560 } 1561 } 1562// check for non-alpha command 1563if (p == cmd && vim_strchr ("@*!=><&~#" , (uint8_t )(* p ))!= NULL ) { 1564p ++ ; 1565 } 1566size_t len = (size_t )(p - cmd ); 1567 1568if (len == 0 ) { 1569xp -> xp_context = EXPAND_UNSUCCESSFUL ; 1570return NULL ; 1571 } 1572 1573eap -> cmdidx = excmd_get_cmdidx (cmd ,len ); 1574 1575// User defined commands support alphanumeric characters. 1576// Also when doing fuzzy expansion for non-shell commands, support 1577// alphanumeric characters. 1578if ((cmd [0 ] >='A' && cmd [0 ] <='Z' ) 1579|| (fuzzy && eap -> cmdidx != CMD_bang && * p != NUL )) { 1580while (ASCII_ISALNUM (* p )|| * p == '*' ) {// Allow * wild card 1581p ++ ; 1582 } 1583 } 1584 } 1585 1586// If the cursor is touching the command, and it ends in an alphanumeric 1587// character, complete the command name. 1588if (* p == NUL && ASCII_ISALNUM (p [-1 ])) { 1589return NULL ; 1590 } 1591 1592if (eap -> cmdidx == CMD_SIZE ) { 1593if (* cmd == 's' && vim_strchr ("cgriI" , (uint8_t )cmd [1 ])!= NULL ) { 1594eap -> cmdidx = CMD_substitute ; 1595p = cmd + 1 ; 1596 }else if (cmd [0 ] >='A' && cmd [0 ] <='Z' ) { 1597eap -> cmd = (char * )cmd ; 1598p = find_ucmd (eap , (char * )p ,NULL ,xp ,complp ); 1599if (p == NULL ) { 1600eap -> cmdidx = CMD_SIZE ;// Ambiguous user command. 1601 } 1602 } 1603 } 1604if (eap -> cmdidx == CMD_SIZE ) { 1605// Not still touching the command and it was an illegal one 1606xp -> xp_context = EXPAND_UNSUCCESSFUL ; 1607return NULL ; 1608 } 1609 1610return p ; 1611} 1612 1613/// Set the completion context for a command argument with wild card characters. 1614static void set_context_for_wildcard_arg (exarg_T * eap ,const char * arg ,bool usefilter , 1615expand_T * xp ,int * complp ) 1616{ 1617bool in_quote = false; 1618const char * bow = NULL ;// Beginning of word. 1619size_t len = 0 ; 1620 1621// Allow spaces within back-quotes to count as part of the argument 1622// being expanded. 1623xp -> xp_pattern = skipwhite (arg ); 1624const char * p = xp -> xp_pattern ; 1625while (* p != NUL ) { 1626int c = utf_ptr2char (p ); 1627if (c == '\\' && p [1 ]!= NUL ) { 1628p ++ ; 1629 }else if (c == '`' ) { 1630if (!in_quote ) { 1631xp -> xp_pattern = (char * )p ; 1632bow = p + 1 ; 1633 } 1634in_quote = !in_quote ; 1635// An argument can contain just about everything, except 1636// characters that end the command and white space. 1637 }else if (c == '|' || c == '\n' || c == '"' 1638|| (ascii_iswhite (c )&& (!(eap != NULL && (eap -> argt & EX_NOSPC )) 1639|| usefilter ))) { 1640len = 0 ;// avoid getting stuck when space is in 'isfname' 1641while (* p != NUL ) { 1642c = utf_ptr2char (p ); 1643if (c == '`' || vim_isfilec_or_wc (c )) { 1644break ; 1645 } 1646len = (size_t )utfc_ptr2len (p ); 1647MB_PTR_ADV (p ); 1648 } 1649if (in_quote ) { 1650bow = p ; 1651 }else { 1652xp -> xp_pattern = (char * )p ; 1653 } 1654p -= len ; 1655 } 1656MB_PTR_ADV (p ); 1657 } 1658 1659// If we are still inside the quotes, and we passed a space, just 1660// expand from there. 1661if (bow != NULL && in_quote ) { 1662xp -> xp_pattern = (char * )bow ; 1663 } 1664xp -> xp_context = EXPAND_FILES ; 1665 1666// For a shell command more chars need to be escaped. 1667if (usefilter 1668|| (eap != NULL && (eap -> cmdidx == CMD_bang || eap -> cmdidx == CMD_terminal )) 1669|| * complp == EXPAND_SHELLCMDLINE ) { 1670#ifndef BACKSLASH_IN_FILENAME 1671xp -> xp_shell = true; 1672#endif 1673// When still after the command name expand executables. 1674if (xp -> xp_pattern == skipwhite (arg )) { 1675xp -> xp_context = EXPAND_SHELLCMD ; 1676 } 1677 } 1678 1679// Check for environment variable. 1680if (* xp -> xp_pattern == '$' ) { 1681for (p = xp -> xp_pattern + 1 ;* p != NUL ;p ++ ) { 1682if (!vim_isIDc ((uint8_t )(* p ))) { 1683break ; 1684 } 1685 } 1686if (* p == NUL ) { 1687xp -> xp_context = EXPAND_ENV_VARS ; 1688xp -> xp_pattern ++ ; 1689// Avoid that the assignment uses EXPAND_FILES again. 1690if (* complp != EXPAND_USER_DEFINED && * complp != EXPAND_USER_LIST ) { 1691* complp = EXPAND_ENV_VARS ; 1692 } 1693 } 1694 } 1695// Check for user names. 1696if (* xp -> xp_pattern == '~' ) { 1697for (p = xp -> xp_pattern + 1 ;* p != NUL && * p != '/' ;p ++ ) {} 1698// Complete ~user only if it partially matches a user name. 1699// A full match ~user<Tab> will be replaced by user's home 1700// directory i.e. something like ~user<Tab> -> /home/user/ 1701if (* p == NUL && p > xp -> xp_pattern + 1 && match_user (xp -> xp_pattern + 1 ) >=1 ) { 1702xp -> xp_context = EXPAND_USER ; 1703xp -> xp_pattern ++ ; 1704 } 1705 } 1706} 1707 1708/// Set the completion context for the "++opt=arg" argument. Always returns NULL. 1709static const char * set_context_in_argopt (expand_T * xp ,const char * arg ) 1710{ 1711char * p = vim_strchr (arg ,'=' ); 1712if (p == NULL ) { 1713xp -> xp_pattern = (char * )arg ; 1714 }else { 1715xp -> xp_pattern = p + 1 ; 1716 } 1717 1718xp -> xp_context = EXPAND_ARGOPT ; 1719return NULL ; 1720} 1721 1722/// Set the completion context for the :filter command. Returns a pointer to the 1723/// next command after the :filter command. 1724static const char * set_context_in_filter_cmd (expand_T * xp ,const char * arg ) 1725{ 1726if (* arg != NUL ) { 1727arg = skip_vimgrep_pat ((char * )arg ,NULL ,NULL ); 1728 } 1729if (arg == NULL || * arg == NUL ) { 1730xp -> xp_context = EXPAND_NOTHING ; 1731return NULL ; 1732 } 1733return skipwhite (arg ); 1734} 1735 1736/// Set the completion context for the :match command. Returns a pointer to the 1737/// next command after the :match command. 1738static const char * set_context_in_match_cmd (expand_T * xp ,const char * arg ) 1739{ 1740if (* arg == NUL || !ends_excmd (* arg )) { 1741// also complete "None" 1742set_context_in_echohl_cmd (xp ,arg ); 1743arg = skipwhite (skiptowhite (arg )); 1744if (* arg != NUL ) { 1745xp -> xp_context = EXPAND_NOTHING ; 1746arg = skip_regexp ((char * )arg + 1 , (uint8_t )(* arg ),p_magic ); 1747 } 1748 } 1749return find_nextcmd (arg ); 1750} 1751 1752/// Returns a pointer to the next command after a :global or a :v command. 1753/// Returns NULL if there is no next command. 1754static const char * find_cmd_after_global_cmd (const char * arg ) 1755{ 1756const int delim = (uint8_t )(* arg );// Get the delimiter. 1757if (delim ) { 1758arg ++ ;// Skip delimiter if there is one. 1759 } 1760 1761while (arg [0 ]!= NUL && (uint8_t )arg [0 ]!= delim ) { 1762if (arg [0 ]== '\\' && arg [1 ]!= NUL ) { 1763arg ++ ; 1764 } 1765arg ++ ; 1766 } 1767if (arg [0 ]!= NUL ) { 1768return arg + 1 ; 1769 } 1770 1771return NULL ; 1772} 1773 1774/// Returns a pointer to the next command after a :substitute or a :& command. 1775/// Returns NULL if there is no next command. 1776static const char * find_cmd_after_substitute_cmd (const char * arg ) 1777{ 1778const int delim = (uint8_t )(* arg ); 1779if (delim ) { 1780// Skip "from" part. 1781arg ++ ; 1782arg = skip_regexp ((char * )arg ,delim ,p_magic ); 1783 1784if (arg [0 ]!= NUL && arg [0 ]== delim ) { 1785// Skip "to" part. 1786arg ++ ; 1787while (arg [0 ]!= NUL && (uint8_t )arg [0 ]!= delim ) { 1788if (arg [0 ]== '\\' && arg [1 ]!= NUL ) { 1789arg ++ ; 1790 } 1791arg ++ ; 1792 } 1793if (arg [0 ]!= NUL ) {// Skip delimiter. 1794arg ++ ; 1795 } 1796 } 1797 } 1798while (arg [0 ]&& strchr ("|\"#" ,arg [0 ])== NULL ) { 1799arg ++ ; 1800 } 1801if (arg [0 ]!= NUL ) { 1802return arg ; 1803 } 1804 1805return NULL ; 1806} 1807 1808/// Returns a pointer to the next command after a :isearch/:dsearch/:ilist 1809/// :dlist/:ijump/:psearch/:djump/:isplit/:dsplit command. 1810/// Returns NULL if there is no next command. 1811static const char * find_cmd_after_isearch_cmd (expand_T * xp ,const char * arg ) 1812{ 1813// Skip count. 1814arg = skipwhite (skipdigits (arg )); 1815if (* arg != '/' ) { 1816return NULL ; 1817 } 1818 1819// Match regexp, not just whole words. 1820for (++ arg ;* arg && * arg != '/' ;arg ++ ) { 1821if (* arg == '\\' && arg [1 ]!= NUL ) { 1822arg ++ ; 1823 } 1824 } 1825if (* arg ) { 1826arg = skipwhite (arg + 1 ); 1827 1828// Check for trailing illegal characters. 1829if (* arg == NUL || strchr ("|\"\n" ,* arg )== NULL ) { 1830xp -> xp_context = EXPAND_NOTHING ; 1831 }else { 1832return arg ; 1833 } 1834 } 1835 1836return NULL ; 1837} 1838 1839/// Set the completion context for the :unlet command. Always returns NULL. 1840static const char * set_context_in_unlet_cmd (expand_T * xp ,const char * arg ) 1841{ 1842// NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43 1843while ((xp -> xp_pattern = (char * )strchr (arg ,' ' ))!= NULL ) { 1844arg = xp -> xp_pattern + 1 ; 1845 } 1846 1847xp -> xp_context = EXPAND_USER_VARS ; 1848xp -> xp_pattern = (char * )arg ; 1849 1850if (* xp -> xp_pattern == '$' ) { 1851xp -> xp_context = EXPAND_ENV_VARS ; 1852xp -> xp_pattern ++ ; 1853 } 1854 1855return NULL ; 1856} 1857 1858/// Set the completion context for the :language command. Always returns NULL. 1859static const char * set_context_in_lang_cmd (expand_T * xp ,const char * arg ) 1860{ 1861const char * p = skiptowhite (arg ); 1862if (* p == NUL ) { 1863xp -> xp_context = EXPAND_LANGUAGE ; 1864xp -> xp_pattern = (char * )arg ; 1865 }else { 1866if (strncmp (arg ,"messages" , (size_t )(p - arg ))== 0 1867|| strncmp (arg ,"ctype" , (size_t )(p - arg ))== 0 1868|| strncmp (arg ,"time" , (size_t )(p - arg ))== 0 1869|| strncmp (arg ,"collate" , (size_t )(p - arg ))== 0 ) { 1870xp -> xp_context = EXPAND_LOCALES ; 1871xp -> xp_pattern = skipwhite (p ); 1872 }else { 1873xp -> xp_context = EXPAND_NOTHING ; 1874 } 1875 } 1876 1877return NULL ; 1878} 1879 1880static enum { 1881EXP_FILETYPECMD_ALL ,///< expand all :filetype values 1882EXP_FILETYPECMD_PLUGIN ,///< expand plugin on off 1883EXP_FILETYPECMD_INDENT ,///< expand indent on off 1884EXP_FILETYPECMD_ONOFF ,///< expand on off 1885}filetype_expand_what ; 1886 1887enum { 1888EXPAND_FILETYPECMD_PLUGIN = 0x01 , 1889EXPAND_FILETYPECMD_INDENT = 0x02 , 1890EXPAND_FILETYPECMD_ONOFF = 0x04 , 1891}; 1892 1893static enum { 1894EXP_BREAKPT_ADD ,///< expand ":breakadd" sub-commands 1895EXP_BREAKPT_DEL ,///< expand ":breakdel" sub-commands 1896EXP_PROFDEL ,///< expand ":profdel" sub-commands 1897}breakpt_expand_what ; 1898 1899/// Set the completion context for the :breakadd command. Always returns NULL. 1900static const char * set_context_in_breakadd_cmd (expand_T * xp ,const char * arg ,cmdidx_T cmdidx ) 1901{ 1902xp -> xp_context = EXPAND_BREAKPOINT ; 1903xp -> xp_pattern = (char * )arg ; 1904 1905if (cmdidx == CMD_breakadd ) { 1906breakpt_expand_what = EXP_BREAKPT_ADD ; 1907 }else if (cmdidx == CMD_breakdel ) { 1908breakpt_expand_what = EXP_BREAKPT_DEL ; 1909 }else { 1910breakpt_expand_what = EXP_PROFDEL ; 1911 } 1912 1913const char * p = skipwhite (arg ); 1914if (* p == NUL ) { 1915return NULL ; 1916 } 1917const char * subcmd_start = p ; 1918 1919if (strncmp ("file " ,p ,5 )== 0 || strncmp ("func " ,p ,5 )== 0 ) { 1920// :breakadd file [lnum] <filename> 1921// :breakadd func [lnum] <funcname> 1922p += 4 ; 1923p = skipwhite (p ); 1924 1925// skip line number (if specified) 1926if (ascii_isdigit (* p )) { 1927p = skipdigits (p ); 1928if (* p != ' ' ) { 1929xp -> xp_context = EXPAND_NOTHING ; 1930return NULL ; 1931 } 1932p = skipwhite (p ); 1933 } 1934if (strncmp ("file" ,subcmd_start ,4 )== 0 ) { 1935xp -> xp_context = EXPAND_FILES ; 1936 }else { 1937xp -> xp_context = EXPAND_USER_FUNC ; 1938 } 1939xp -> xp_pattern = (char * )p ; 1940 }else if (strncmp ("expr " ,p ,5 )== 0 ) { 1941// :breakadd expr <expression> 1942xp -> xp_context = EXPAND_EXPRESSION ; 1943xp -> xp_pattern = skipwhite (p + 5 ); 1944 } 1945 1946return NULL ; 1947} 1948 1949static const char * set_context_in_scriptnames_cmd (expand_T * xp ,const char * arg ) 1950{ 1951xp -> xp_context = EXPAND_NOTHING ; 1952xp -> xp_pattern = NULL ; 1953 1954char * p = skipwhite (arg ); 1955if (ascii_isdigit (* p )) { 1956return NULL ; 1957 } 1958 1959xp -> xp_context = EXPAND_SCRIPTNAMES ; 1960xp -> xp_pattern = p ; 1961 1962return NULL ; 1963} 1964 1965/// Set the completion context for the :filetype command. Always returns NULL. 1966static const char * set_context_in_filetype_cmd (expand_T * xp ,const char * arg ) 1967{ 1968xp -> xp_context = EXPAND_FILETYPECMD ; 1969xp -> xp_pattern = (char * )arg ; 1970filetype_expand_what = EXP_FILETYPECMD_ALL ; 1971 1972char * p = skipwhite (arg ); 1973if (* p == NUL ) { 1974return NULL ; 1975 } 1976 1977int val = 0 ; 1978 1979while (true) { 1980if (strncmp (p ,"plugin" ,6 )== 0 && ascii_iswhite (p [6 ])) { 1981val |=EXPAND_FILETYPECMD_PLUGIN ; 1982p = skipwhite (p + 6 ); 1983continue ; 1984 } 1985if (strncmp (p ,"indent" ,6 )== 0 && ascii_iswhite (p [6 ])) { 1986val |=EXPAND_FILETYPECMD_INDENT ; 1987p = skipwhite (p + 6 ); 1988continue ; 1989 } 1990break ; 1991 } 1992 1993if ((val & EXPAND_FILETYPECMD_PLUGIN )&& (val & EXPAND_FILETYPECMD_INDENT )) { 1994filetype_expand_what = EXP_FILETYPECMD_ONOFF ; 1995 }else if ((val & EXPAND_FILETYPECMD_PLUGIN )) { 1996filetype_expand_what = EXP_FILETYPECMD_INDENT ; 1997 }else if ((val & EXPAND_FILETYPECMD_INDENT )) { 1998filetype_expand_what = EXP_FILETYPECMD_PLUGIN ; 1999 } 2000 2001xp -> xp_pattern = p ; 2002 2003return NULL ; 2004} 2005 2006/// Sets the completion context for commands that involve a search pattern 2007/// and a line range (e.g., :s, :g, :v). 2008static void set_context_with_pattern (expand_T * xp ) 2009{ 2010CmdlineInfo * ccline = get_cmdline_info (); 2011 2012emsg_off ++ ; 2013int skiplen = 0 ; 2014int dummy ,patlen ; 2015bool magic = p_magic ; 2016int retval = parse_pattern_and_range (& pre_incsearch_pos ,& dummy ,& skiplen ,& patlen ,& magic ); 2017emsg_off -- ; 2018 2019// Check if cursor is within search pattern 2020if (!retval || ccline -> cmdpos <=skiplen || ccline -> cmdpos > skiplen + patlen ) { 2021return ; 2022 } 2023 2024xp -> xp_pattern = ccline -> cmdbuff + skiplen ; 2025xp -> xp_pattern_len = (size_t )(ccline -> cmdpos - skiplen ); 2026xp -> xp_context = EXPAND_PATTERN_IN_BUF ; 2027xp -> xp_search_dir = FORWARD ; 2028} 2029 2030/// Set the completion context in "xp" for command "cmd" with index "cmdidx". 2031/// The argument to the command is "arg" and the argument flags is "argt". 2032/// For user-defined commands and for environment variables, "context" has the 2033/// completion type. 2034/// 2035/// @return a pointer to the next command, or NULL if there is no next command. 2036static const char * set_context_by_cmdname (const char * cmd ,cmdidx_T cmdidx ,expand_T * xp , 2037const char * arg ,uint32_t argt ,int context ,bool forceit ) 2038{ 2039const char * nextcmd ; 2040 2041switch (cmdidx ) { 2042case CMD_find : 2043case CMD_sfind : 2044case CMD_tabfind : 2045if (xp -> xp_context == EXPAND_FILES ) { 2046xp -> xp_context = get_findfunc ()-> type != 2047kCallbackNone ?EXPAND_FINDFUNC :EXPAND_FILES_IN_PATH ; 2048 } 2049break ; 2050case CMD_bcd : 2051case CMD_bchdir : 2052case CMD_cd : 2053case CMD_chdir : 2054case CMD_lcd : 2055case CMD_lchdir : 2056case CMD_tcd : 2057case CMD_tchdir : 2058if (xp -> xp_context == EXPAND_FILES ) { 2059xp -> xp_context = EXPAND_DIRS_IN_CDPATH ; 2060 } 2061break ; 2062case CMD_help : 2063xp -> xp_context = EXPAND_HELP ; 2064xp -> xp_pattern = (char * )arg ; 2065break ; 2066 2067// Command modifiers: return the argument. 2068// Also for commands with an argument that is a command. 2069case CMD_aboveleft : 2070case CMD_argdo : 2071case CMD_belowright : 2072case CMD_botright : 2073case CMD_browse : 2074case CMD_bufdo : 2075case CMD_cdo : 2076case CMD_cfdo : 2077case CMD_confirm : 2078case CMD_debug : 2079case CMD_folddoclosed : 2080case CMD_folddoopen : 2081case CMD_hide : 2082case CMD_horizontal : 2083case CMD_keepalt : 2084case CMD_keepjumps : 2085case CMD_keepmarks : 2086case CMD_keeppatterns : 2087case CMD_ldo : 2088case CMD_leftabove : 2089case CMD_lfdo : 2090case CMD_lockmarks : 2091case CMD_noautocmd : 2092case CMD_noswapfile : 2093case CMD_restart : 2094case CMD_rightbelow : 2095case CMD_sandbox : 2096case CMD_silent : 2097case CMD_tab : 2098case CMD_tabdo : 2099case CMD_topleft : 2100case CMD_unsilent : 2101case CMD_verbose : 2102case CMD_vertical : 2103case CMD_windo : 2104return arg ; 2105 2106case CMD_filter : 2107return set_context_in_filter_cmd (xp ,arg ); 2108 2109case CMD_match : 2110return set_context_in_match_cmd (xp ,arg ); 2111 2112// All completion for the +cmdline_compl feature goes here. 2113 2114case CMD_command : 2115return set_context_in_user_cmd (xp ,arg ); 2116 2117case CMD_delcommand : 2118xp -> xp_context = EXPAND_USER_COMMANDS ; 2119xp -> xp_pattern = (char * )arg ; 2120break ; 2121 2122case CMD_global : 2123case CMD_vglobal : 2124nextcmd = find_cmd_after_global_cmd (arg ); 2125if (!nextcmd && may_expand_pattern ) { 2126set_context_with_pattern (xp ); 2127 } 2128return nextcmd ; 2129 2130case CMD_and : 2131case CMD_substitute : 2132nextcmd = find_cmd_after_substitute_cmd (arg ); 2133if (!nextcmd && may_expand_pattern ) { 2134set_context_with_pattern (xp ); 2135 } 2136return nextcmd ; 2137 2138case CMD_isearch : 2139case CMD_dsearch : 2140case CMD_ilist : 2141case CMD_dlist : 2142case CMD_ijump : 2143case CMD_psearch : 2144case CMD_djump : 2145case CMD_isplit : 2146case CMD_dsplit : 2147return find_cmd_after_isearch_cmd (xp ,arg ); 2148case CMD_autocmd : 2149return aucmd_set_expand_context (xp , (char * )arg , false); 2150 2151case CMD_doautocmd : 2152case CMD_doautoall : 2153return aucmd_set_expand_context (xp , (char * )arg , true); 2154case CMD_set : 2155set_context_in_set_cmd (xp , (char * )arg ,0 ); 2156break ; 2157case CMD_setglobal : 2158set_context_in_set_cmd (xp , (char * )arg ,OPT_GLOBAL ); 2159break ; 2160case CMD_setlocal : 2161set_context_in_set_cmd (xp , (char * )arg ,OPT_LOCAL ); 2162break ; 2163case CMD_tag : 2164case CMD_stag : 2165case CMD_ptag : 2166case CMD_ltag : 2167case CMD_tselect : 2168case CMD_stselect : 2169case CMD_ptselect : 2170case CMD_tjump : 2171case CMD_stjump : 2172case CMD_ptjump : 2173if (wop_flags & kOptWopFlagTagfile ) { 2174xp -> xp_context = EXPAND_TAGS_LISTFILES ; 2175 }else { 2176xp -> xp_context = EXPAND_TAGS ; 2177 } 2178xp -> xp_pattern = (char * )arg ; 2179break ; 2180case CMD_augroup : 2181xp -> xp_context = EXPAND_AUGROUP ; 2182xp -> xp_pattern = (char * )arg ; 2183break ; 2184case CMD_syntax : 2185set_context_in_syntax_cmd (xp ,arg ); 2186break ; 2187case CMD_const : 2188case CMD_let : 2189case CMD_if : 2190case CMD_elseif : 2191case CMD_while : 2192case CMD_for : 2193case CMD_echo : 2194case CMD_echon : 2195case CMD_execute : 2196case CMD_echomsg : 2197case CMD_echoerr : 2198case CMD_call : 2199case CMD_return : 2200case CMD_cexpr : 2201case CMD_caddexpr : 2202case CMD_cgetexpr : 2203case CMD_lexpr : 2204case CMD_laddexpr : 2205case CMD_lgetexpr : 2206set_context_for_expression (xp , (char * )arg ,cmdidx ); 2207break ; 2208 2209case CMD_unlet : 2210return set_context_in_unlet_cmd (xp ,arg ); 2211case CMD_function : 2212case CMD_delfunction : 2213xp -> xp_context = EXPAND_USER_FUNC ; 2214xp -> xp_pattern = (char * )arg ; 2215break ; 2216 2217case CMD_echohl : 2218set_context_in_echohl_cmd (xp ,arg ); 2219break ; 2220case CMD_highlight : 2221set_context_in_highlight_cmd (xp ,arg ); 2222break ; 2223case CMD_sign : 2224set_context_in_sign_cmd (xp , (char * )arg ); 2225break ; 2226case CMD_bdelete : 2227case CMD_bwipeout : 2228case CMD_bunload : 2229// NOLINTNEXTLINE(*-casting): remove once CI uses glibc 2.43 2230while ((xp -> xp_pattern = (char * )strchr (arg ,' ' ))!= NULL ) { 2231arg = xp -> xp_pattern + 1 ; 2232 } 2233FALLTHROUGH ; 2234case CMD_buffer : 2235case CMD_sbuffer : 2236case CMD_pbuffer : 2237case CMD_checktime : 2238xp -> xp_context = EXPAND_BUFFERS ; 2239xp -> xp_pattern = (char * )arg ; 2240break ; 2241case CMD_diffget : 2242case CMD_diffput : 2243// If current buffer is in diff mode, complete buffer names 2244// which are in diff mode, and different than current buffer. 2245xp -> xp_context = EXPAND_DIFF_BUFFERS ; 2246xp -> xp_pattern = (char * )arg ; 2247break ; 2248 2249case CMD_USER : 2250case CMD_USER_BUF : 2251return set_context_in_user_cmdarg (cmd ,arg ,argt ,context ,xp ,forceit ); 2252 2253case CMD_map : 2254case CMD_noremap : 2255case CMD_nmap : 2256case CMD_nnoremap : 2257case CMD_vmap : 2258case CMD_vnoremap : 2259case CMD_omap : 2260case CMD_onoremap : 2261case CMD_imap : 2262case CMD_inoremap : 2263case CMD_cmap : 2264case CMD_cnoremap : 2265case CMD_lmap : 2266case CMD_lnoremap : 2267case CMD_smap : 2268case CMD_snoremap : 2269case CMD_xmap : 2270case CMD_xnoremap : 2271return set_context_in_map_cmd (xp , (char * )cmd , (char * )arg ,forceit , false, 2272 false,cmdidx ); 2273case CMD_unmap : 2274case CMD_nunmap : 2275case CMD_vunmap : 2276case CMD_ounmap : 2277case CMD_iunmap : 2278case CMD_cunmap : 2279case CMD_lunmap : 2280case CMD_sunmap : 2281case CMD_xunmap : 2282return set_context_in_map_cmd (xp , (char * )cmd , (char * )arg ,forceit , false, 2283 true,cmdidx ); 2284case CMD_mapclear : 2285case CMD_nmapclear : 2286case CMD_vmapclear : 2287case CMD_omapclear : 2288case CMD_imapclear : 2289case CMD_cmapclear : 2290case CMD_lmapclear : 2291case CMD_smapclear : 2292case CMD_xmapclear : 2293xp -> xp_context = EXPAND_MAPCLEAR ; 2294xp -> xp_pattern = (char * )arg ; 2295break ; 2296 2297case CMD_abbreviate : 2298case CMD_noreabbrev : 2299case CMD_cabbrev : 2300case CMD_cnoreabbrev : 2301case CMD_iabbrev : 2302case CMD_inoreabbrev : 2303return set_context_in_map_cmd (xp , (char * )cmd , (char * )arg ,forceit , true, 2304 false,cmdidx ); 2305case CMD_unabbreviate : 2306case CMD_cunabbrev : 2307case CMD_iunabbrev : 2308return set_context_in_map_cmd (xp , (char * )cmd , (char * )arg ,forceit , true, 2309 true,cmdidx ); 2310case CMD_menu : 2311case CMD_noremenu : 2312case CMD_unmenu : 2313case CMD_amenu : 2314case CMD_anoremenu : 2315case CMD_aunmenu : 2316case CMD_nmenu : 2317case CMD_nnoremenu : 2318case CMD_nunmenu : 2319case CMD_vmenu : 2320case CMD_vnoremenu : 2321case CMD_vunmenu : 2322case CMD_omenu : 2323case CMD_onoremenu : 2324case CMD_ounmenu : 2325case CMD_imenu : 2326case CMD_inoremenu : 2327case CMD_iunmenu : 2328case CMD_cmenu : 2329case CMD_cnoremenu : 2330case CMD_cunmenu : 2331case CMD_tlmenu : 2332case CMD_tlnoremenu : 2333case CMD_tlunmenu : 2334case CMD_tmenu : 2335case CMD_tunmenu : 2336case CMD_popup : 2337case CMD_emenu : 2338return set_context_in_menu_cmd (xp ,cmd , (char * )arg ,forceit ); 2339 2340case CMD_colorscheme : 2341xp -> xp_context = EXPAND_COLORS ; 2342xp -> xp_pattern = (char * )arg ; 2343break ; 2344 2345case CMD_compiler : 2346xp -> xp_context = EXPAND_COMPILER ; 2347xp -> xp_pattern = (char * )arg ; 2348break ; 2349 2350case CMD_ownsyntax : 2351xp -> xp_context = EXPAND_OWNSYNTAX ; 2352xp -> xp_pattern = (char * )arg ; 2353break ; 2354 2355case CMD_setfiletype : 2356xp -> xp_context = EXPAND_FILETYPE ; 2357xp -> xp_pattern = (char * )arg ; 2358break ; 2359 2360case CMD_packadd : 2361xp -> xp_context = EXPAND_PACKADD ; 2362xp -> xp_pattern = (char * )arg ; 2363break ; 2364 2365case CMD_runtime : 2366set_context_in_runtime_cmd (xp ,arg ); 2367break ; 2368 2369case CMD_language : 2370return set_context_in_lang_cmd (xp ,arg ); 2371 2372case CMD_profile : 2373set_context_in_profile_cmd (xp ,arg ); 2374break ; 2375case CMD_checkhealth : 2376xp -> xp_context = EXPAND_CHECKHEALTH ; 2377break ; 2378 2379case CMD_marks : 2380xp -> xp_context = EXPAND_MARKS ; 2381break ; 2382 2383case CMD_log : 2384xp -> xp_context = EXPAND_LOG ; 2385break ; 2386 2387case CMD_lsp : 2388xp -> xp_context = EXPAND_LSP ; 2389break ; 2390 2391case CMD_packdel : 2392xp -> xp_context = EXPAND_PACKDEL ; 2393break ; 2394 2395case CMD_packupdate : 2396xp -> xp_context = EXPAND_PACKUPDATE ; 2397break ; 2398 2399case CMD_retab : 2400xp -> xp_context = EXPAND_RETAB ; 2401xp -> xp_pattern = (char * )arg ; 2402break ; 2403 2404case CMD_messages : 2405xp -> xp_context = EXPAND_MESSAGES ; 2406xp -> xp_pattern = (char * )arg ; 2407break ; 2408 2409case CMD_history : 2410xp -> xp_context = EXPAND_HISTORY ; 2411xp -> xp_pattern = (char * )arg ; 2412break ; 2413case CMD_syntime : 2414xp -> xp_context = EXPAND_SYNTIME ; 2415xp -> xp_pattern = (char * )arg ; 2416break ; 2417 2418case CMD_argdelete : 2419while ((xp -> xp_pattern = vim_strchr (arg ,' ' ))!= NULL ) { 2420arg = (xp -> xp_pattern + 1 ); 2421 } 2422xp -> xp_context = EXPAND_ARGLIST ; 2423xp -> xp_pattern = (char * )arg ; 2424break ; 2425 2426case CMD_breakadd : 2427case CMD_profdel : 2428case CMD_breakdel : 2429return set_context_in_breakadd_cmd (xp ,arg ,cmdidx ); 2430 2431case CMD_scriptnames : 2432return set_context_in_scriptnames_cmd (xp ,arg ); 2433 2434case CMD_filetype : 2435return set_context_in_filetype_cmd (xp ,arg ); 2436 2437case CMD_lua : 2438case CMD_equal : 2439xp -> xp_context = EXPAND_LUA ; 2440break ; 2441 2442default : 2443break ; 2444 } 2445return NULL ; 2446} 2447 2448/// This is all pretty much copied from do_one_cmd(), with all the extra stuff 2449/// we don't need/want deleted. Maybe this could be done better if we didn't 2450/// repeat all this stuff. The only problem is that they may not stay 2451/// perfectly compatible with each other, but then the command line syntax 2452/// probably won't change that much -- webb. 2453/// 2454/// @param buff buffer for command string 2455static const char * set_one_cmd_context (expand_T * xp ,const char * buff ) 2456{ 2457size_t len = 0 ; 2458exarg_T ea ; 2459int context = EXPAND_NOTHING ; 2460bool forceit = false; 2461bool usefilter = false;// Filter instead of file name. 2462 2463ExpandInit (xp ); 2464xp -> xp_pattern = (char * )buff ; 2465xp -> xp_line = (char * )buff ; 2466xp -> xp_context = EXPAND_COMMANDS ;// Default until we get past command 2467ea .argt = 0 ; 2468 2469// 1. skip comment lines and leading space, colons or bars 2470const char * cmd ; 2471for (cmd = buff ;vim_strchr (" \t:|" , (uint8_t )(* cmd ))!= NULL ;cmd ++ ) {} 2472xp -> xp_pattern = (char * )cmd ; 2473 2474if (* cmd == NUL ) { 2475return NULL ; 2476 } 2477if (* cmd == '"' ) {// ignore comment lines 2478xp -> xp_context = EXPAND_NOTHING ; 2479return NULL ; 2480 } 2481 2482// 3. skip over a range specifier of the form: addr [,addr] [;addr] .. 2483cmd = skip_range (cmd ,& xp -> xp_context ); 2484xp -> xp_pattern = (char * )cmd ; 2485if (* cmd == NUL ) { 2486return NULL ; 2487 } 2488if (* cmd == '"' ) { 2489xp -> xp_context = EXPAND_NOTHING ; 2490return NULL ; 2491 } 2492 2493if (* cmd == '|' || * cmd == '\n' ) { 2494return cmd + 1 ;// There's another command 2495 } 2496 2497// Get the command index. 2498const char * p = set_cmd_index (cmd ,& ea ,xp ,& context ); 2499if (p == NULL ) { 2500return NULL ; 2501 } 2502 2503xp -> xp_context = EXPAND_NOTHING ;// Default now that we're past command 2504 2505if (* p == '!' ) {// forced commands 2506forceit = true; 2507p ++ ; 2508 } 2509 2510// 6. parse arguments 2511if (!IS_USER_CMDIDX (ea .cmdidx )) { 2512ea .argt = excmd_get_argt (ea .cmdidx ); 2513 } 2514 2515const char * arg = skipwhite (p ); 2516 2517// Does command allow "++argopt" argument? 2518if (ea .argt & EX_ARGOPT ) { 2519while (* arg != NUL && strncmp (arg ,"++" ,2 )== 0 ) { 2520p = arg + 2 ; 2521while (* p && !ascii_isspace (* p )) { 2522MB_PTR_ADV (p ); 2523 } 2524 2525// Still touching the command after "++"? 2526if (* p == NUL ) { 2527if (ea .argt & EX_ARGOPT ) { 2528return set_context_in_argopt (xp ,arg + 2 ); 2529 } 2530 } 2531 2532arg = skipwhite (p ); 2533 } 2534 } 2535 2536if (ea .cmdidx == CMD_write || ea .cmdidx == CMD_update ) { 2537if (* arg == '>' ) {// append 2538if (*++ arg == '>' ) { 2539arg ++ ; 2540 } 2541arg = skipwhite (arg ); 2542 }else if (* arg == '!' && ea .cmdidx == CMD_write ) {// :w !filter 2543arg ++ ; 2544usefilter = true; 2545 } 2546 } 2547 2548if (ea .cmdidx == CMD_read ) { 2549usefilter = forceit ;// :r! filter if forced 2550if (* arg == '!' ) {// :r !filter 2551arg ++ ; 2552usefilter = true; 2553 } 2554 } 2555 2556if (ea .cmdidx == CMD_lshift || ea .cmdidx == CMD_rshift ) { 2557while (* arg == * cmd ) {// allow any number of '>' or '<' 2558arg ++ ; 2559 } 2560arg = skipwhite (arg ); 2561 } 2562 2563// Does command allow "+command"? 2564if ((ea .argt & EX_CMDARG )&& !usefilter && * arg == '+' ) { 2565// Check if we're in the +command 2566p = arg + 1 ; 2567arg = skip_cmd_arg ((char * )arg , false); 2568 2569// Still touching the command after '+'? 2570if (* arg == NUL ) { 2571return p ; 2572 } 2573 2574// Skip space(s) after +command to get to the real argument. 2575arg = skipwhite (arg ); 2576 } 2577 2578// Check for '|' to separate commands and '"' to start comments. 2579// Don't do this for ":read !cmd" and ":write !cmd". 2580if ((ea .argt & EX_TRLBAR )&& !usefilter ) { 2581p = arg ; 2582// ":redir @" is not the start of a comment 2583if (ea .cmdidx == CMD_redir && p [0 ]== '@' && p [1 ]== '"' ) { 2584p += 2 ; 2585 } 2586while (* p ) { 2587if (* p == Ctrl_V ) { 2588if (p [1 ]!= NUL ) { 2589p ++ ; 2590 } 2591 }else if ((* p == '"' && !(ea .argt & EX_NOTRLCOM )) 2592|| * p == '|' 2593|| * p == '\n' ) { 2594if (* (p - 1 )!= '\\' ) { 2595if (* p == '|' || * p == '\n' ) { 2596return p + 1 ; 2597 } 2598return NULL ;// It's a comment 2599 } 2600 } 2601MB_PTR_ADV (p ); 2602 } 2603 } 2604 2605if (!(ea .argt & EX_EXTRA )&& * arg != NUL && strchr ("|\"" ,* arg )== NULL ) { 2606// no arguments allowed but there is something 2607return NULL ; 2608 } 2609 2610// Find start of last argument (argument just before cursor): 2611p = buff ; 2612xp -> xp_pattern = (char * )p ; 2613len = strlen (buff ); 2614while (* p && p < buff + len ) { 2615if (* p == ' ' || * p == TAB ) { 2616// argument starts after a space 2617xp -> xp_pattern = (char * )++ p ; 2618 }else { 2619if (* p == '\\' && * (p + 1 )!= NUL ) { 2620p ++ ;// skip over escaped character 2621 } 2622MB_PTR_ADV (p ); 2623 } 2624 } 2625 2626if (ea .argt & EX_XFILE ) { 2627set_context_for_wildcard_arg (& ea ,arg ,usefilter ,xp ,& context ); 2628 } 2629 2630// Switch on command name. 2631return set_context_by_cmdname (cmd ,ea .cmdidx ,xp ,arg ,ea .argt ,context ,forceit ); 2632} 2633 2634/// Set the completion context in "xp" for command "str" 2635/// 2636/// @param str start of command line 2637/// @param len length of command line (excl. NUL) 2638/// @param col position of cursor 2639/// @param use_ccline use ccline for info 2640void set_cmd_context (expand_T * xp ,char * str ,int len ,int col ,int use_ccline ) 2641{ 2642CmdlineInfo * const ccline = get_cmdline_info (); 2643char old_char = NUL ; 2644 2645// Only save and overwrite the character when it is not the NUL terminator 2646// already. "str" may be a read-only empty string: tv_get_string() falls 2647// back to a "" literal for a NULL string or on a type error, and writing 2648// at "col" would then crash. 2649// This also avoids a UMR warning from Purify. 2650if (col < len ) { 2651old_char = str [col ]; 2652str [col ]= NUL ; 2653 } 2654const char * nextcomm = str ; 2655 2656if (use_ccline && ccline -> cmdfirstc == '=' ) { 2657// pass CMD_SIZE because there is no real command 2658set_context_for_expression (xp ,str ,CMD_SIZE ); 2659 }else if (use_ccline && ccline -> input_fn ) { 2660xp -> xp_context = ccline -> xp_context ; 2661xp -> xp_pattern = ccline -> cmdbuff ; 2662xp -> xp_arg = ccline -> xp_arg ; 2663if (xp -> xp_context == EXPAND_SHELLCMDLINE ) { 2664int context = xp -> xp_context ; 2665set_context_for_wildcard_arg (NULL ,xp -> xp_pattern , false,xp ,& context ); 2666 } 2667 }else { 2668while (nextcomm != NULL ) { 2669nextcomm = set_one_cmd_context (xp ,nextcomm ); 2670 } 2671 } 2672 2673// Store the string here so that call_user_expand_func() can get to them 2674// easily. 2675xp -> xp_line = str ; 2676xp -> xp_col = col ; 2677 2678if (col < len ) { 2679str [col ]= old_char ; 2680 } 2681} 2682 2683/// Expand the command line "str" from context "xp". 2684/// "xp" must have been set by set_cmd_context(). 2685/// xp->xp_pattern points into "str", to where the text that is to be expanded 2686/// starts. 2687/// Returns EXPAND_UNSUCCESSFUL when there is something illegal before the 2688/// cursor. 2689/// Returns EXPAND_NOTHING when there is nothing to expand, might insert the 2690/// key that triggered expansion literally. 2691/// Returns EXPAND_OK otherwise. 2692/// 2693/// @param str start of command line 2694/// @param col position of cursor 2695/// @param matchcount return: nr of matches 2696/// @param matches return: array of pointers to matches 2697int expand_cmdline (expand_T * xp ,const char * str ,int col ,int * matchcount ,char *** matches ) 2698{ 2699char * file_str = NULL ; 2700int options = WILD_ADD_SLASH |WILD_SILENT ; 2701 2702if (xp -> xp_context == EXPAND_UNSUCCESSFUL ) { 2703beep_flush (); 2704return EXPAND_UNSUCCESSFUL ;// Something illegal on command line 2705 } 2706if (xp -> xp_context == EXPAND_NOTHING ) { 2707// Caller can use the character as a normal char instead 2708return EXPAND_NOTHING ; 2709 } 2710 2711// add star to file name, or convert to regexp if not exp. files. 2712assert ((str + col )- xp -> xp_pattern >=0 ); 2713xp -> xp_pattern_len = (size_t )((str + col )- xp -> xp_pattern ); 2714if (cmdline_fuzzy_completion_supported (xp )) { 2715// If fuzzy matching, don't modify the search string 2716file_str = xstrdup (xp -> xp_pattern ); 2717 }else { 2718file_str = addstar (xp -> xp_pattern ,xp -> xp_pattern_len ,xp -> xp_context ); 2719 } 2720 2721if (p_wic ) { 2722options += WILD_ICASE ; 2723 } 2724 2725// find all files that match the description 2726if (ExpandFromContext (xp ,file_str ,matches ,matchcount ,options )== FAIL ) { 2727* matchcount = 0 ; 2728* matches = NULL ; 2729 } 2730xfree (file_str ); 2731 2732return EXPAND_OK ; 2733} 2734 2735/// Expand file or directory names. 2736static int expand_files_and_dirs (expand_T * xp ,char * pat ,char *** matches ,int * numMatches , 2737int flags ,int options ) 2738{ 2739bool free_pat = false; 2740 2741// for ":set path=" and ":set tags=" halve backslashes for escaped space 2742if (xp -> xp_backslash != XP_BS_NONE ) { 2743free_pat = true; 2744size_t pat_len = strlen (pat ); 2745pat = xstrnsave (pat ,pat_len ); 2746 2747char * pat_end = pat + pat_len ; 2748for (char * p = pat ;* p != NUL ;p ++ ) { 2749if (* p != '\\' ) { 2750continue ; 2751 } 2752 2753if (xp -> xp_backslash & XP_BS_THREE 2754&& * (p + 1 )== '\\' 2755&& * (p + 2 )== '\\' 2756&& * (p + 3 )== ' ' ) { 2757char * from = p + 3 ; 2758memmove (p ,from , (size_t )(pat_end - from )+ 1 );// +1 for NUL 2759pat_end -= 3 ; 2760 }else if (xp -> xp_backslash & XP_BS_ONE 2761&& * (p + 1 )== ' ' ) { 2762char * from = p + 1 ; 2763memmove (p ,from , (size_t )(pat_end - from )+ 1 );// +1 for NUL 2764pat_end -- ; 2765 }else if (xp -> xp_backslash & XP_BS_COMMA ) { 2766if (* (p + 1 )== '\\' && * (p + 2 )== ',' ) { 2767char * from = p + 2 ; 2768memmove (p ,from , (size_t )(pat_end - from )+ 1 );// +1 for NUL 2769pat_end -= 2 ; 2770#ifdef BACKSLASH_IN_FILENAME 2771} else if ( * ( p + 1 ) == ',' ) { 2772char * from = p + 1 ; 2773memmove ( p , from , ( size_t )( pat_end - from ) + 1 ); // +1 for NUL 2774pat_end -- ; 2775#endif 2776} 2777} 2778} 2779} 2780 2781int ret = FAIL ; 2782if ( xp -> xp_context == EXPAND_FINDFUNC ) { 2783ret = expand_findfunc ( xp , pat , matches , numMatches ); 2784} else { 2785if ( xp -> xp_context == EXPAND_FILES ) { 2786flags |= EW_FILE ; 2787} else if ( xp -> xp_context == EXPAND_FILES_IN_PATH ) { 2788flags |= ( EW_FILE | EW_PATH ); 2789} else if ( xp -> xp_context == EXPAND_DIRS_IN_CDPATH ) { 2790flags = ( flags | EW_DIR | EW_CDPATH ) & ~ EW_FILE ; 2791} else { 2792flags = ( flags | EW_DIR ) & ~ EW_FILE ; 2793} 2794if ( options & WILD_ICASE ) { 2795flags |= EW_ICASE ; 2796} 2797// Expand wildcards, supporting %:h and the like. 2798ret = expand_wildcards_eval ( & pat , numMatches , matches , flags ); 2799} 2800if ( free_pat ) { 2801xfree ( pat ); 2802} 2803#ifdef BACKSLASH_IN_FILENAME 2804if ((( options & WILD_USE_SHELLSLASH ) && ! p_ssl ) 2805|| (( options & WILD_USE_COMPLETESLASH ) 2806&& (( p_csl [ 0 ] == NUL && ! p_ssl ) || p_csl [ 0 ] == 'b' ))) { 2807for ( int j = 0 ; j < * numMatches ; j ++ ) { 2808char * ptr = ( * matches )[ j ]; 2809for (; * ptr ; ptr ++ ) { 2810if ( * ptr == PATHSEP ) { 2811* ptr = '\\' ; 2812} 2813} 2814} 2815} 2816#endif 2817return ret ; 2818} 2819 2820/// Function given to ExpandGeneric() to obtain the possible arguments of the 2821/// ":filetype {plugin,indent}" command. 2822static char * get_filetypecmd_arg ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2823{ 2824if ( idx < 0 ) { 2825return NULL ; 2826} 2827 2828if ( filetype_expand_what == EXP_FILETYPECMD_ALL && idx < 5 ) { 2829char * opts_all [] = { "detect" , "indent" , "plugin" , "on" , "off" }; 2830return opts_all [ idx ]; 2831} 2832if ( filetype_expand_what == EXP_FILETYPECMD_PLUGIN && idx < 3 ) { 2833char * opts_plugin [] = { "plugin" , "on" , "off" }; 2834return opts_plugin [ idx ]; 2835} 2836if ( filetype_expand_what == EXP_FILETYPECMD_INDENT && idx < 3 ) { 2837char * opts_indent [] = { "indent" , "on" , "off" }; 2838return opts_indent [ idx ]; 2839} 2840if ( filetype_expand_what == EXP_FILETYPECMD_ONOFF && idx < 2 ) { 2841char * opts_onoff [] = { "on" , "off" }; 2842return opts_onoff [ idx ]; 2843} 2844return NULL ; 2845} 2846 2847/// Function given to ExpandGeneric() to obtain the possible arguments of the 2848/// ":breakadd {expr, file, func, here}" command. 2849/// ":breakdel {func, file, here}" command. 2850static char * get_breakadd_arg ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2851{ 2852if ( idx >= 0 && idx <= 3 ) { 2853char * opts [] = { "expr" , "file" , "func" , "here" }; 2854 2855// breakadd {expr, file, func, here} 2856if ( breakpt_expand_what == EXP_BREAKPT_ADD ) { 2857return opts [ idx ]; 2858} else if ( breakpt_expand_what == EXP_BREAKPT_DEL ) { 2859// breakdel {func, file, here} 2860if ( idx <= 2 ) { 2861return opts [ idx + 1 ]; 2862} 2863} else { 2864// profdel {func, file} 2865if ( idx <= 1 ) { 2866return opts [ idx + 1 ]; 2867} 2868} 2869} 2870return NULL ; 2871} 2872 2873/// Function given to ExpandGeneric() to obtain the possible arguments for the 2874/// ":scriptnames" command. 2875static char * get_scriptnames_arg ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2876{ 2877if (! SCRIPT_ID_VALID ( idx + 1 )) { 2878return NULL ; 2879} 2880 2881scriptitem_T * si = SCRIPT_ITEM ( idx + 1 ); 2882home_replace ( NULL , si -> sn_name , NameBuff , MAXPATHL , true); 2883return NameBuff ; 2884} 2885 2886/// Function given to ExpandGeneric() to obtain the possible arguments of the 2887/// ":retab {-indentonly}" option. 2888static char * get_retab_arg ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2889{ 2890if ( idx == 0 ) { 2891return "-indentonly" ; 2892} 2893return NULL ; 2894} 2895 2896/// Function given to ExpandGeneric() to obtain the possible arguments of the 2897/// ":messages {clear}" command. 2898static char * get_messages_arg ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2899{ 2900if ( idx == 0 ) { 2901return "clear" ; 2902} 2903return NULL ; 2904} 2905 2906static char * get_mapclear_arg ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2907{ 2908if ( idx == 0 ) { 2909return "<buffer>" ; 2910} 2911return NULL ; 2912} 2913 2914/// Completion for |:checkhealth| command. 2915/// 2916/// Given to ExpandGeneric() to obtain all available heathcheck names. 2917/// @param[in] idx Index of the healthcheck item. 2918/// @param[in] xp Not used. 2919static char * get_healthcheck_names ( expand_T * xp FUNC_ATTR_UNUSED , int idx ) 2920{ 2921static Object names = OBJECT_INIT ; 2922static unsigned last_gen = 0 ; 2923 2924if ( last_gen != get_cmdline_last_prompt_id () || last_gen == 0 ) { 2925Array a = ARRAY_DICT_INIT ; 2926Error err = ERROR_INIT ; 2927Object res = NLUA_EXEC_STATIC ( "return vim.health._complete()" , a , kRetObject , NULL , & err ); 2928api_clear_error ( & err ); 2929api_free_object ( names ); 2930names = res ; 2931last_gen = get_cmdline_last_prompt_id (); 2932} 2933 2934if ( names . type == kObjectTypeArray && idx < ( int ) names . data . array . size 2935&& names . data . array . items [ idx ]. type == kObjectTypeString ) { 2936return names . data . array . items [ idx ]. data . string . data ; 2937} 2938return NULL ; 2939} 2940 2941/// Completes arg1 via Lua. 2942/// 2943/// @param[in] lua Lua script. 2944/// @param[in] xp Expandy thing 🤷 2945/// @param[in] idx Index of the item. 2946static char * get_arg1_from_lua ( char * lua , expand_T * xp , int idx ) 2947{ 2948static Object names = OBJECT_INIT ; 2949static char * last_xp_line = NULL ; 2950static unsigned last_gen = 0 ; 2951 2952if ( last_xp_line == NULL || strcmp ( last_xp_line , xp -> xp_line ) != 0 2953|| last_gen != get_cmdline_last_prompt_id ()) { 2954xfree ( last_xp_line ); 2955last_xp_line = xstrdup ( xp -> xp_line ); 2956MAXSIZE_TEMP_ARRAY ( args , 2 ); 2957Error err = ERROR_INIT ; 2958 2959ADD_C ( args , CSTR_AS_OBJ ( xp -> xp_pattern )); 2960ADD_C ( args , CSTR_AS_OBJ ( xp -> xp_line )); 2961// Build the current command line as a Lua string argument 2962Object res = nlua_exec ( cstr_as_string ( lua ), NULL , args , kRetObject , NULL , & err ); 2963api_clear_error ( & err ); 2964api_free_object ( names ); 2965names = res ; 2966last_gen = get_cmdline_last_prompt_id (); 2967} 2968 2969if ( names . type == kObjectTypeArray && idx < ( int ) names . data . array . size 2970&& names . data . array . items [ idx ]. type == kObjectTypeString ) { 2971return names . data . array . items [ idx ]. data . string . data ; 2972} 2973return NULL ; 2974} 2975 2976/// Completion for the |:marks| command. Given to ExpandGeneric(). 2977/// @param[in] xp Expandy thing 🤷 2978/// @param[in] idx Index of the item. 2979static char * get_marks_arg ( expand_T * xp , int idx ) 2980{ 2981return get_arg1_from_lua ( "return require'vim._core.marks'.complete(...)" , xp , idx ); 2982} 2983 2984/// Completion for |:log| command. Given to ExpandGeneric(). 2985/// @param[in] xp Expandy thing 🤷 2986/// @param[in] idx Index of the item. 2987static char * get_log_arg ( expand_T * xp , int idx ) 2988{ 2989return get_arg1_from_lua ( "return require'vim._core.ex_cmd'.log_complete(...)" , xp , idx ); 2990} 2991 2992/// Completion for |:lsp| command. Given to ExpandGeneric(). 2993/// @param[in] xp Expandy thing 🤷 2994/// @param[in] idx Index of the item. 2995static char * get_lsp_arg ( expand_T * xp , int idx ) 2996{ 2997return get_arg1_from_lua ( "return require'vim._core.ex_cmd'.lsp_complete(...)" , xp , idx ); 2998} 2999 3000/// Completion for |:packdel| command. Given to ExpandGeneric(). 3001/// @param[in] xp Expandy thing. 3002/// @param[in] idx Index of the item. 3003static char * get_packdel_arg ( expand_T * xp , int idx ) 3004{ 3005return get_arg1_from_lua ( "return require'vim._core.ex_cmd'.packdel_complete(...)" , xp , idx ); 3006} 3007 3008/// Completion for |:packupdate| command. Given to ExpandGeneric(). 3009/// @param[in] xp Expandy thing. 3010/// @param[in] idx Index of the item. 3011static char * get_packupdate_arg ( expand_T * xp , int idx ) 3012{ 3013return get_arg1_from_lua ( "return require'vim._core.ex_cmd'.packupdate_complete(...)" , xp , idx ); 3014} 3015 3016/// Do the expansion based on xp->xp_context and "rmp". 3017static int ExpandOther ( char * pat , expand_T * xp , regmatch_T * rmp , char *** matches , int * numMatches ) 3018{ 3019typedef CompleteListItemGetter ExpandFunc ; 3020static struct expgen { 3021int context ; 3022ExpandFunc func ; 3023int ic ; 3024int escaped ; 3025} tab [] = { 3026{ EXPAND_COMMANDS , get_command_name , false, true }, 3027{ EXPAND_FILETYPECMD , get_filetypecmd_arg , true, true }, 3028{ EXPAND_MAPCLEAR , get_mapclear_arg , true, true }, 3029{ EXPAND_MESSAGES , get_messages_arg , true, true }, 3030{ EXPAND_HISTORY , get_history_arg , true, true }, 3031{ EXPAND_USER_COMMANDS , get_user_commands , false, true }, 3032{ EXPAND_USER_ADDR_TYPE , get_user_cmd_addr_type , false, true }, 3033{ EXPAND_USER_CMD_FLAGS , get_user_cmd_flags , false, true }, 3034{ EXPAND_USER_NARGS , get_user_cmd_nargs , false, true }, 3035{ EXPAND_USER_COMPLETE , get_user_cmd_complete , false, true }, 3036{ EXPAND_USER_VARS , get_user_var_name , false, true }, 3037{ EXPAND_FUNCTIONS , get_function_name , false, true }, 3038{ EXPAND_USER_FUNC , get_user_func_name , false, true }, 3039{ EXPAND_EXPRESSION , get_expr_name , false, true }, 3040{ EXPAND_MENUS , get_menu_name , false, true }, 3041{ EXPAND_MENUNAMES , get_menu_names , false, true }, 3042{ EXPAND_SYNTAX , get_syntax_name , true, true }, 3043{ EXPAND_SYNTIME , get_syntime_arg , true, true }, 3044{ EXPAND_HIGHLIGHT , get_highlight_name , true, false }, 3045{ EXPAND_EVENTS , expand_get_event_name , true, false }, 3046{ EXPAND_AUGROUP , expand_get_augroup_name , true, false }, 3047{ EXPAND_SIGN , get_sign_name , true, true }, 3048{ EXPAND_PROFILE , get_profile_name , true, true }, 3049{ EXPAND_LANGUAGE , get_lang_arg , true, false }, 3050{ EXPAND_LOCALES , get_locales , true, false }, 3051{ EXPAND_ENV_VARS , get_env_name , true, true }, 3052{ EXPAND_USER , get_users , true, false }, 3053{ EXPAND_ARGLIST , get_arglist_name , true, false }, 3054{ EXPAND_BREAKPOINT , get_breakadd_arg , true, true }, 3055{ EXPAND_SCRIPTNAMES , get_scriptnames_arg , true, false }, 3056{ EXPAND_RETAB , get_retab_arg , true, true }, 3057{ EXPAND_CHECKHEALTH , get_healthcheck_names , true, false }, 3058{ EXPAND_MARKS , get_marks_arg , true, false }, 3059{ EXPAND_LOG , get_log_arg , true, false }, 3060{ EXPAND_LSP , get_lsp_arg , true, false }, 3061{ EXPAND_PACKDEL , get_packdel_arg , true, false }, 3062{ EXPAND_PACKUPDATE , get_packupdate_arg , true, false }, 3063}; 3064int ret = FAIL ; 3065 3066// Find a context in the table and call the ExpandGeneric() with the 3067// right function to do the expansion. 3068for ( int i = 0 ; i < ( int ) ARRAY_SIZE ( tab ); i ++ ) { 3069if ( xp -> xp_context == tab [ i ]. context ) { 3070if ( tab [ i ]. ic ) { 3071rmp -> rm_ic = true; 3072} 3073ExpandGeneric ( pat , xp , rmp , matches , numMatches , tab [ i ]. func , tab [ i ]. escaped ); 3074ret = OK ; 3075break; 3076} 3077} 3078 3079return ret ; 3080} 3081 3082/// Map wild expand options to flags for expand_wildcards() 3083static int map_wildopts_to_ewflags ( int options ) 3084{ 3085int flags = EW_DIR ; // include directories 3086if ( options & WILD_LIST_NOTFOUND ) { 3087flags |= EW_NOTFOUND ; 3088} 3089if ( options & WILD_ADD_SLASH ) { 3090flags |= EW_ADDSLASH ; 3091} 3092if ( options & WILD_KEEP_ALL ) { 3093flags |= EW_KEEPALL ; 3094} 3095if ( options & WILD_SILENT ) { 3096flags |= EW_SILENT ; 3097} 3098if ( options & WILD_NOERROR ) { 3099flags |= EW_NOERROR ; 3100} 3101if ( options & WILD_ALLLINKS ) { 3102flags |= EW_ALLLINKS ; 3103} 3104 3105return flags ; 3106} 3107 3108/// Do the expansion based on xp->xp_context and "pat". 3109/// 3110/// @param options WILD_ flags 3111static int ExpandFromContext ( expand_T * xp , char * pat , char *** matches , int * numMatches , int options ) 3112{ 3113regmatch_T regmatch = { . rm_ic = false }; 3114int ret ; 3115int flags = map_wildopts_to_ewflags ( options ); 3116const bool fuzzy = cmdline_fuzzy_complete ( pat ) 3117&& cmdline_fuzzy_completion_supported ( xp ); 3118 3119if ( xp -> xp_context == EXPAND_FILES 3120|| xp -> xp_context == EXPAND_DIRECTORIES 3121|| xp -> xp_context == EXPAND_FILES_IN_PATH 3122|| xp -> xp_context == EXPAND_FINDFUNC 3123|| xp -> xp_context == EXPAND_DIRS_IN_CDPATH ) { 3124return expand_files_and_dirs ( xp , pat , matches , numMatches , flags , options ); 3125} 3126 3127* matches = NULL ; 3128* numMatches = 0 ; 3129if ( xp -> xp_context == EXPAND_HELP ) { 3130// With an empty argument we would get all the help tags, which is 3131// very slow. Get matches for "help" instead. 3132if ( find_help_tags ( * pat == NUL ? "help" : pat , 3133numMatches , matches , false) == OK ) { 3134cleanup_help_tags ( * numMatches , * matches ); 3135return OK ; 3136} 3137return FAIL ; 3138} 3139 3140if ( xp -> xp_context == EXPAND_SHELLCMD ) { 3141expand_shellcmd ( pat , matches , numMatches , flags ); 3142return OK ; 3143} 3144if ( xp -> xp_context == EXPAND_OLD_SETTING ) { 3145return ExpandOldSetting ( numMatches , matches ); 3146} 3147if ( xp -> xp_context == EXPAND_BUFFERS ) { 3148return ExpandBufnames ( pat , numMatches , matches , options ); 3149} 3150if ( xp -> xp_context == EXPAND_DIFF_BUFFERS ) { 3151return ExpandBufnames ( pat , numMatches , matches , options | BUF_DIFF_FILTER ); 3152} 3153if ( xp -> xp_context == EXPAND_TAGS 3154|| xp -> xp_context == EXPAND_TAGS_LISTFILES ) { 3155return expand_tags ( xp -> xp_context == EXPAND_TAGS , pat , numMatches , matches ); 3156} 3157if ( xp -> xp_context == EXPAND_COLORS ) { 3158char * directories [] = { "colors" , NULL }; 3159return ExpandRTDir ( pat , DIP_START + DIP_OPT , numMatches , matches , directories ); 3160} 3161if ( xp -> xp_context == EXPAND_COMPILER ) { 3162char * directories [] = { "compiler" , NULL }; 3163return ExpandRTDir ( pat , 0 , numMatches , matches , directories ); 3164} 3165if ( xp -> xp_context == EXPAND_OWNSYNTAX ) { 3166char * directories [] = { "syntax" , NULL }; 3167return ExpandRTDir ( pat , 0 , numMatches , matches , directories ); 3168} 3169if ( xp -> xp_context == EXPAND_FILETYPE ) { 3170char * directories [] = { "syntax" , "indent" , "ftplugin" , NULL }; 3171return ExpandRTDir ( pat , 0 , numMatches , matches , directories ); 3172} 3173if ( xp -> xp_context == EXPAND_KEYMAP ) { 3174char * directories [] = { "keymap" , NULL }; 3175return ExpandRTDir ( pat , 0 , numMatches , matches , directories ); 3176} 3177if ( xp -> xp_context == EXPAND_USER_LIST ) { 3178return ExpandUserList ( xp , matches , numMatches ); 3179} 3180if ( xp -> xp_context == EXPAND_USER_LUA ) { 3181return ExpandUserLua ( xp , numMatches , matches ); 3182} 3183if ( xp -> xp_context == EXPAND_PACKADD ) { 3184return ExpandPackAddDir ( pat , numMatches , matches ); 3185} 3186if ( xp -> xp_context == EXPAND_RUNTIME ) { 3187return expand_runtime_cmd ( pat , numMatches , matches ); 3188} 3189if ( xp -> xp_context == EXPAND_PATTERN_IN_BUF ) { 3190return expand_pattern_in_buf ( pat , xp -> xp_search_dir , matches , numMatches ); 3191} 3192 3193// When expanding a function name starting with s:, match the <SNR>nr_ 3194// prefix. 3195char * tofree = NULL ; 3196if ( xp -> xp_context == EXPAND_USER_FUNC && strncmp ( pat , "^s:" , 3 ) == 0 ) { 3197const size_t len = strlen ( pat ) + 20 ; 3198 3199tofree = xmalloc ( len ); 3200snprintf ( tofree , len , "^<SNR>\\d\\+_%s" , pat + 3 ); 3201pat = tofree ; 3202} 3203 3204if ( xp -> xp_context == EXPAND_LUA ) { 3205return nlua_expand_get_matches ( numMatches , matches ); 3206} 3207 3208if (! fuzzy ) { 3209regmatch . regprog = vim_regcomp ( pat , p_magic ? RE_MAGIC : 0 ); 3210if ( regmatch . regprog == NULL ) { 3211xfree ( tofree ); 3212return FAIL ; 3213} 3214// set ignore-case according to p_ic, p_scs and pat 3215regmatch . rm_ic = ignorecase ( pat ); 3216} 3217 3218if ( xp -> xp_context == EXPAND_SETTINGS 3219|| xp -> xp_context == EXPAND_BOOL_SETTINGS ) { 3220ret = ExpandSettings ( xp , & regmatch , pat , numMatches , matches , fuzzy ); 3221} else if ( xp -> xp_context == EXPAND_STRING_SETTING ) { 3222ret = ExpandStringSetting ( xp , & regmatch , numMatches , matches ); 3223} else if ( xp -> xp_context == EXPAND_SETTING_SUBTRACT ) { 3224ret = ExpandSettingSubtract ( xp , & regmatch , numMatches , matches ); 3225} else if ( xp -> xp_context == EXPAND_MAPPINGS ) { 3226ret = ExpandMappings ( pat , & regmatch , numMatches , matches ); 3227} else if ( xp -> xp_context == EXPAND_ARGOPT ) { 3228ret = expand_argopt ( pat , xp , & regmatch , matches , numMatches ); 3229} else if ( xp -> xp_context == EXPAND_USER_DEFINED ) { 3230ret = ExpandUserDefined ( pat , xp , & regmatch , matches , numMatches ); 3231} else { 3232ret = ExpandOther ( pat , xp , & regmatch , matches , numMatches ); 3233} 3234 3235if (! fuzzy ) { 3236vim_regfree ( regmatch . regprog ); 3237} 3238xfree ( tofree ); 3239 3240return ret ; 3241} 3242 3243/// Expand a list of names. 3244/// 3245/// Generic function for command line completion. It calls a function to 3246/// obtain strings, one by one. The strings are matched against a regexp 3247/// program. Matching strings are copied into an array, which is returned. 3248/// 3249/// @param func returns a string from the list 3250void ExpandGeneric (const char * const pat , expand_T * xp , regmatch_T * regmatch , char *** matches , 3251int * numMatches , CompleteListItemGetter func , bool escaped ) 3252{ 3253const bool fuzzy = cmdline_fuzzy_complete ( pat ); 3254* matches = NULL ; 3255* numMatches = 0 ; 3256 3257garray_T ga ; 3258if (! fuzzy ) { 3259ga_init ( & ga , sizeof( char * ), 30 ); 3260} else { 3261ga_init ( & ga , sizeof( fuzmatch_str_T ), 30 ); 3262} 3263 3264for ( int i = 0 ;; i ++ ) { 3265char * str = ( * func )( xp , i ); 3266if ( str == NULL ) { // End of list. 3267break; 3268} 3269if ( * str == NUL ) { // Skip empty strings. 3270continue; 3271} 3272 3273bool match ; 3274int score = 0 ; 3275if ( xp -> xp_pattern [ 0 ] != NUL ) { 3276if (! fuzzy ) { 3277match = vim_regexec ( regmatch , str , 0 ); 3278} else { 3279score = fuzzy_match_str ( str , pat ); 3280match = ( score != FUZZY_SCORE_NONE ); 3281} 3282} else { 3283match = true; 3284} 3285 3286if (! match ) { 3287continue; 3288} 3289 3290if ( escaped ) { 3291str = vim_strsave_escaped ( str , " \t\\." ); 3292} else { 3293str = xstrdup ( str ); 3294} 3295 3296if ( fuzzy ) { 3297GA_APPEND ( fuzmatch_str_T , & ga , (( fuzmatch_str_T ){ 3298. idx = ga . ga_len , 3299. str = str , 3300. score = score , 3301})); 3302} else { 3303GA_APPEND ( char * , & ga , str ); 3304} 3305 3306if ( func == get_menu_names ) { 3307// Test for separator added by get_menu_names(). 3308str += strlen ( str ) - 1 ; 3309if ( * str == '\001' ) { 3310* str = '.' ; 3311} 3312} 3313} 3314 3315if ( ga . ga_len == 0 ) { 3316return; 3317} 3318 3319// Sort the matches when using regular expression matching and sorting 3320// applies to the completion context. Menus and scriptnames should be kept 3321// in the specified order. 3322const bool sort_matches = ! fuzzy 3323&& xp -> xp_context != EXPAND_MENUNAMES 3324&& xp -> xp_context != EXPAND_STRING_SETTING 3325&& xp -> xp_context != EXPAND_MENUS 3326&& xp -> xp_context != EXPAND_SCRIPTNAMES 3327&& xp -> xp_context != EXPAND_ARGOPT ; 3328 3329// <SNR> functions should be sorted to the end. 3330const bool funcsort = xp -> xp_context == EXPAND_EXPRESSION 3331|| xp -> xp_context == EXPAND_FUNCTIONS 3332|| xp -> xp_context == EXPAND_USER_FUNC ; 3333 3334// Sort the matches. 3335if ( sort_matches ) { 3336if ( funcsort ) { 3337// <SNR> functions should be sorted to the end. 3338qsort ( ga . ga_data , ( size_t ) ga . ga_len , sizeof( char * ), sort_func_compare ); 3339} else { 3340sort_strings ( ga . ga_data , ga . ga_len ); 3341} 3342} 3343 3344if (! fuzzy ) { 3345* matches = ga . ga_data ; 3346* numMatches = ga . ga_len ; 3347} else { 3348fuzzymatches_to_strmatches ( ga . ga_data , matches , ga . ga_len , funcsort ); 3349* numMatches = ga . ga_len ; 3350} 3351 3352// Reset the variables used for special highlight names expansion, so that 3353// they don't show up when getting normal highlight names by ID. 3354reset_expand_highlight (); 3355} 3356 3357/// Expand shell command matches in one directory of $PATH. 3358/// 3359/// @param pathed_pattern fully pathed pattern 3360/// @param pathlen length of the path portion of pathed_pattern (0 if no path) 3361static void expand_shellcmd_onedir ( char * pathed_pattern , size_t pathlen , char *** matches , 3362int * numMatches , int flags , hashtab_T * ht , garray_T * gap ) 3363{ 3364// Expand matches in one directory of $PATH. 3365if ( expand_wildcards ( 1 , & pathed_pattern , numMatches , matches , flags ) != OK ) { 3366return; 3367} 3368 3369ga_grow ( gap , * numMatches ); 3370 3371for ( int i = 0 ; i < * numMatches ; i ++ ) { 3372char * name = ( * matches )[ i ]; 3373size_t namelen = strlen ( name ); 3374 3375if ( namelen > pathlen ) { 3376// Check if this name was already found. 3377hash_T hash = hash_hash ( name + pathlen ); 3378hashitem_T * hi = hash_lookup ( ht , name + pathlen , namelen - pathlen , hash ); 3379if ( HASHITEM_EMPTY ( hi )) { 3380// Remove the path that was prepended. 3381memmove ( name , name + pathlen , namelen - pathlen + 1 ); // +1 for NUL 3382(( char ** ) gap -> ga_data )[ gap -> ga_len ++ ] = name ; 3383hash_add_item ( ht , hi , name , hash ); 3384name = NULL ; 3385} 3386} 3387xfree ( name ); 3388} 3389xfree ( * matches ); 3390} 3391 3392/// Complete a shell command. 3393/// 3394/// @param filepat is a pattern to match with command names. 3395/// @param[out] matches is pointer to array of pointers to matches. 3396/// *matches will either be set to NULL or point to 3397/// allocated memory. 3398/// @param[out] numMatches is pointer to number of matches. 3399/// @param flagsarg is a combination of EW_* flags. 3400static void expand_shellcmd ( char * filepat , char *** matches , int * numMatches , int flagsarg ) 3401FUNC_ATTR_NONNULL_ALL 3402{ 3403char * path = NULL ; 3404garray_T ga ; 3405char * buf = xmalloc ( MAXPATHL ); 3406int flags = flagsarg ; 3407bool did_curdir = false; 3408 3409// for ":set path=" and ":set tags=" halve backslashes for escaped space 3410size_t patlen = strlen ( filepat ); 3411char * pat = xmemdupz ( filepat , patlen ); 3412// Replace "\ " with " ". 3413char * e = pat + patlen ; 3414for ( char * s = pat ; * s != NUL ; s ++ ) { 3415if ( * s != '\\' ) { 3416continue; 3417} 3418char * p = s + 1 ; 3419if ( * p == ' ' ) { 3420memmove ( s , p , ( size_t )( e - p ) + 1 ); // +1 for NUL 3421e -- ; 3422} 3423} 3424patlen = ( size_t )( e - pat ); 3425 3426flags |= EW_FILE | EW_EXEC | EW_SHELLCMD ; 3427 3428bool mustfree = false; // Track memory allocation for *path. 3429if ( pat [ 0 ] == '.' && ( vim_ispathsep ( pat [ 1 ]) 3430|| ( pat [ 1 ] == '.' && vim_ispathsep ( pat [ 2 ])))) { 3431path = "." ; 3432} else { 3433// For an absolute name we don't use $PATH. 3434if (! path_is_absolute ( pat )) { 3435path = vim_getenv ( "PATH" ); 3436} 3437if ( path == NULL ) { 3438path = "" ; 3439} else { 3440mustfree = true; 3441} 3442} 3443 3444// Go over all directories in $PATH. Expand matches in that directory and 3445// collect them in "ga". When "." is not in $PATH also expand for the 3446// current directory, to find "subdir/cmd". 3447ga_init ( & ga , ( int )sizeof( char * ), 10 ); 3448hashtab_T found_ht ; 3449hash_init ( & found_ht ); 3450for ( char * s = path ;; s = e ) { 3451size_t pathlen ; // length of the path portion of buf (including trailing slash). 3452size_t seplen ; 3453 3454if ( * s == NUL ) { 3455if ( did_curdir ) { 3456break; 3457} 3458 3459// Find directories in the current directory, path is empty. 3460did_curdir = true; 3461flags |= EW_DIR ; 3462 3463e = s ; 3464pathlen = 0 ; 3465seplen = 0 ; 3466} else { 3467e = vim_strchr ( s , ENV_SEPCHAR ); 3468if ( e == NULL ) { 3469e = s + strlen ( s ); 3470} 3471 3472pathlen = ( size_t )( e - s ); 3473if ( strncmp ( s , "." , pathlen ) == 0 ) { 3474did_curdir = true; 3475flags |= EW_DIR ; 3476} else { 3477// Do not match directories inside a $PATH item. 3478flags &= ~ EW_DIR ; 3479} 3480 3481seplen = ! after_pathsep ( s , e ) ? STRLEN_LITERAL ( PATHSEPSTR ) : 0 ; 3482} 3483 3484// Make sure that the pathed pattern (ie the path and pattern concatenated 3485// together) will fit inside the buffer. If not skip it and move on to the 3486// next path. 3487if ( pathlen + seplen + patlen + 1 <= MAXPATHL ) { 3488if ( pathlen > 0 ) { 3489xmemcpyz ( buf , s , pathlen ); 3490if ( seplen > 0 ) { 3491xmemcpyz ( buf + pathlen , S_LEN ( PATHSEPSTR )); 3492pathlen += seplen ; 3493} 3494} 3495xmemcpyz ( buf + pathlen , pat , patlen ); 3496 3497expand_shellcmd_onedir ( buf , pathlen , matches , numMatches , flags , & found_ht , & ga ); 3498} 3499 3500if ( * e != NUL ) { 3501e ++ ; 3502} 3503} 3504* matches = ga . ga_data ; 3505* numMatches = ga . ga_len ; 3506 3507xfree ( buf ); 3508xfree ( pat ); 3509if ( mustfree ) { 3510xfree ( path ); 3511} 3512hash_clear ( & found_ht ); 3513} 3514 3515/// Call "user_expand_func()" to invoke a user defined Vim script function and 3516/// return the result (either a string, a List or NULL). 3517static void * call_user_expand_func ( user_expand_func_T user_expand_func , expand_T * xp ) 3518FUNC_ATTR_NONNULL_ALL 3519{ 3520CmdlineInfo * const ccline = get_cmdline_info (); 3521char keep = 0 ; 3522typval_T args [ 4 ]; 3523const sctx_T save_current_sctx = current_sctx ; 3524 3525if ( xp -> xp_arg == NULL || xp -> xp_arg [ 0 ] == NUL || xp -> xp_line == NULL ) { 3526return NULL ; 3527} 3528 3529if ( ccline -> cmdbuff != NULL ) { 3530keep = ccline -> cmdbuff [ ccline -> cmdlen ]; 3531ccline -> cmdbuff [ ccline -> cmdlen ] = 0 ; 3532} 3533 3534char * pat = xstrnsave ( xp -> xp_pattern , xp -> xp_pattern_len ); 3535args [ 0 ]. v_type = VAR_STRING ; 3536args [ 1 ]. v_type = VAR_STRING ; 3537args [ 2 ]. v_type = VAR_NUMBER ; 3538args [ 3 ]. v_type = VAR_UNKNOWN ; 3539args [ 0 ]. vval . v_string = pat ; 3540args [ 1 ]. vval . v_string = xp -> xp_line ; 3541args [ 2 ]. vval . v_number = xp -> xp_col ; 3542 3543current_sctx = xp -> xp_script_ctx ; 3544 3545void * const ret = user_expand_func ( xp -> xp_arg , 3 , args ); 3546 3547current_sctx = save_current_sctx ; 3548if ( ccline -> cmdbuff != NULL ) { 3549ccline -> cmdbuff [ ccline -> cmdlen ] = keep ; 3550} 3551 3552xfree ( pat ); 3553return ret ; 3554} 3555 3556/// Expand names with a function defined by the user (EXPAND_USER_DEFINED and 3557/// EXPAND_USER_LIST). 3558static int ExpandUserDefined (const char * const pat , expand_T * xp , regmatch_T * regmatch , 3559char *** matches , int * numMatches ) 3560{ 3561const bool fuzzy = cmdline_fuzzy_complete ( pat ); 3562* matches = NULL ; 3563* numMatches = 0 ; 3564 3565char * const retstr = call_user_expand_func ( call_func_retstr , xp ); 3566if ( retstr == NULL ) { 3567return FAIL ; 3568} 3569 3570garray_T ga ; 3571if (! fuzzy ) { 3572ga_init ( & ga , ( int )sizeof( char * ), 3 ); 3573} else { 3574ga_init ( & ga , ( int )sizeof( fuzmatch_str_T ), 3 ); 3575} 3576 3577for ( char * s = retstr , * e ; * s != NUL ; s = e ) { 3578e = vim_strchr ( s , '\n' ); 3579if ( e == NULL ) { 3580e = s + strlen ( s ); 3581} 3582const char keep = * e ; 3583* e = NUL ; 3584 3585bool match ; 3586int score = 0 ; 3587if ( xp -> xp_pattern [ 0 ] != NUL ) { 3588if (! fuzzy ) { 3589match = vim_regexec ( regmatch , s , 0 ); 3590} else { 3591score = fuzzy_match_str ( s , pat ); 3592match = ( score != FUZZY_SCORE_NONE ); 3593} 3594} else { 3595match = true; // match everything 3596} 3597 3598* e = keep ; 3599 3600if ( match ) { 3601char * p = xmemdupz ( s , ( size_t )( e - s )); 3602 3603if (! fuzzy ) { 3604GA_APPEND ( char * , & ga , p ); 3605} else { 3606GA_APPEND ( fuzmatch_str_T , & ga , (( fuzmatch_str_T ){ 3607. idx = ga . ga_len , 3608. str = p , 3609. score = score , 3610})); 3611} 3612} 3613 3614if ( * e != NUL ) { 3615e ++ ; 3616} 3617} 3618xfree ( retstr ); 3619 3620if ( ga . ga_len == 0 ) { 3621return OK ; 3622} 3623 3624if (! fuzzy ) { 3625* matches = ga . ga_data ; 3626* numMatches = ga . ga_len ; 3627} else { 3628fuzzymatches_to_strmatches ( ga . ga_data , matches , ga . ga_len , false); 3629* numMatches = ga . ga_len ; 3630} 3631return OK ; 3632} 3633 3634void expand_process_user_list ( list_T * retlist , char *** matches , int * numMatches , expand_T * xp ) 3635{ 3636garray_T ga ; 3637garray_T ga_abbr ; 3638garray_T ga_kind ; 3639garray_T ga_menu ; 3640garray_T ga_info ; 3641bool have_extra = false; 3642ga_init ( & ga , sizeof( char * ), 3 ); 3643ga_init ( & ga_abbr , sizeof( char * ), 3 ); 3644ga_init ( & ga_kind , sizeof( char * ), 3 ); 3645ga_init ( & ga_menu , sizeof( char * ), 3 ); 3646ga_init ( & ga_info , sizeof( char * ), 3 ); 3647// Loop over the items in the list. 3648TV_LIST_ITER_CONST ( retlist , li , { 3649const typval_T * tv = TV_LIST_ITEM_TV ( li ); 3650char * p = NULL ; 3651char * abbr = NULL ; 3652char * kind = NULL ; 3653char * menu = NULL ; 3654char * info = NULL ; 3655 3656if ( tv -> v_type == VAR_STRING ) { 3657if ( tv -> vval . v_string == NULL ) { 3658continue; // Skip NULL strings 3659} 3660p = xstrdup ( tv -> vval . v_string ); 3661} else if ( tv -> v_type == VAR_DICT && tv -> vval . v_dict != NULL ) { 3662dict_T * d = tv -> vval . v_dict ; 3663char * word = tv_dict_get_string ( d , "word" , false); 3664 3665if ( word == NULL ) { 3666continue; // "word" is required 3667} 3668p = xstrdup ( word ); 3669abbr = tv_dict_get_string ( d , "abbr" , true); 3670kind = tv_dict_get_string ( d , "kind" , true); 3671menu = tv_dict_get_string ( d , "menu" , true); 3672info = tv_dict_get_string ( d , "info" , true); 3673if ( abbr != NULL || kind != NULL || menu != NULL || info != NULL ) { 3674have_extra = true; 3675} 3676} else { 3677continue; // Skip other types 3678} 3679 3680GA_APPEND ( char * , & ga , p ); 3681GA_APPEND ( char * , & ga_abbr , abbr ); 3682GA_APPEND ( char * , & ga_kind , kind ); 3683GA_APPEND ( char * , & ga_menu , menu ); 3684GA_APPEND ( char * , & ga_info , info ); 3685}); 3686 3687* matches = ga . ga_data ; 3688* numMatches = ga . ga_len ; 3689if ( have_extra && ga . ga_len > 0 ) { 3690xp -> xp_files_abbr = ( char ** ) ga_abbr . ga_data ; 3691xp -> xp_files_kind = ( char ** ) ga_kind . ga_data ; 3692xp -> xp_files_menu = ( char ** ) ga_menu . ga_data ; 3693xp -> xp_files_info = ( char ** ) ga_info . ga_data ; 3694} else { 3695// No extra info collected; free the placeholder NULL entries. 3696for ( int i = 0 ; i < ga_abbr . ga_len ; i ++ ) { 3697xfree ((( char ** ) ga_abbr . ga_data )[ i ]); 3698} 3699xfree ( ga_abbr . ga_data ); 3700for ( int i = 0 ; i < ga_kind . ga_len ; i ++ ) { 3701xfree ((( char ** ) ga_kind . ga_data )[ i ]); 3702} 3703xfree ( ga_kind . ga_data ); 3704for ( int i = 0 ; i < ga_menu . ga_len ; i ++ ) { 3705xfree ((( char ** ) ga_menu . ga_data )[ i ]); 3706} 3707xfree ( ga_menu . ga_data ); 3708for ( int i = 0 ; i < ga_info . ga_len ; i ++ ) { 3709xfree ((( char ** ) ga_info . ga_data )[ i ]); 3710} 3711xfree ( ga_info . ga_data ); 3712} 3713} 3714 3715/// Expand names with a list returned by a function defined by the user. 3716static int ExpandUserList ( expand_T * xp , char *** matches , int * numMatches ) 3717{ 3718* matches = NULL ; 3719* numMatches = 0 ; 3720list_T * const retlist = call_user_expand_func ( call_func_retlist , xp ); 3721if ( retlist == NULL ) { 3722return FAIL ; 3723} 3724 3725expand_process_user_list ( retlist , matches , numMatches , xp ); 3726tv_list_unref ( retlist ); 3727return OK ; 3728} 3729 3730static int ExpandUserLua ( expand_T * xp , int * numMatches , char *** matches ) 3731{ 3732typval_T rettv = TV_INITIAL_VALUE ; 3733nlua_call_user_expand_func ( xp , & rettv ); 3734if ( rettv . v_type != VAR_LIST ) { 3735tv_clear ( & rettv ); 3736return FAIL ; 3737} 3738 3739list_T * const retlist = rettv . vval . v_list ; 3740 3741expand_process_user_list ( retlist , matches , numMatches , xp ); 3742tv_list_unref ( retlist ); 3743return OK ; 3744} 3745 3746/// Expand `file` for all comma-separated directories in `path`. 3747/// Adds matches to `ga`. 3748/// If "dirs" is true only expand directory names. 3749void globpath ( char * path , char * file , garray_T * ga , int expand_options , bool dirs ) 3750FUNC_ATTR_NONNULL_ALL 3751{ 3752char * buf = xmalloc ( MAXPATHL ); 3753 3754expand_T xpc ; 3755ExpandInit ( & xpc ); 3756xpc . xp_context = dirs ? EXPAND_DIRECTORIES : EXPAND_FILES ; 3757 3758size_t filelen = strlen ( file ); 3759 3760// Loop over all entries in {path}. 3761while ( * path != NUL ) { 3762// Copy one item of the path to buf[] and concatenate the file name. 3763 3764// length of the path portion of buf (including trailing slash). 3765size_t pathlen = copy_option_part ( & path , buf , MAXPATHL , "," ); 3766size_t seplen = ( * buf != NUL && ! after_pathsep ( buf , buf + pathlen )) 3767? STRLEN_LITERAL ( PATHSEPSTR ) : 0 ; 3768 3769if ( pathlen + seplen + filelen + 1 <= MAXPATHL ) { 3770if ( seplen > 0 ) { 3771xmemcpyz ( buf + pathlen , S_LEN ( PATHSEPSTR )); 3772pathlen += seplen ; 3773} 3774xmemcpyz ( buf + pathlen , file , filelen ); 3775 3776char ** p ; 3777int num_p = 0 ; 3778ExpandFromContext ( & xpc , buf , & p , & num_p , WILD_SILENT | expand_options ); 3779if ( num_p > 0 ) { 3780ExpandEscape ( & xpc , buf , num_p , p , WILD_SILENT | expand_options ); 3781 3782// Concatenate new results to previous ones. 3783ga_grow ( ga , num_p ); 3784// take over the pointers and put them in "ga" 3785for ( int i = 0 ; i < num_p ; i ++ ) { 3786(( char ** ) ga -> ga_data )[ ga -> ga_len ] = p [ i ]; 3787ga -> ga_len ++ ; 3788} 3789xfree ( p ); 3790} 3791} 3792} 3793 3794xfree ( buf ); 3795} 3796 3797/// Translate some keys pressed when 'wildmenu' is used. 3798int wildmenu_translate_key ( CmdlineInfo * cclp , int key , expand_T * xp , bool did_wild_list ) 3799{ 3800int c = key ; 3801 3802if ( cmdline_pum_active () || did_wild_list || wild_menu_showing ) { 3803if ( c == K_LEFT ) { 3804c = Ctrl_P ; 3805} else if ( c == K_RIGHT ) { 3806c = Ctrl_N ; 3807} 3808} 3809 3810// Hitting CR after "emenu Name.": complete submenu 3811if ( xp -> xp_context == EXPAND_MENUNAMES 3812&& cclp -> cmdpos > 1 3813&& cclp -> cmdbuff [ cclp -> cmdpos - 1 ] == '.' 3814&& cclp -> cmdbuff [ cclp -> cmdpos - 2 ] != '\\' 3815&& ( c == '\n' || c == '\r' || c == K_KENTER )) { 3816c = K_DOWN ; 3817} 3818 3819return c ; 3820} 3821 3822/// Delete characters on the command line, from "from" to the current position. 3823static void cmdline_del ( CmdlineInfo * cclp , int from ) 3824{ 3825assert ( cclp -> cmdpos <= cclp -> cmdlen ); 3826memmove ( cclp -> cmdbuff + from , cclp -> cmdbuff + cclp -> cmdpos , 3827( size_t ) cclp -> cmdlen - ( size_t ) cclp -> cmdpos + 1 ); 3828cclp -> cmdlen -= cclp -> cmdpos - from ; 3829cclp -> cmdpos = from ; 3830} 3831 3832/// Handle a key pressed when the wild menu for the menu names 3833/// (EXPAND_MENUNAMES) is displayed. 3834static int wildmenu_process_key_menunames ( CmdlineInfo * cclp , int key , expand_T * xp ) 3835{ 3836// Hitting <Down> after "emenu Name.": complete submenu 3837if ( key == K_DOWN && cclp -> cmdpos > 0 3838&& cclp -> cmdbuff [ cclp -> cmdpos - 1 ] == '.' ) { 3839key = ( int ) p_wc ; 3840KeyTyped = true; // in case the key was mapped 3841} else if ( key == K_UP ) { 3842// Hitting <Up>: Remove one submenu name in front of the 3843// cursor 3844bool found = false; 3845 3846int j = ( int )( xp -> xp_pattern - cclp -> cmdbuff ); 3847int i = 0 ; 3848while ( -- j > 0 ) { 3849// check for start of menu name 3850if ( cclp -> cmdbuff [ j ] == ' ' 3851&& cclp -> cmdbuff [ j - 1 ] != '\\' ) { 3852i = j + 1 ; 3853break; 3854} 3855// check for start of submenu name 3856if ( cclp -> cmdbuff [ j ] == '.' 3857&& cclp -> cmdbuff [ j - 1 ] != '\\' ) { 3858if ( found ) { 3859i = j + 1 ; 3860break; 3861} else { 3862found = true; 3863} 3864} 3865} 3866if ( i > 0 ) { 3867cmdline_del ( cclp , i ); 3868} 3869key = ( int ) p_wc ; 3870KeyTyped = true; // in case the key was mapped 3871xp -> xp_context = EXPAND_NOTHING ; 3872} 3873 3874return key ; 3875} 3876 3877/// Handle a key pressed when the wild menu for file names (EXPAND_FILES) or 3878/// directory names (EXPAND_DIRECTORIES) or shell command names 3879/// (EXPAND_SHELLCMD) is displayed. 3880static int wildmenu_process_key_filenames ( CmdlineInfo * cclp , int key , expand_T * xp ) 3881{ 3882char upseg [ 5 ]; 3883upseg [ 0 ] = PATHSEP ; 3884upseg [ 1 ] = '.' ; 3885upseg [ 2 ] = '.' ; 3886upseg [ 3 ] = PATHSEP ; 3887upseg [ 4 ] = NUL ; 3888 3889if ( key == K_DOWN 3890&& cclp -> cmdpos > 0 3891&& cclp -> cmdbuff [ cclp -> cmdpos - 1 ] == PATHSEP 3892&& ( cclp -> cmdpos < 3 3893|| cclp -> cmdbuff [ cclp -> cmdpos - 2 ] != '.' 3894|| cclp -> cmdbuff [ cclp -> cmdpos - 3 ] != '.' )) { 3895// go down a directory 3896key = ( int ) p_wc ; 3897KeyTyped = true; // in case the key was mapped 3898} else if ( strncmp ( xp -> xp_pattern , upseg + 1 , 3 ) == 0 && key == K_DOWN ) { 3899// If in a direct ancestor, strip off one ../ to go down 3900bool found = false; 3901 3902int j = cclp -> cmdpos ; 3903int i = ( int )( xp -> xp_pattern - cclp -> cmdbuff ); 3904while ( -- j > i ) { 3905j -= utf_head_off ( cclp -> cmdbuff , cclp -> cmdbuff + j ); 3906if ( vim_ispathsep ( cclp -> cmdbuff [ j ])) { 3907found = true; 3908break; 3909} 3910} 3911if ( found 3912&& cclp -> cmdbuff [ j - 1 ] == '.' 3913&& cclp -> cmdbuff [ j - 2 ] == '.' 3914&& ( vim_ispathsep ( cclp -> cmdbuff [ j - 3 ]) || j == i + 2 )) { 3915cmdline_del ( cclp , j - 2 ); 3916key = ( int ) p_wc ; 3917KeyTyped = true; // in case the key was mapped 3918} 3919} else if ( key == K_UP ) { 3920// go up a directory 3921bool found = false; 3922 3923int j = cclp -> cmdpos - 1 ; 3924int i = ( int )( xp -> xp_pattern - cclp -> cmdbuff ); 3925while ( -- j > i ) { 3926j -= utf_head_off ( cclp -> cmdbuff , cclp -> cmdbuff + j ); 3927if ( vim_ispathsep ( cclp -> cmdbuff [ j ]) 3928#ifdef BACKSLASH_IN_FILENAME 3929&& vim_strchr ( " *?[{`$%#" , ( uint8_t ) cclp -> cmdbuff [ j + 1 ]) == NULL 3930#endif 3931) { 3932if ( found ) { 3933i = j + 1 ; 3934break; 3935} else { 3936found = true; 3937} 3938} 3939} 3940 3941if (! found ) { 3942j = i ; 3943} else if ( strncmp ( cclp -> cmdbuff + j , upseg , 4 ) == 0 ) { 3944j += 4 ; 3945} else if ( strncmp ( cclp -> cmdbuff + j , upseg + 1 , 3 ) == 0 3946&& j == i ) { 3947j += 3 ; 3948} else { 3949j = 0 ; 3950} 3951 3952if ( j > 0 ) { 3953// TODO(tarruda): this is only for DOS/Unix systems - need to put in 3954// machine-specific stuff here and in upseg init 3955cmdline_del ( cclp , j ); 3956put_on_cmdline ( upseg + 1 , 3 , false); 3957} else if ( cclp -> cmdpos > i ) { 3958cmdline_del ( cclp , i ); 3959} 3960 3961// Now complete in the new directory. Set KeyTyped in case the 3962// Up key came from a mapping. 3963key = ( int ) p_wc ; 3964KeyTyped = true; 3965} 3966 3967return key ; 3968} 3969 3970/// Handle a key pressed when wild menu is displayed 3971int wildmenu_process_key ( CmdlineInfo * cclp , int key , expand_T * xp ) 3972{ 3973// Special translations for 'wildmenu' 3974if ( xp -> xp_context == EXPAND_MENUNAMES ) { 3975return wildmenu_process_key_menunames ( cclp , key , xp ); 3976} 3977if ( xp -> xp_context == EXPAND_FILES 3978|| xp -> xp_context == EXPAND_DIRECTORIES 3979|| xp -> xp_context == EXPAND_SHELLCMD ) { 3980return wildmenu_process_key_filenames ( cclp , key , xp ); 3981} 3982 3983return key ; 3984} 3985 3986/// Free expanded names when finished walking through the matches 3987void wildmenu_cleanup ( CmdlineInfo * cclp ) 3988{ 3989if (! p_wmnu || wild_menu_showing == 0 ) { 3990return; 3991} 3992 3993const bool skt = KeyTyped ; 3994const int old_RedrawingDisabled = RedrawingDisabled ; 3995 3996if ( cclp -> input_fn ) { 3997RedrawingDisabled = 0 ; 3998} 3999 4000// Clear highlighting applied during wildmenu activity 4001set_no_hlsearch (true); 4002 4003if ( wild_menu_showing == WM_SCROLLED ) { 4004// Entered command line, move it up 4005cmdline_row -- ; 4006redrawcmd (); 4007wild_menu_showing = 0 ; 4008} else if ( save_p_ls != -1 ) { 4009// restore 'laststatus' and 'winminheight' 4010p_ls = save_p_ls ; 4011p_wmh = save_p_wmh ; 4012last_status (false); 4013update_screen (); // redraw the screen NOW 4014redrawcmd (); 4015save_p_ls = -1 ; 4016wild_menu_showing = 0 ; 4017} else { 4018win_redraw_last_status ( topframe ); 4019wild_menu_showing = 0 ; // must be before redraw_statuslines #8385 4020redraw_statuslines (); 4021} 4022KeyTyped = skt ; 4023if ( cclp -> input_fn ) { 4024RedrawingDisabled = old_RedrawingDisabled ; 4025} 4026} 4027 4028/// "getcompletion()" function 4029void f_getcompletion ( typval_T * argvars , typval_T * rettv , EvalFuncData fptr ) 4030{ 4031expand_T xpc ; 4032bool filtered = false; 4033int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH 4034| WILD_NO_BEEP | WILD_HOME_REPLACE ; 4035 4036if ( tv_check_for_string_arg ( argvars , 1 ) == FAIL ) { 4037return; 4038} 4039const char * const type = tv_get_string ( & argvars [ 1 ]); 4040 4041if ( argvars [ 2 ]. v_type != VAR_UNKNOWN ) { 4042filtered = ( bool ) tv_get_bool_chk ( & argvars [ 2 ], NULL ); 4043} 4044 4045if ( p_wic ) { 4046options |= WILD_ICASE ; 4047} 4048 4049// For filtered results, 'wildignore' is used 4050if (! filtered ) { 4051options |= WILD_KEEP_ALL ; 4052} 4053 4054if ( argvars [ 0 ]. v_type != VAR_STRING ) { 4055if ( tv_get_string_chk ( & argvars [ 0 ]) != NULL ) { 4056emsg ( _ ( e_invarg )); 4057} 4058return; 4059} 4060const char * const pattern = tv_get_string ( & argvars [ 0 ]); 4061const char * pattern_start = pattern ; 4062 4063if ( strcmp ( type , "cmdline" ) == 0 ) { 4064const int cmdline_len = ( int ) strlen ( pattern ); 4065set_cmd_context ( & xpc , ( char * ) pattern , cmdline_len , cmdline_len , false); 4066pattern_start = xpc . xp_pattern ; 4067xpc . xp_pattern_len = strlen ( xpc . xp_pattern ); 4068xpc . xp_col = cmdline_len ; 4069goto theend ; 4070} 4071 4072ExpandInit ( & xpc ); 4073xpc . xp_pattern = ( char * ) pattern ; 4074xpc . xp_pattern_len = strlen ( xpc . xp_pattern ); 4075xpc . xp_line = ( char * ) pattern ; 4076 4077xpc . xp_context = cmdcomplete_str_to_type ( type ); 4078switch ( xpc . xp_context ) { 4079case EXPAND_NOTHING : 4080semsg ( _ ( e_invarg2 ), type ); 4081return; 4082 4083case EXPAND_USER_DEFINED : 4084// Must be "custom,funcname" pattern 4085if ( strncmp ( type , "custom," , 7 ) != 0 ) { 4086semsg ( _ ( e_invarg2 ), type ); 4087return; 4088} 4089 4090xpc . xp_arg = ( char * )( type + 7 ); 4091break; 4092 4093case EXPAND_USER_LIST : 4094// Must be "customlist,funcname" pattern 4095if ( strncmp ( type , "customlist," , 11 ) != 0 ) { 4096semsg ( _ ( e_invarg2 ), type ); 4097return; 4098} 4099 4100xpc . xp_arg = ( char * )( type + 11 ); 4101break; 4102 4103case EXPAND_MENUS : 4104set_context_in_menu_cmd ( & xpc , "menu" , xpc . xp_pattern , false); 4105xpc . xp_pattern_len -= ( size_t )( xpc . xp_pattern - pattern_start ); 4106break; 4107 4108case EXPAND_SIGN : 4109set_context_in_sign_cmd ( & xpc , xpc . xp_pattern ); 4110xpc . xp_pattern_len -= ( size_t )( xpc . xp_pattern - pattern_start ); 4111break; 4112 4113case EXPAND_RUNTIME : 4114set_context_in_runtime_cmd ( & xpc , xpc . xp_pattern ); 4115xpc . xp_pattern_len -= ( size_t )( xpc . xp_pattern - pattern_start ); 4116break; 4117 4118case EXPAND_SHELLCMDLINE : { 4119int context = EXPAND_SHELLCMDLINE ; 4120set_context_for_wildcard_arg ( NULL , xpc . xp_pattern , false, & xpc , & context ); 4121xpc . xp_pattern_len -= ( size_t )( xpc . xp_pattern - pattern_start ); 4122break; 4123} 4124 4125case EXPAND_FILETYPECMD : 4126filetype_expand_what = EXP_FILETYPECMD_ALL ; 4127break; 4128 4129default: 4130break; 4131} 4132 4133theend : 4134if ( xpc . xp_context == EXPAND_LUA ) { 4135xpc . xp_col = ( int ) strlen ( xpc . xp_line ); 4136nlua_expand_pat ( & xpc ); 4137xpc . xp_pattern_len -= ( size_t )( xpc . xp_pattern - pattern_start ); 4138} 4139char * pat ; 4140if ( cmdline_fuzzy_completion_supported ( & xpc )) { 4141// when fuzzy matching, don't modify the search string 4142pat = xmemdupz ( xpc . xp_pattern , xpc . xp_pattern_len ); 4143} else { 4144pat = addstar ( xpc . xp_pattern , xpc . xp_pattern_len , xpc . xp_context ); 4145} 4146 4147ExpandOne ( & xpc , pat , NULL , options , WILD_ALL_KEEP ); 4148tv_list_alloc_ret ( rettv , xpc . xp_numfiles ); 4149 4150for ( int i = 0 ; i < xpc . xp_numfiles ; i ++ ) { 4151tv_list_append_string ( rettv -> vval . v_list , xpc . xp_files [ i ], -1 ); 4152} 4153xfree ( pat ); 4154ExpandCleanup ( & xpc ); 4155} 4156 4157/// "getcompletiontype()" function 4158void f_getcompletiontype ( typval_T * argvars , typval_T * rettv , EvalFuncData fptr ) 4159{ 4160rettv -> v_type = VAR_STRING ; 4161rettv -> vval . v_string = NULL ; 4162 4163if ( tv_check_for_string_arg ( argvars , 0 ) == FAIL ) { 4164return; 4165} 4166 4167const char * pat = tv_get_string ( & argvars [ 0 ]); 4168expand_T xpc ; 4169ExpandInit ( & xpc ); 4170 4171int cmdline_len = ( int ) strlen ( pat ); 4172set_cmd_context ( & xpc , ( char * ) pat , cmdline_len , cmdline_len , false); 4173rettv -> vval . v_string = cmdcomplete_type_to_str ( xpc . xp_context , xpc . xp_arg ); 4174 4175ExpandCleanup ( & xpc ); 4176} 4177 4178/// "cmdcomplete_info()" function 4179void f_cmdcomplete_info ( typval_T * argvars , typval_T * rettv , EvalFuncData fptr ) 4180{ 4181CmdlineInfo * ccline = get_cmdline_info (); 4182 4183tv_dict_alloc_ret ( rettv ); 4184if ( ccline == NULL || ccline -> xpc == NULL || ccline -> xpc -> xp_files == NULL ) { 4185return; 4186} 4187 4188dict_T * retdict = rettv -> vval . v_dict ; 4189int ret = tv_dict_add_str_len ( retdict , S_LEN ( "cmdline_orig" ), 4190cmdline_orig . data , ( int ) cmdline_orig . size ); 4191if ( ret == OK ) { 4192ret = tv_dict_add_nr ( retdict , S_LEN ( "pum_visible" ), pum_visible ()); 4193} 4194if ( ret == OK ) { 4195ret = tv_dict_add_nr ( retdict , S_LEN ( "selected" ), ccline -> xpc -> xp_selected ); 4196} 4197if ( ret == OK ) { 4198list_T * li = tv_list_alloc ( ccline -> xpc -> xp_numfiles ); 4199ret = tv_dict_add_list ( retdict , S_LEN ( "matches" ), li ); 4200for ( int idx = 0 ; ret == OK && idx < ccline -> xpc -> xp_numfiles ; idx ++ ) { 4201tv_list_append_string ( li , ccline -> xpc -> xp_files [ idx ], -1 ); 4202} 4203} 4204} 4205 4206/// Copy a substring from the current buffer (curbuf), spanning from the given 4207/// 'start' position to the word boundary after 'end' position. 4208/// The copied string is stored in '*match', and the actual end position of the 4209/// matched text is returned in '*match_end'. 4210static int copy_substring_from_pos ( pos_T * start , pos_T * end , char ** match , pos_T * match_end ) 4211{ 4212bool exacttext = wop_flags & kOptWopFlagExacttext ; 4213 4214if ( start -> lnum > end -> lnum 4215|| ( start -> lnum == end -> lnum && start -> col >= end -> col )) { 4216return FAIL ; // invalid range 4217} 4218 4219// Use a growable string (ga) 4220garray_T ga ; 4221ga_init ( & ga , 1 , 128 ); 4222 4223// Append start line from start->col to end 4224char * start_line = ml_get ( start -> lnum ); 4225char * start_ptr = start_line + start -> col ; 4226bool is_single_line = start -> lnum == end -> lnum ; 4227 4228int segment_len = is_single_line ? ( int )( end -> col - start -> col ) 4229: ( int )( ml_get_len ( start -> lnum ) - start -> col ); 4230ga_grow ( & ga , segment_len + 2 ); 4231ga_concat_len ( & ga , start_ptr , ( size_t ) segment_len ); 4232if (! is_single_line ) { 4233if ( exacttext ) { 4234GA_CONCAT_LITERAL ( & ga , "\\n" ); 4235} else { 4236ga_append ( & ga , '\n' ); 4237} 4238} 4239 4240// Append full lines between start and end 4241if (! is_single_line ) { 4242for ( linenr_T lnum = start -> lnum + 1 ; lnum < end -> lnum ; lnum ++ ) { 4243char * line = ml_get ( lnum ); 4244int linelen = ml_get_len ( lnum ); 4245ga_grow ( & ga , linelen + 2 ); 4246ga_concat_len ( & ga , line , ( size_t ) linelen ); 4247if ( exacttext ) { 4248GA_CONCAT_LITERAL ( & ga , "\\n" ); 4249} else { 4250ga_append ( & ga , '\n' ); 4251} 4252} 4253} 4254 4255// Append partial end line (up to word end) 4256char * end_line = ml_get ( end -> lnum ); 4257char * word_end = find_word_end ( end_line + end -> col ); 4258segment_len = ( int )( word_end - end_line ); 4259ga_grow ( & ga , segment_len ); 4260ga_concat_len ( & ga , end_line + ( is_single_line ? end -> col : 0 ), 4261( size_t )( segment_len - ( is_single_line ? end -> col : 0 ))); 4262 4263// Null-terminate 4264ga_grow ( & ga , 1 ); 4265ga_append ( & ga , NUL ); 4266 4267* match = ( char * ) ga . ga_data ; 4268match_end -> lnum = end -> lnum ; 4269match_end -> col = segment_len ; 4270 4271return OK ; 4272} 4273 4274/// Returns true if the given string `str` matches the regex pattern `pat`. 4275/// Honors the 'ignorecase' (p_ic) and 'smartcase' (p_scs) settings to determine 4276/// case sensitivity. 4277static bool is_regex_match ( char * pat , char * str ) 4278{ 4279if ( strcmp ( pat , str ) == 0 ) { 4280return true; 4281} 4282 4283regmatch_T regmatch ; 4284 4285emsg_off ++ ; 4286msg_silent ++ ; 4287regmatch . regprog = vim_regcomp ( pat , RE_MAGIC + RE_STRING ); 4288emsg_off -- ; 4289msg_silent -- ; 4290 4291if ( regmatch . regprog == NULL ) { 4292return false; 4293} 4294regmatch . rm_ic = p_ic ; 4295if ( p_ic && p_scs ) { 4296regmatch . rm_ic = ! pat_has_uppercase ( pat ); 4297} 4298 4299emsg_off ++ ; 4300msg_silent ++ ; 4301bool result = vim_regexec_nl ( & regmatch , str , ( colnr_T ) 0 ); 4302emsg_off -- ; 4303msg_silent -- ; 4304 4305vim_regfree ( regmatch . regprog ); 4306return result ; 4307} 4308 4309/// Constructs a new match string by appending text from the buffer (starting at 4310/// end_match_pos) to the given pattern `pat`. The result is a concatenation of 4311/// `pat` and the word following end_match_pos. 4312/// If 'lowercase' is true, the appended text is converted to lowercase before 4313/// being combined. Returns the newly allocated match string, or NULL on failure. 4314static char * concat_pattern_with_buffer_match ( char * pat , int pat_len , pos_T * end_match_pos , 4315bool lowercase ) 4316FUNC_ATTR_NONNULL_RET 4317{ 4318char * line = ml_get ( end_match_pos -> lnum ); 4319char * word_end = find_word_end ( line + end_match_pos -> col ); 4320int match_len = ( int )( word_end - ( line + end_match_pos -> col )); 4321char * match = xmalloc (( size_t ) match_len + ( size_t ) pat_len + 1 ); // +1 for NUL 4322 4323memmove ( match , pat , ( size_t ) pat_len ); 4324if ( match_len > 0 ) { 4325if ( lowercase ) { 4326char * mword = xstrnsave ( line + end_match_pos -> col , ( size_t ) match_len ); 4327char * lower = strcase_save ( mword , false); 4328xfree ( mword ); 4329memmove ( match + pat_len , lower , ( size_t ) match_len ); 4330xfree ( lower ); 4331} else { 4332memmove ( match + pat_len , line + end_match_pos -> col , ( size_t ) match_len ); 4333} 4334} 4335match [ pat_len + match_len ] = NUL ; 4336return match ; 4337} 4338 4339/// Search for strings matching "pat" in the specified range and return them. 4340/// Returns OK on success, FAIL otherwise. 4341/// 4342/// @param pat pattern to match 4343/// @param dir FORWARD or BACKWARD 4344/// @param[out] matches array with matched string 4345/// @param[out] numMatches number of matches 4346static int expand_pattern_in_buf ( char * pat , Direction dir , char *** matches , int * numMatches ) 4347{ 4348bool exacttext = wop_flags & kOptWopFlagExacttext ; 4349bool has_range = Search . first_line != 0 ; 4350 4351* matches = NULL ; 4352* numMatches = 0 ; 4353 4354if ( pat == NULL || * pat == NUL ) { 4355return FAIL ; 4356} 4357 4358int pat_len = ( int ) strlen ( pat ); 4359pos_T cur_match_pos = { 0 }, prev_match_pos = { 0 }; 4360if ( has_range ) { 4361cur_match_pos . lnum = Search . first_line ; 4362} else { 4363cur_match_pos = pre_incsearch_pos ; 4364} 4365 4366int search_flags = SEARCH_OPT | SEARCH_NOOF | SEARCH_PEEK | SEARCH_NFMSG 4367| ( has_range ? SEARCH_START : 0 ); 4368 4369garray_T ga ; 4370ga_init ( & ga , sizeof( char * ), 10 ); // Use growable array of char * 4371 4372pos_T end_match_pos , word_end_pos ; 4373bool looped_around = false; 4374bool compl_started = false; 4375char * match , * full_match ; 4376 4377while (true) { 4378emsg_off ++ ; 4379msg_silent ++ ; 4380int found_new_match = searchit ( NULL , curbuf , & cur_match_pos , 4381& end_match_pos , dir , pat , ( size_t ) pat_len , 1L , 4382search_flags , RE_LAST , p_magic , NULL ); 4383msg_silent -- ; 4384emsg_off -- ; 4385 4386if ( found_new_match == FAIL ) { 4387break; 4388} 4389 4390// If in range mode, check if match is within the range 4391if ( has_range && ( cur_match_pos . lnum < Search . first_line 4392|| cur_match_pos . lnum > Search . last_line )) { 4393break; 4394} 4395 4396if ( compl_started ) { 4397// If we've looped back to an earlier match, stop 4398if (( dir == FORWARD && ltoreq ( cur_match_pos , prev_match_pos )) 4399|| ( dir == BACKWARD && ltoreq ( prev_match_pos , cur_match_pos ))) { 4400if ( looped_around ) { 4401break; 4402} else { 4403looped_around = true; 4404} 4405} 4406} 4407 4408compl_started = true; 4409prev_match_pos = cur_match_pos ; 4410 4411// Abort if user typed a character or interrupted 4412if ( char_avail () || got_int ) { 4413if ( got_int ) { 4414( void ) vpeekc (); // Remove <C-C> from input stream 4415got_int = false; // Don't abandon the command line 4416} 4417goto cleanup ; 4418} 4419 4420// searchit() can return line number +1 past the last line when 4421// searching for "foo\n" if "foo" is at end of buffer. 4422if ( end_match_pos . lnum > curbuf -> b_ml . ml_line_count ) { 4423cur_match_pos . lnum = 1 ; 4424cur_match_pos . col = 0 ; 4425cur_match_pos . coladd = 0 ; 4426continue; 4427} 4428 4429// Extract the matching text prepended to completed word 4430if ( copy_substring_from_pos ( & cur_match_pos , & end_match_pos , & full_match , 4431& word_end_pos ) == FAIL ) { 4432break; 4433} 4434 4435if ( exacttext ) { 4436match = full_match ; 4437} else { 4438// Construct a new match from completed word appended to pattern itself 4439match = concat_pattern_with_buffer_match ( pat , pat_len , & end_match_pos , false); 4440 4441// The regex pattern may include '\C' or '\c'. First, try matching the 4442// buffer word as-is. If it doesn't match, try again with the lowercase 4443// version of the word to handle smartcase behavior. 4444if (! is_regex_match ( match , full_match )) { 4445xfree ( match ); 4446match = concat_pattern_with_buffer_match ( pat , pat_len , & end_match_pos , true); 4447if (! is_regex_match ( match , full_match )) { 4448xfree ( match ); 4449xfree ( full_match ); 4450continue; 4451} 4452} 4453xfree ( full_match ); 4454} 4455 4456// Include this match if it is not a duplicate 4457for ( int i = 0 ; i < ga . ga_len ; i ++ ) { 4458if ( strcmp ( match , (( char ** ) ga . ga_data )[ i ]) == 0 ) { 4459XFREE_CLEAR ( match ); 4460break; 4461} 4462} 4463if ( match != NULL ) { 4464ga_grow ( & ga , 1 ); 4465(( char ** ) ga . ga_data )[ ga . ga_len ++ ] = match ; 4466if ( ga . ga_len > TAG_MANY ) { 4467break; 4468} 4469} 4470if ( has_range ) { 4471cur_match_pos = word_end_pos ; 4472} 4473} 4474 4475* matches = ( char ** ) ga . ga_data ; 4476* numMatches = ga . ga_len ; 4477return OK ; 4478 4479cleanup : 4480ga_clear_strings ( & ga ); 4481return FAIL ; 4482}