diff options
35 files changed, 3697 insertions, 2958 deletions
diff --git a/runtime/doc/options.txt b/runtime/doc/options.txt index b5e8b7a99a..2e0c1f8cc4 100644 --- a/runtime/doc/options.txt +++ b/runtime/doc/options.txt @@ -7020,7 +7020,8 @@ A jump table for the options with a short description can be found at |Q_op|. *'wildoptions'* *'wop'* 'wildoptions' 'wop' string (default "pum,tagfile") global - List of words that change how |cmdline-completion| is done. + A list of words that change how |cmdline-completion| is done. + The following values are supported: pum Display the completion matches using the popup menu in the same style as the |ins-completion-menu|. tagfile When using CTRL-D to list matching tags, the kind of diff --git a/runtime/doc/vim_diff.txt b/runtime/doc/vim_diff.txt index 76beaf9830..53effa1443 100644 --- a/runtime/doc/vim_diff.txt +++ b/runtime/doc/vim_diff.txt @@ -207,7 +207,6 @@ Commands: |:checkhealth| |:drop| is always available |:Man| is available by default, with many improvements such as completion - |:sign-define| accepts a `numhl` argument, to highlight the line number |:match| can be invoked before highlight group is defined |:source| works with Lua User commands can support |:command-preview| to show results as you type @@ -374,6 +373,9 @@ Commands: |:doautocmd| does not warn about "No matching autocommands". |:wincmd| accepts a count. +Command line completion: + The meanings of arrow keys do not change depending on 'wildoptions'. + Functions: |input()| and |inputdialog()| support for each other’s features (return on cancel and completion respectively) via dictionary argument (replaces all diff --git a/src/nvim/arglist.c b/src/nvim/arglist.c index 7d8917cc73..0be83f0c05 100644 --- a/src/nvim/arglist.c +++ b/src/nvim/arglist.c @@ -10,6 +10,7 @@ #include "nvim/buffer.h" #include "nvim/charset.h" #include "nvim/eval.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_getln.h" #include "nvim/fileio.h" diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index 1ff0140162..ab5b32bf3e 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -34,6 +34,7 @@ #include "nvim/change.h" #include "nvim/channel.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cursor.h" #include "nvim/decoration.h" #include "nvim/diff.h" diff --git a/src/nvim/cmdexpand.c b/src/nvim/cmdexpand.c new file mode 100644 index 0000000000..e82e98ba4e --- /dev/null +++ b/src/nvim/cmdexpand.c @@ -0,0 +1,2829 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check +// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com + +// cmdexpand.c: functions for command-line completion + +#include "nvim/api/private/helpers.h" +#include "nvim/arglist.h" +#include "nvim/ascii.h" +#include "nvim/buffer.h" +#include "nvim/charset.h" +#include "nvim/cmdexpand.h" +#include "nvim/cmdhist.h" +#include "nvim/drawscreen.h" +#include "nvim/eval.h" +#include "nvim/eval/funcs.h" +#include "nvim/eval/userfunc.h" +#include "nvim/ex_cmds.h" +#include "nvim/ex_cmds2.h" +#include "nvim/ex_docmd.h" +#include "nvim/ex_getln.h" +#include "nvim/garray.h" +#include "nvim/getchar.h" +#include "nvim/help.h" +#include "nvim/highlight_group.h" +#include "nvim/if_cscope.h" +#include "nvim/lua/executor.h" +#include "nvim/mapping.h" +#include "nvim/menu.h" +#include "nvim/option.h" +#include "nvim/os/os.h" +#include "nvim/popupmenu.h" +#include "nvim/profile.h" +#include "nvim/regexp.h" +#include "nvim/screen.h" +#include "nvim/search.h" +#include "nvim/sign.h" +#include "nvim/strings.h" +#include "nvim/syntax.h" +#include "nvim/tag.h" +#include "nvim/types.h" +#include "nvim/ui.h" +#include "nvim/usercmd.h" +#include "nvim/vim.h" +#include "nvim/window.h" + +/// Type used by ExpandGeneric() +typedef char *(*CompleteListItemGetter)(expand_T *, int); + +/// Type used by call_user_expand_func +typedef void *(*user_expand_func_T)(const char_u *, int, typval_T *); + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "cmdexpand.c.generated.h" +#endif + +static int cmd_showtail; ///< Only show path tail in lists ? + +/// "compl_match_array" points the currently displayed list of entries in the +/// popup menu. It is NULL when there is no popup menu. +static pumitem_T *compl_match_array = NULL; +static int compl_match_arraysize; +/// First column in cmdline of the matched item for completion. +static int compl_startcol; +static int compl_selected; + +static int sort_func_compare(const void *s1, const void *s2) +{ + char_u *p1 = *(char_u **)s1; + char_u *p2 = *(char_u **)s2; + + if (*p1 != '<' && *p2 == '<') { + return -1; + } + if (*p1 == '<' && *p2 != '<') { + return 1; + } + return STRCMP(p1, p2); +} + +static void ExpandEscape(expand_T *xp, char_u *str, int numfiles, char **files, int options) +{ + int i; + char_u *p; + const int vse_what = xp->xp_context == EXPAND_BUFFERS ? VSE_BUFFER : VSE_NONE; + + // May change home directory back to "~" + if (options & WILD_HOME_REPLACE) { + tilde_replace(str, numfiles, files); + } + + if (options & WILD_ESCAPE) { + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_FILES_IN_PATH + || xp->xp_context == EXPAND_SHELLCMD + || xp->xp_context == EXPAND_BUFFERS + || xp->xp_context == EXPAND_DIRECTORIES) { + // Insert a backslash into a file name before a space, \, %, # + // and wildmatch characters, except '~'. + for (i = 0; i < numfiles; i++) { + // for ":set path=" we need to escape spaces twice + if (xp->xp_backslash == XP_BS_THREE) { + p = vim_strsave_escaped((char_u *)files[i], (char_u *)" "); + xfree(files[i]); + files[i] = (char *)p; +#if defined(BACKSLASH_IN_FILENAME) + p = vim_strsave_escaped(files[i], (char_u *)" "); + xfree(files[i]); + files[i] = p; +#endif + } +#ifdef BACKSLASH_IN_FILENAME + p = (char_u *)vim_strsave_fnameescape((const char *)files[i], vse_what); +#else + p = (char_u *)vim_strsave_fnameescape((const char *)files[i], + xp->xp_shell ? VSE_SHELL : vse_what); +#endif + xfree(files[i]); + files[i] = (char *)p; + + // If 'str' starts with "\~", replace "~" at start of + // files[i] with "\~". + if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~') { + escape_fname(&files[i]); + } + } + xp->xp_backslash = XP_BS_NONE; + + // If the first file starts with a '+' escape it. Otherwise it + // could be seen as "+cmd". + if (*files[0] == '+') { + escape_fname(&files[0]); + } + } else if (xp->xp_context == EXPAND_TAGS) { + // Insert a backslash before characters in a tag name that + // would terminate the ":tag" command. + for (i = 0; i < numfiles; i++) { + p = vim_strsave_escaped((char_u *)files[i], (char_u *)"\\|\""); + xfree(files[i]); + files[i] = (char *)p; + } + } + } +} + +/// Return FAIL if this is not an appropriate context in which to do +/// completion of anything, return OK if it is (even if there are no matches). +/// For the caller, this means that the character is just passed through like a +/// normal character (instead of being expanded). This allows :s/^I^D etc. +/// +/// @param options extra options for ExpandOne() +/// @param escape if true, escape the returned matches +int nextwild(expand_T *xp, int type, int options, bool escape) +{ + CmdlineInfo *const ccline = get_cmdline_info(); + int i, j; + char_u *p1; + char_u *p2; + int difflen; + + if (xp->xp_numfiles == -1) { + set_expand_context(xp); + cmd_showtail = expand_showtail(xp); + } + + if (xp->xp_context == EXPAND_UNSUCCESSFUL) { + beep_flush(); + return OK; // Something illegal on command line + } + if (xp->xp_context == EXPAND_NOTHING) { + // Caller can use the character as a normal char instead + return FAIL; + } + + if (!(ui_has(kUICmdline) || ui_has(kUIWildmenu))) { + msg_puts("..."); // show that we are busy + ui_flush(); + } + + i = (int)((char_u *)xp->xp_pattern - ccline->cmdbuff); + assert(ccline->cmdpos >= i); + xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i; + + if (type == WILD_NEXT || type == WILD_PREV) { + // Get next/previous match for a previous expanded pattern. + p2 = ExpandOne(xp, NULL, NULL, 0, type); + } else { + // Translate string into pattern and expand it. + p1 = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); + const int use_options = (options + | WILD_HOME_REPLACE + | WILD_ADD_SLASH + | WILD_SILENT + | (escape ? WILD_ESCAPE : 0) + | (p_wic ? WILD_ICASE : 0)); + p2 = ExpandOne(xp, p1, vim_strnsave(&ccline->cmdbuff[i], xp->xp_pattern_len), + use_options, type); + xfree(p1); + + // xp->xp_pattern might have been modified by ExpandOne (for example, + // in lua completion), so recompute the pattern index and length + i = (int)((char_u *)xp->xp_pattern - ccline->cmdbuff); + xp->xp_pattern_len = (size_t)ccline->cmdpos - (size_t)i; + + // Longest match: make sure it is not shorter, happens with :help. + if (p2 != NULL && type == WILD_LONGEST) { + for (j = 0; (size_t)j < xp->xp_pattern_len; j++) { + if (ccline->cmdbuff[i + j] == '*' + || ccline->cmdbuff[i + j] == '?') { + break; + } + } + if ((int)STRLEN(p2) < j) { + XFREE_CLEAR(p2); + } + } + } + + if (p2 != NULL && !got_int) { + difflen = (int)STRLEN(p2) - (int)(xp->xp_pattern_len); + if (ccline->cmdlen + difflen + 4 > ccline->cmdbufflen) { + realloc_cmdbuff(ccline->cmdlen + difflen + 4); + xp->xp_pattern = (char *)ccline->cmdbuff + i; + } + assert(ccline->cmdpos <= ccline->cmdlen); + memmove(&ccline->cmdbuff[ccline->cmdpos + difflen], + &ccline->cmdbuff[ccline->cmdpos], + (size_t)ccline->cmdlen - (size_t)ccline->cmdpos + 1); + memmove(&ccline->cmdbuff[i], p2, STRLEN(p2)); + ccline->cmdlen += difflen; + ccline->cmdpos += difflen; + } + xfree(p2); + + redrawcmd(); + cursorcmd(); + + // When expanding a ":map" command and no matches are found, assume that + // the key is supposed to be inserted literally + if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL) { + return FAIL; + } + + if (xp->xp_numfiles <= 0 && p2 == NULL) { + beep_flush(); + } else if (xp->xp_numfiles == 1) { + // free expanded pattern + (void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE); + } + + return OK; +} + +void cmdline_pum_display(bool changed_array) +{ + pum_display(compl_match_array, compl_match_arraysize, compl_selected, + changed_array, compl_startcol); +} + +bool cmdline_pum_active(void) +{ + // compl_match_array != NULL should already imply pum_visible() in Nvim. + return compl_match_array != NULL; +} + +/// Remove the cmdline completion popup menu +void cmdline_pum_remove(void) +{ + pum_undisplay(true); + XFREE_CLEAR(compl_match_array); +} + +void cmdline_pum_cleanup(CmdlineInfo *cclp) +{ + cmdline_pum_remove(); + wildmenu_cleanup(cclp); +} + +/// Do wildcard expansion on the string 'str'. +/// Chars that should not be expanded must be preceded with a backslash. +/// Return a pointer to allocated memory containing the new string. +/// Return NULL for failure. +/// +/// "orig" is the originally expanded string, copied to allocated memory. It +/// should either be kept in orig_save or freed. When "mode" is WILD_NEXT or +/// WILD_PREV "orig" should be NULL. +/// +/// Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode" +/// is WILD_EXPAND_FREE or WILD_ALL. +/// +/// mode = WILD_FREE: just free previously expanded matches +/// mode = WILD_EXPAND_FREE: normal expansion, do not keep matches +/// mode = WILD_EXPAND_KEEP: normal expansion, keep matches +/// mode = WILD_NEXT: use next match in multiple match, wrap to first +/// mode = WILD_PREV: use previous match in multiple match, wrap to first +/// mode = WILD_ALL: return all matches concatenated +/// mode = WILD_LONGEST: return longest matched part +/// mode = WILD_ALL_KEEP: get all matches, keep matches +/// +/// options = WILD_LIST_NOTFOUND: list entries without a match +/// options = WILD_HOME_REPLACE: do home_replace() for buffer names +/// options = WILD_USE_NL: Use '\n' for WILD_ALL +/// options = WILD_NO_BEEP: Don't beep for multiple matches +/// options = WILD_ADD_SLASH: add a slash after directory names +/// options = WILD_KEEP_ALL: don't remove 'wildignore' entries +/// options = WILD_SILENT: don't print warning messages +/// options = WILD_ESCAPE: put backslash before special chars +/// options = WILD_ICASE: ignore case for files +/// +/// The variables xp->xp_context and xp->xp_backslash must have been set! +/// +/// @param orig allocated copy of original of expanded string +char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode) +{ + char_u *ss = NULL; + static int findex; + static char_u *orig_save = NULL; // kept value of orig + int orig_saved = false; + int i; + int non_suf_match; // number without matching suffix + + // first handle the case of using an old match + if (mode == WILD_NEXT || mode == WILD_PREV) { + if (xp->xp_numfiles > 0) { + if (mode == WILD_PREV) { + if (findex == -1) { + findex = xp->xp_numfiles; + } + findex--; + } else { // mode == WILD_NEXT + findex++; + } + + // When wrapping around, return the original string, set findex to + // -1. + if (findex < 0) { + if (orig_save == NULL) { + findex = xp->xp_numfiles - 1; + } else { + findex = -1; + } + } + if (findex >= xp->xp_numfiles) { + if (orig_save == NULL) { + findex = 0; + } else { + findex = -1; + } + } + if (compl_match_array) { + compl_selected = findex; + cmdline_pum_display(false); + } else if (p_wmnu) { + redraw_wildmenu(xp, xp->xp_numfiles, xp->xp_files, findex, cmd_showtail); + } + if (findex == -1) { + return vim_strsave(orig_save); + } + return vim_strsave((char_u *)xp->xp_files[findex]); + } else { + return NULL; + } + } + + if (mode == WILD_CANCEL) { + ss = vim_strsave(orig_save ? orig_save : (char_u *)""); + } else if (mode == WILD_APPLY) { + ss = vim_strsave(findex == -1 ? (orig_save ? orig_save : (char_u *)"") : + (char_u *)xp->xp_files[findex]); + } + + // free old names + if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST) { + FreeWild(xp->xp_numfiles, xp->xp_files); + xp->xp_numfiles = -1; + XFREE_CLEAR(orig_save); + } + findex = 0; + + if (mode == WILD_FREE) { // only release file name + return NULL; + } + + if (xp->xp_numfiles == -1 && mode != WILD_APPLY && mode != WILD_CANCEL) { + xfree(orig_save); + orig_save = orig; + orig_saved = true; + + // Do the expansion. + if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files, options) == FAIL) { +#ifdef FNAME_ILLEGAL + // Illegal file name has been silently skipped. But when there + // are wildcards, the real problem is that there was no match, + // causing the pattern to be added, which has illegal characters. + if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND)) { + semsg(_(e_nomatch2), str); + } +#endif + } else if (xp->xp_numfiles == 0) { + if (!(options & WILD_SILENT)) { + semsg(_(e_nomatch2), str); + } + } else { + // Escape the matches for use on the command line. + ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options); + + // Check for matching suffixes in file names. + if (mode != WILD_ALL && mode != WILD_ALL_KEEP + && mode != WILD_LONGEST) { + if (xp->xp_numfiles) { + non_suf_match = xp->xp_numfiles; + } else { + non_suf_match = 1; + } + if ((xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_DIRECTORIES) + && xp->xp_numfiles > 1) { + // More than one match; check suffix. + // The files will have been sorted on matching suffix in + // expand_wildcards, only need to check the first two. + non_suf_match = 0; + for (i = 0; i < 2; i++) { + if (match_suffix((char_u *)xp->xp_files[i])) { + non_suf_match++; + } + } + } + if (non_suf_match != 1) { + // Can we ever get here unless it's while expanding + // interactively? If not, we can get rid of this all + // together. Don't really want to wait for this message + // (and possibly have to hit return to continue!). + if (!(options & WILD_SILENT)) { + emsg(_(e_toomany)); + } else if (!(options & WILD_NO_BEEP)) { + beep_flush(); + } + } + if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE)) { + ss = vim_strsave((char_u *)xp->xp_files[0]); + } + } + } + } + + // Find longest common part + if (mode == WILD_LONGEST && xp->xp_numfiles > 0) { + size_t len = 0; + + for (size_t mb_len; xp->xp_files[0][len]; len += mb_len) { + mb_len = (size_t)utfc_ptr2len(&xp->xp_files[0][len]); + int c0 = utf_ptr2char(&xp->xp_files[0][len]); + for (i = 1; i < xp->xp_numfiles; i++) { + int ci = utf_ptr2char(&xp->xp_files[i][len]); + + if (p_fic && (xp->xp_context == EXPAND_DIRECTORIES + || xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_SHELLCMD + || xp->xp_context == EXPAND_BUFFERS)) { + if (mb_tolower(c0) != mb_tolower(ci)) { + break; + } + } else if (c0 != ci) { + break; + } + } + if (i < xp->xp_numfiles) { + if (!(options & WILD_NO_BEEP)) { + vim_beep(BO_WILD); + } + break; + } + } + + ss = (char_u *)xstrndup(xp->xp_files[0], len); + findex = -1; // next p_wc gets first one + } + + // Concatenate all matching names. Unless interrupted, this can be slow + // and the result probably won't be used. + // TODO(philix): use xstpcpy instead of strcat in a loop (ExpandOne) + if (mode == WILD_ALL && xp->xp_numfiles > 0 && !got_int) { + size_t len = 0; + for (i = 0; i < xp->xp_numfiles; i++) { + len += STRLEN(xp->xp_files[i]) + 1; + } + ss = xmalloc(len); + *ss = NUL; + for (i = 0; i < xp->xp_numfiles; i++) { + STRCAT(ss, xp->xp_files[i]); + if (i != xp->xp_numfiles - 1) { + STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " "); + } + } + } + + if (mode == WILD_EXPAND_FREE || mode == WILD_ALL) { + ExpandCleanup(xp); + } + + // Free "orig" if it wasn't stored in "orig_save". + if (!orig_saved) { + xfree(orig); + } + + return ss; +} + +/// Prepare an expand structure for use. +void ExpandInit(expand_T *xp) + FUNC_ATTR_NONNULL_ALL +{ + CLEAR_POINTER(xp); + xp->xp_backslash = XP_BS_NONE; + xp->xp_numfiles = -1; +} + +/// Cleanup an expand structure after use. +void ExpandCleanup(expand_T *xp) +{ + if (xp->xp_numfiles >= 0) { + FreeWild(xp->xp_numfiles, xp->xp_files); + xp->xp_numfiles = -1; + } +} + +/// Show all matches for completion on the command line. +/// Returns EXPAND_NOTHING when the character that triggered expansion should +/// be inserted like a normal character. +int showmatches(expand_T *xp, int wildmenu) +{ + CmdlineInfo *const ccline = get_cmdline_info(); +#define L_SHOWFILE(m) (showtail \ + ? sm_gettail(files_found[m], false) : files_found[m]) + int num_files; + char **files_found; + int i, j, k; + int maxlen; + int lines; + int columns; + char_u *p; + int lastlen; + int attr; + int showtail; + + if (xp->xp_numfiles == -1) { + set_expand_context(xp); + i = expand_cmdline(xp, ccline->cmdbuff, ccline->cmdpos, + &num_files, &files_found); + showtail = expand_showtail(xp); + if (i != EXPAND_OK) { + return i; + } + } else { + num_files = xp->xp_numfiles; + files_found = xp->xp_files; + showtail = cmd_showtail; + } + + bool compl_use_pum = (ui_has(kUICmdline) + ? ui_has(kUIPopupmenu) + : wildmenu && (wop_flags & WOP_PUM)) + || ui_has(kUIWildmenu); + + if (compl_use_pum) { + assert(num_files >= 0); + compl_match_arraysize = num_files; + compl_match_array = xmalloc(sizeof(pumitem_T) * (size_t)compl_match_arraysize); + for (i = 0; i < num_files; i++) { + compl_match_array[i] = (pumitem_T){ + .pum_text = (char_u *)L_SHOWFILE(i), + .pum_info = NULL, + .pum_extra = NULL, + .pum_kind = NULL, + }; + } + char_u *endpos = (char_u *)(showtail ? sm_gettail(xp->xp_pattern, true) : xp->xp_pattern); + if (ui_has(kUICmdline)) { + compl_startcol = (int)(endpos - ccline->cmdbuff); + } else { + compl_startcol = cmd_screencol((int)(endpos - ccline->cmdbuff)); + } + compl_selected = -1; + cmdline_pum_display(true); + return EXPAND_OK; + } + + if (!wildmenu) { + msg_didany = false; // lines_left will be set + msg_start(); // prepare for paging + msg_putchar('\n'); + ui_flush(); + cmdline_row = msg_row; + msg_didany = false; // lines_left will be set again + msg_start(); // prepare for paging + } + + if (got_int) { + got_int = false; // only int. the completion, not the cmd line + } else if (wildmenu) { + redraw_wildmenu(xp, num_files, files_found, -1, showtail); + } else { + // find the length of the longest file name + maxlen = 0; + for (i = 0; i < num_files; i++) { + if (!showtail && (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_SHELLCMD + || xp->xp_context == EXPAND_BUFFERS)) { + home_replace(NULL, files_found[i], (char *)NameBuff, MAXPATHL, true); + j = vim_strsize((char *)NameBuff); + } else { + j = vim_strsize(L_SHOWFILE(i)); + } + if (j > maxlen) { + maxlen = j; + } + } + + if (xp->xp_context == EXPAND_TAGS_LISTFILES) { + lines = num_files; + } else { + // compute the number of columns and lines for the listing + maxlen += 2; // two spaces between file names + columns = (Columns + 2) / maxlen; + if (columns < 1) { + columns = 1; + } + lines = (num_files + columns - 1) / columns; + } + + attr = HL_ATTR(HLF_D); // find out highlighting for directories + + if (xp->xp_context == EXPAND_TAGS_LISTFILES) { + msg_puts_attr(_("tagname"), HL_ATTR(HLF_T)); + msg_clr_eos(); + msg_advance(maxlen - 3); + msg_puts_attr(_(" kind file\n"), HL_ATTR(HLF_T)); + } + + // list the files line by line + for (i = 0; i < lines; i++) { + lastlen = 999; + for (k = i; k < num_files; k += lines) { + if (xp->xp_context == EXPAND_TAGS_LISTFILES) { + msg_outtrans_attr((char_u *)files_found[k], HL_ATTR(HLF_D)); + p = (char_u *)files_found[k] + STRLEN(files_found[k]) + 1; + msg_advance(maxlen + 1); + msg_puts((const char *)p); + msg_advance(maxlen + 3); + msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D)); + break; + } + for (j = maxlen - lastlen; --j >= 0;) { + msg_putchar(' '); + } + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_SHELLCMD + || xp->xp_context == EXPAND_BUFFERS) { + // highlight directories + if (xp->xp_numfiles != -1) { + // Expansion was done before and special characters + // were escaped, need to halve backslashes. Also + // $HOME has been replaced with ~/. + char_u *exp_path = expand_env_save_opt((char_u *)files_found[k], true); + char_u *path = exp_path != NULL ? exp_path : (char_u *)files_found[k]; + char_u *halved_slash = backslash_halve_save(path); + j = os_isdir(halved_slash); + xfree(exp_path); + if (halved_slash != path) { + xfree(halved_slash); + } + } else { + // Expansion was done here, file names are literal. + j = os_isdir((char_u *)files_found[k]); + } + if (showtail) { + p = (char_u *)L_SHOWFILE(k); + } else { + home_replace(NULL, files_found[k], (char *)NameBuff, MAXPATHL, true); + p = NameBuff; + } + } else { + j = false; + p = (char_u *)L_SHOWFILE(k); + } + lastlen = msg_outtrans_attr(p, j ? attr : 0); + } + if (msg_col > 0) { // when not wrapped around + msg_clr_eos(); + msg_putchar('\n'); + } + ui_flush(); // show one line at a time + if (got_int) { + got_int = false; + break; + } + } + + // we redraw the command below the lines that we have just listed + // This is a bit tricky, but it saves a lot of screen updating. + cmdline_row = msg_row; // will put it back later + } + + if (xp->xp_numfiles == -1) { + FreeWild(num_files, files_found); + } + + return EXPAND_OK; +} + +/// Private path_tail for showmatches() (and redraw_wildmenu()): +/// Find tail of file name path, but ignore trailing "/". +char *sm_gettail(char *s, bool eager) +{ + char_u *p; + char_u *t = (char_u *)s; + bool had_sep = false; + + for (p = (char_u *)s; *p != NUL;) { + if (vim_ispathsep(*p) +#ifdef BACKSLASH_IN_FILENAME + && !rem_backslash(p) +#endif + ) { + if (eager) { + t = p + 1; + } else { + had_sep = true; + } + } else if (had_sep) { + t = p; + had_sep = false; + } + MB_PTR_ADV(p); + } + return (char *)t; +} + +/// Return true if we only need to show the tail of completion matches. +/// When not completing file names or there is a wildcard in the path false is +/// returned. +static bool expand_showtail(expand_T *xp) +{ + char_u *s; + char_u *end; + + // When not completing file names a "/" may mean something different. + if (xp->xp_context != EXPAND_FILES + && xp->xp_context != EXPAND_SHELLCMD + && xp->xp_context != EXPAND_DIRECTORIES) { + return false; + } + + end = (char_u *)path_tail(xp->xp_pattern); + if (end == (char_u *)xp->xp_pattern) { // there is no path separator + return false; + } + + for (s = (char_u *)xp->xp_pattern; s < end; s++) { + // Skip escaped wildcards. Only when the backslash is not a path + // separator, on DOS the '*' "path\*\file" must not be skipped. + if (rem_backslash(s)) { + s++; + } else if (vim_strchr("*?[", *s) != NULL) { + return false; + } + } + return true; +} + +/// Prepare a string for expansion. +/// +/// When expanding file names: The string will be used with expand_wildcards(). +/// Copy "fname[len]" into allocated memory and add a '*' at the end. +/// When expanding other names: The string will be used with regcomp(). Copy +/// the name into allocated memory and prepend "^". +/// +/// @param context EXPAND_FILES etc. +char_u *addstar(char_u *fname, size_t len, int context) + FUNC_ATTR_NONNULL_RET +{ + char_u *retval; + size_t i, j; + size_t new_len; + char_u *tail; + int ends_in_star; + + if (context != EXPAND_FILES + && context != EXPAND_FILES_IN_PATH + && context != EXPAND_SHELLCMD + && context != EXPAND_DIRECTORIES) { + // Matching will be done internally (on something other than files). + // So we convert the file-matching-type wildcards into our kind for + // use with vim_regcomp(). First work out how long it will be: + + // For help tags the translation is done in find_help_tags(). + // For a tag pattern starting with "/" no translation is needed. + if (context == EXPAND_HELP + || context == EXPAND_CHECKHEALTH + || context == EXPAND_COLORS + || context == EXPAND_COMPILER + || context == EXPAND_OWNSYNTAX + || context == EXPAND_FILETYPE + || context == EXPAND_PACKADD + || ((context == EXPAND_TAGS_LISTFILES || context == EXPAND_TAGS) + && fname[0] == '/')) { + retval = vim_strnsave(fname, len); + } else { + new_len = len + 2; // +2 for '^' at start, NUL at end + for (i = 0; i < len; i++) { + if (fname[i] == '*' || fname[i] == '~') { + new_len++; // '*' needs to be replaced by ".*" + // '~' needs to be replaced by "\~" + } + // Buffer names are like file names. "." should be literal + if (context == EXPAND_BUFFERS && fname[i] == '.') { + new_len++; // "." becomes "\." + } + // Custom expansion takes care of special things, match + // backslashes literally (perhaps also for other types?) + if ((context == EXPAND_USER_DEFINED + || context == EXPAND_USER_LIST) && fname[i] == '\\') { + new_len++; // '\' becomes "\\" + } + } + retval = xmalloc(new_len); + { + retval[0] = '^'; + j = 1; + for (i = 0; i < len; i++, j++) { + // Skip backslash. But why? At least keep it for custom + // expansion. + if (context != EXPAND_USER_DEFINED + && context != EXPAND_USER_LIST + && fname[i] == '\\' + && ++i == len) { + break; + } + + switch (fname[i]) { + case '*': + retval[j++] = '.'; + break; + case '~': + retval[j++] = '\\'; + break; + case '?': + retval[j] = '.'; + continue; + case '.': + if (context == EXPAND_BUFFERS) { + retval[j++] = '\\'; + } + break; + case '\\': + if (context == EXPAND_USER_DEFINED + || context == EXPAND_USER_LIST) { + retval[j++] = '\\'; + } + break; + } + retval[j] = fname[i]; + } + retval[j] = NUL; + } + } + } else { + retval = xmalloc(len + 4); + STRLCPY(retval, fname, len + 1); + + // Don't add a star to *, ~, ~user, $var or `cmd`. + // * would become **, which walks the whole tree. + // ~ would be at the start of the file name, but not the tail. + // $ could be anywhere in the tail. + // ` could be anywhere in the file name. + // When the name ends in '$' don't add a star, remove the '$'. + tail = (char_u *)path_tail((char *)retval); + ends_in_star = (len > 0 && retval[len - 1] == '*'); +#ifndef BACKSLASH_IN_FILENAME + for (ssize_t k = (ssize_t)len - 2; k >= 0; k--) { + if (retval[k] != '\\') { + break; + } + ends_in_star = !ends_in_star; + } +#endif + if ((*retval != '~' || tail != retval) + && !ends_in_star + && vim_strchr((char *)tail, '$') == NULL + && vim_strchr((char *)retval, '`') == NULL) { + retval[len++] = '*'; + } else if (len > 0 && retval[len - 1] == '$') { + len--; + } + retval[len] = NUL; + } + return retval; +} + +/// Must parse the command line so far to work out what context we are in. +/// Completion can then be done based on that context. +/// This routine sets the variables: +/// xp->xp_pattern The start of the pattern to be expanded within +/// the command line (ends at the cursor). +/// xp->xp_context The type of thing to expand. Will be one of: +/// +/// EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on +/// the command line, like an unknown command. Caller +/// should beep. +/// EXPAND_NOTHING Unrecognised context for completion, use char like +/// a normal char, rather than for completion. eg +/// :s/^I/ +/// EXPAND_COMMANDS Cursor is still touching the command, so complete +/// it. +/// EXPAND_BUFFERS Complete file names for :buf and :sbuf commands. +/// EXPAND_FILES After command with EX_XFILE set, or after setting +/// with P_EXPAND set. eg :e ^I, :w>>^I +/// EXPAND_DIRECTORIES In some cases this is used instead of the latter +/// when we know only directories are of interest. eg +/// :set dir=^I +/// EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd". +/// EXPAND_SETTINGS Complete variable names. eg :set d^I +/// EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I +/// EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I +/// EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect +/// EXPAND_HELP Complete tags from the file 'helpfile'/tags +/// EXPAND_EVENTS Complete event names +/// EXPAND_SYNTAX Complete :syntax command arguments +/// EXPAND_HIGHLIGHT Complete highlight (syntax) group names +/// EXPAND_AUGROUP Complete autocommand group names +/// EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I +/// EXPAND_MAPPINGS Complete mapping and abbreviation names, +/// eg :unmap a^I , :cunab x^I +/// EXPAND_FUNCTIONS Complete internal or user defined function names, +/// eg :call sub^I +/// EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I +/// EXPAND_EXPRESSION Complete internal or user defined function/variable +/// names in expressions, eg :while s^I +/// EXPAND_ENV_VARS Complete environment variable names +/// EXPAND_USER Complete user names +void set_expand_context(expand_T *xp) +{ + CmdlineInfo *const ccline = get_cmdline_info(); + + // only expansion for ':', '>' and '=' command-lines + if (ccline->cmdfirstc != ':' + && ccline->cmdfirstc != '>' && ccline->cmdfirstc != '=' + && !ccline->input_fn) { + xp->xp_context = EXPAND_NOTHING; + return; + } + set_cmd_context(xp, ccline->cmdbuff, ccline->cmdlen, ccline->cmdpos, true); +} + +/// This is all pretty much copied from do_one_cmd(), with all the extra stuff +/// we don't need/want deleted. Maybe this could be done better if we didn't +/// repeat all this stuff. The only problem is that they may not stay +/// perfectly compatible with each other, but then the command line syntax +/// probably won't change that much -- webb. +/// +/// @param buff buffer for command string +static const char *set_one_cmd_context(expand_T *xp, const char *buff) +{ + size_t len = 0; + exarg_T ea; + int context = EXPAND_NOTHING; + bool forceit = false; + bool usefilter = false; // Filter instead of file name. + + ExpandInit(xp); + xp->xp_pattern = (char *)buff; + xp->xp_line = (char *)buff; + xp->xp_context = EXPAND_COMMANDS; // Default until we get past command + ea.argt = 0; + + // 2. skip comment lines and leading space, colons or bars + const char *cmd; + for (cmd = buff; vim_strchr(" \t:|", *cmd) != NULL; cmd++) {} + xp->xp_pattern = (char *)cmd; + + if (*cmd == NUL) { + return NULL; + } + if (*cmd == '"') { // ignore comment lines + xp->xp_context = EXPAND_NOTHING; + return NULL; + } + + // 3. parse a range specifier of the form: addr [,addr] [;addr] .. + cmd = (const char *)skip_range(cmd, &xp->xp_context); + + // 4. parse command + xp->xp_pattern = (char *)cmd; + if (*cmd == NUL) { + return NULL; + } + if (*cmd == '"') { + xp->xp_context = EXPAND_NOTHING; + return NULL; + } + + if (*cmd == '|' || *cmd == '\n') { + return cmd + 1; // There's another command + } + + // Isolate the command and search for it in the command table. + // Exceptions: + // - the 'k' command can directly be followed by any character, but + // do accept "keepmarks", "keepalt" and "keepjumps". + // - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r' + const char *p; + if (*cmd == 'k' && cmd[1] != 'e') { + ea.cmdidx = CMD_k; + p = cmd + 1; + } else { + p = cmd; + while (ASCII_ISALPHA(*p) || *p == '*') { // Allow * wild card + p++; + } + // a user command may contain digits + if (ASCII_ISUPPER(cmd[0])) { + while (ASCII_ISALNUM(*p) || *p == '*') { + p++; + } + } + // for python 3.x: ":py3*" commands completion + if (cmd[0] == 'p' && cmd[1] == 'y' && p == cmd + 2 && *p == '3') { + p++; + while (ASCII_ISALPHA(*p) || *p == '*') { + p++; + } + } + // check for non-alpha command + if (p == cmd && vim_strchr("@*!=><&~#", *p) != NULL) { + p++; + } + len = (size_t)(p - cmd); + + if (len == 0) { + xp->xp_context = EXPAND_UNSUCCESSFUL; + return NULL; + } + + ea.cmdidx = excmd_get_cmdidx(cmd, len); + + if (cmd[0] >= 'A' && cmd[0] <= 'Z') { + while (ASCII_ISALNUM(*p) || *p == '*') { // Allow * wild card + p++; + } + } + } + + // If the cursor is touching the command, and it ends in an alphanumeric + // character, complete the command name. + if (*p == NUL && ASCII_ISALNUM(p[-1])) { + return NULL; + } + + if (ea.cmdidx == CMD_SIZE) { + if (*cmd == 's' && vim_strchr("cgriI", cmd[1]) != NULL) { + ea.cmdidx = CMD_substitute; + p = cmd + 1; + } else if (cmd[0] >= 'A' && cmd[0] <= 'Z') { + ea.cmd = (char *)cmd; + p = (const char *)find_ucmd(&ea, (char *)p, NULL, xp, &context); + if (p == NULL) { + ea.cmdidx = CMD_SIZE; // Ambiguous user command. + } + } + } + if (ea.cmdidx == CMD_SIZE) { + // Not still touching the command and it was an illegal one + xp->xp_context = EXPAND_UNSUCCESSFUL; + return NULL; + } + + xp->xp_context = EXPAND_NOTHING; // Default now that we're past command + + if (*p == '!') { // forced commands + forceit = true; + p++; + } + + // 5. parse arguments + if (!IS_USER_CMDIDX(ea.cmdidx)) { + ea.argt = excmd_get_argt(ea.cmdidx); + } + + const char *arg = (const char *)skipwhite(p); + + // Skip over ++argopt argument + if ((ea.argt & EX_ARGOPT) && *arg != NUL && strncmp(arg, "++", 2) == 0) { + p = arg; + while (*p && !ascii_isspace(*p)) { + MB_PTR_ADV(p); + } + arg = (const char *)skipwhite(p); + } + + if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { + if (*arg == '>') { // Append. + if (*++arg == '>') { + arg++; + } + arg = (const char *)skipwhite(arg); + } else if (*arg == '!' && ea.cmdidx == CMD_write) { // :w !filter + arg++; + usefilter = true; + } + } + + if (ea.cmdidx == CMD_read) { + usefilter = forceit; // :r! filter if forced + if (*arg == '!') { // :r !filter + arg++; + usefilter = true; + } + } + + if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { + while (*arg == *cmd) { // allow any number of '>' or '<' + arg++; + } + arg = (const char *)skipwhite(arg); + } + + // Does command allow "+command"? + if ((ea.argt & EX_CMDARG) && !usefilter && *arg == '+') { + // Check if we're in the +command + p = arg + 1; + arg = (const char *)skip_cmd_arg((char *)arg, false); + + // Still touching the command after '+'? + if (*arg == NUL) { + return p; + } + + // Skip space(s) after +command to get to the real argument. + arg = (const char *)skipwhite(arg); + } + + // Check for '|' to separate commands and '"' to start comments. + // Don't do this for ":read !cmd" and ":write !cmd". + if ((ea.argt & EX_TRLBAR) && !usefilter) { + p = arg; + // ":redir @" is not the start of a comment + if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"') { + p += 2; + } + while (*p) { + if (*p == Ctrl_V) { + if (p[1] != NUL) { + p++; + } + } else if ((*p == '"' && !(ea.argt & EX_NOTRLCOM)) + || *p == '|' + || *p == '\n') { + if (*(p - 1) != '\\') { + if (*p == '|' || *p == '\n') { + return p + 1; + } + return NULL; // It's a comment + } + } + MB_PTR_ADV(p); + } + } + + if (!(ea.argt & EX_EXTRA) && *arg != NUL && strchr("|\"", *arg) == NULL) { + // no arguments allowed but there is something + return NULL; + } + + // Find start of last argument (argument just before cursor): + p = buff; + xp->xp_pattern = (char *)p; + len = strlen(buff); + while (*p && p < buff + len) { + if (*p == ' ' || *p == TAB) { + // Argument starts after a space. + xp->xp_pattern = (char *)++p; + } else { + if (*p == '\\' && *(p + 1) != NUL) { + p++; // skip over escaped character + } + MB_PTR_ADV(p); + } + } + + if (ea.argt & EX_XFILE) { + int in_quote = false; + const char *bow = NULL; // Beginning of word. + + // Allow spaces within back-quotes to count as part of the argument + // being expanded. + xp->xp_pattern = skipwhite(arg); + p = (const char *)xp->xp_pattern; + while (*p != NUL) { + int c = utf_ptr2char(p); + if (c == '\\' && p[1] != NUL) { + p++; + } else if (c == '`') { + if (!in_quote) { + xp->xp_pattern = (char *)p; + bow = p + 1; + } + in_quote = !in_quote; + // An argument can contain just about everything, except + // characters that end the command and white space. + } else if (c == '|' || c == '\n' || c == '"' || ascii_iswhite(c)) { + len = 0; // avoid getting stuck when space is in 'isfname' + while (*p != NUL) { + c = utf_ptr2char(p); + if (c == '`' || vim_isfilec_or_wc(c)) { + break; + } + len = (size_t)utfc_ptr2len(p); + MB_PTR_ADV(p); + } + if (in_quote) { + bow = p; + } else { + xp->xp_pattern = (char *)p; + } + p -= len; + } + MB_PTR_ADV(p); + } + + // If we are still inside the quotes, and we passed a space, just + // expand from there. + if (bow != NULL && in_quote) { + xp->xp_pattern = (char *)bow; + } + xp->xp_context = EXPAND_FILES; + + // For a shell command more chars need to be escaped. + if (usefilter || ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal) { +#ifndef BACKSLASH_IN_FILENAME + xp->xp_shell = true; +#endif + // When still after the command name expand executables. + if (xp->xp_pattern == skipwhite(arg)) { + xp->xp_context = EXPAND_SHELLCMD; + } + } + + // Check for environment variable. + if (*xp->xp_pattern == '$') { + for (p = (const char *)xp->xp_pattern + 1; *p != NUL; p++) { + if (!vim_isIDc((uint8_t)(*p))) { + break; + } + } + if (*p == NUL) { + xp->xp_context = EXPAND_ENV_VARS; + xp->xp_pattern++; + // Avoid that the assignment uses EXPAND_FILES again. + if (context != EXPAND_USER_DEFINED && context != EXPAND_USER_LIST) { + context = EXPAND_ENV_VARS; + } + } + } + // Check for user names. + if (*xp->xp_pattern == '~') { + for (p = (const char *)xp->xp_pattern + 1; *p != NUL && *p != '/'; p++) {} + // Complete ~user only if it partially matches a user name. + // A full match ~user<Tab> will be replaced by user's home + // directory i.e. something like ~user<Tab> -> /home/user/ + if (*p == NUL && p > (const char *)xp->xp_pattern + 1 + && match_user((char_u *)xp->xp_pattern + 1) >= 1) { + xp->xp_context = EXPAND_USER; + xp->xp_pattern++; + } + } + } + + // 6. switch on command name + switch (ea.cmdidx) { + case CMD_find: + case CMD_sfind: + case CMD_tabfind: + if (xp->xp_context == EXPAND_FILES) { + xp->xp_context = EXPAND_FILES_IN_PATH; + } + break; + case CMD_cd: + case CMD_chdir: + case CMD_lcd: + case CMD_lchdir: + case CMD_tcd: + case CMD_tchdir: + if (xp->xp_context == EXPAND_FILES) { + xp->xp_context = EXPAND_DIRECTORIES; + } + break; + case CMD_help: + xp->xp_context = EXPAND_HELP; + xp->xp_pattern = (char *)arg; + break; + + // Command modifiers: return the argument. + // Also for commands with an argument that is a command. + case CMD_aboveleft: + case CMD_argdo: + case CMD_belowright: + case CMD_botright: + case CMD_browse: + case CMD_bufdo: + case CMD_cdo: + case CMD_cfdo: + case CMD_confirm: + case CMD_debug: + case CMD_folddoclosed: + case CMD_folddoopen: + case CMD_hide: + case CMD_keepalt: + case CMD_keepjumps: + case CMD_keepmarks: + case CMD_keeppatterns: + case CMD_ldo: + case CMD_leftabove: + case CMD_lfdo: + case CMD_lockmarks: + case CMD_noautocmd: + case CMD_noswapfile: + case CMD_rightbelow: + case CMD_sandbox: + case CMD_silent: + case CMD_tab: + case CMD_tabdo: + case CMD_topleft: + case CMD_verbose: + case CMD_vertical: + case CMD_windo: + return arg; + + case CMD_filter: + if (*arg != NUL) { + arg = (const char *)skip_vimgrep_pat((char *)arg, NULL, NULL); + } + if (arg == NULL || *arg == NUL) { + xp->xp_context = EXPAND_NOTHING; + return NULL; + } + return (const char *)skipwhite(arg); + + case CMD_match: + if (*arg == NUL || !ends_excmd(*arg)) { + // also complete "None" + set_context_in_echohl_cmd(xp, arg); + arg = (const char *)skipwhite((char *)skiptowhite((const char_u *)arg)); + if (*arg != NUL) { + xp->xp_context = EXPAND_NOTHING; + arg = (const char *)skip_regexp((char_u *)arg + 1, (uint8_t)(*arg), + p_magic, NULL); + } + } + return (const char *)find_nextcmd((char_u *)arg); + + // All completion for the +cmdline_compl feature goes here. + + case CMD_command: + return set_context_in_user_cmd(xp, arg); + + case CMD_delcommand: + xp->xp_context = EXPAND_USER_COMMANDS; + xp->xp_pattern = (char *)arg; + break; + + case CMD_global: + case CMD_vglobal: { + const int delim = (uint8_t)(*arg); // Get the delimiter. + if (delim) { + arg++; // Skip delimiter if there is one. + } + + while (arg[0] != NUL && (uint8_t)arg[0] != delim) { + if (arg[0] == '\\' && arg[1] != NUL) { + arg++; + } + arg++; + } + if (arg[0] != NUL) { + return arg + 1; + } + break; + } + case CMD_and: + case CMD_substitute: { + const int delim = (uint8_t)(*arg); + if (delim) { + // Skip "from" part. + arg++; + arg = (const char *)skip_regexp((char_u *)arg, delim, p_magic, NULL); + } + // Skip "to" part. + while (arg[0] != NUL && (uint8_t)arg[0] != delim) { + if (arg[0] == '\\' && arg[1] != NUL) { + arg++; + } + arg++; + } + if (arg[0] != NUL) { // Skip delimiter. + arg++; + } + while (arg[0] && strchr("|\"#", arg[0]) == NULL) { + arg++; + } + if (arg[0] != NUL) { + return arg; + } + break; + } + case CMD_isearch: + case CMD_dsearch: + case CMD_ilist: + case CMD_dlist: + case CMD_ijump: + case CMD_psearch: + case CMD_djump: + case CMD_isplit: + case CMD_dsplit: + // Skip count. + arg = (const char *)skipwhite(skipdigits(arg)); + if (*arg == '/') { // Match regexp, not just whole words. + for (++arg; *arg && *arg != '/'; arg++) { + if (*arg == '\\' && arg[1] != NUL) { + arg++; + } + } + if (*arg) { + arg = (const char *)skipwhite(arg + 1); + + // Check for trailing illegal characters. + if (*arg && strchr("|\"\n", *arg) == NULL) { + xp->xp_context = EXPAND_NOTHING; + } else { + return arg; + } + } + } + break; + case CMD_autocmd: + return (const char *)set_context_in_autocmd(xp, (char *)arg, false); + + case CMD_doautocmd: + case CMD_doautoall: + return (const char *)set_context_in_autocmd(xp, (char *)arg, true); + case CMD_set: + set_context_in_set_cmd(xp, (char_u *)arg, 0); + break; + case CMD_setglobal: + set_context_in_set_cmd(xp, (char_u *)arg, OPT_GLOBAL); + break; + case CMD_setlocal: + set_context_in_set_cmd(xp, (char_u *)arg, OPT_LOCAL); + break; + case CMD_tag: + case CMD_stag: + case CMD_ptag: + case CMD_ltag: + case CMD_tselect: + case CMD_stselect: + case CMD_ptselect: + case CMD_tjump: + case CMD_stjump: + case CMD_ptjump: + if (wop_flags & WOP_TAGFILE) { + xp->xp_context = EXPAND_TAGS_LISTFILES; + } else { + xp->xp_context = EXPAND_TAGS; + } + xp->xp_pattern = (char *)arg; + break; + case CMD_augroup: + xp->xp_context = EXPAND_AUGROUP; + xp->xp_pattern = (char *)arg; + break; + case CMD_syntax: + set_context_in_syntax_cmd(xp, arg); + break; + case CMD_const: + case CMD_let: + case CMD_if: + case CMD_elseif: + case CMD_while: + case CMD_for: + case CMD_echo: + case CMD_echon: + case CMD_execute: + case CMD_echomsg: + case CMD_echoerr: + case CMD_call: + case CMD_return: + case CMD_cexpr: + case CMD_caddexpr: + case CMD_cgetexpr: + case CMD_lexpr: + case CMD_laddexpr: + case CMD_lgetexpr: + set_context_for_expression(xp, (char *)arg, ea.cmdidx); + break; + + case CMD_unlet: + while ((xp->xp_pattern = strchr(arg, ' ')) != NULL) { + arg = (const char *)xp->xp_pattern + 1; + } + + xp->xp_context = EXPAND_USER_VARS; + xp->xp_pattern = (char *)arg; + + if (*xp->xp_pattern == '$') { + xp->xp_context = EXPAND_ENV_VARS; + xp->xp_pattern++; + } + + break; + + case CMD_function: + case CMD_delfunction: + xp->xp_context = EXPAND_USER_FUNC; + xp->xp_pattern = (char *)arg; + break; + + case CMD_echohl: + set_context_in_echohl_cmd(xp, arg); + break; + case CMD_highlight: + set_context_in_highlight_cmd(xp, arg); + break; + case CMD_cscope: + case CMD_lcscope: + case CMD_scscope: + set_context_in_cscope_cmd(xp, arg, ea.cmdidx); + break; + case CMD_sign: + set_context_in_sign_cmd(xp, (char_u *)arg); + break; + case CMD_bdelete: + case CMD_bwipeout: + case CMD_bunload: + while ((xp->xp_pattern = strchr(arg, ' ')) != NULL) { + arg = (const char *)xp->xp_pattern + 1; + } + FALLTHROUGH; + case CMD_buffer: + case CMD_sbuffer: + case CMD_checktime: + xp->xp_context = EXPAND_BUFFERS; + xp->xp_pattern = (char *)arg; + break; + case CMD_diffget: + case CMD_diffput: + // If current buffer is in diff mode, complete buffer names + // which are in diff mode, and different than current buffer. + xp->xp_context = EXPAND_DIFF_BUFFERS; + xp->xp_pattern = (char *)arg; + break; + + case CMD_USER: + case CMD_USER_BUF: + if (context != EXPAND_NOTHING) { + // EX_XFILE: file names are handled above. + if (!(ea.argt & EX_XFILE)) { + if (context == EXPAND_MENUS) { + return (const char *)set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit); + } else if (context == EXPAND_COMMANDS) { + return arg; + } else if (context == EXPAND_MAPPINGS) { + return (const char *)set_context_in_map_cmd(xp, "map", (char_u *)arg, forceit, + false, false, + CMD_map); + } + // Find start of last argument. + p = arg; + while (*p) { + if (*p == ' ') { + // argument starts after a space + arg = p + 1; + } else if (*p == '\\' && *(p + 1) != NUL) { + p++; // skip over escaped character + } + MB_PTR_ADV(p); + } + xp->xp_pattern = (char *)arg; + } + xp->xp_context = context; + } + break; + + case CMD_map: + case CMD_noremap: + case CMD_nmap: + case CMD_nnoremap: + case CMD_vmap: + case CMD_vnoremap: + case CMD_omap: + case CMD_onoremap: + case CMD_imap: + case CMD_inoremap: + case CMD_cmap: + case CMD_cnoremap: + case CMD_lmap: + case CMD_lnoremap: + case CMD_smap: + case CMD_snoremap: + case CMD_xmap: + case CMD_xnoremap: + return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, false, + false, ea.cmdidx); + case CMD_unmap: + case CMD_nunmap: + case CMD_vunmap: + case CMD_ounmap: + case CMD_iunmap: + case CMD_cunmap: + case CMD_lunmap: + case CMD_sunmap: + case CMD_xunmap: + return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, false, + true, ea.cmdidx); + case CMD_mapclear: + case CMD_nmapclear: + case CMD_vmapclear: + case CMD_omapclear: + case CMD_imapclear: + case CMD_cmapclear: + case CMD_lmapclear: + case CMD_smapclear: + case CMD_xmapclear: + xp->xp_context = EXPAND_MAPCLEAR; + xp->xp_pattern = (char *)arg; + break; + + case CMD_abbreviate: + case CMD_noreabbrev: + case CMD_cabbrev: + case CMD_cnoreabbrev: + case CMD_iabbrev: + case CMD_inoreabbrev: + return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, true, + false, ea.cmdidx); + case CMD_unabbreviate: + case CMD_cunabbrev: + case CMD_iunabbrev: + return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, true, + true, ea.cmdidx); + case CMD_menu: + case CMD_noremenu: + case CMD_unmenu: + case CMD_amenu: + case CMD_anoremenu: + case CMD_aunmenu: + case CMD_nmenu: + case CMD_nnoremenu: + case CMD_nunmenu: + case CMD_vmenu: + case CMD_vnoremenu: + case CMD_vunmenu: + case CMD_omenu: + case CMD_onoremenu: + case CMD_ounmenu: + case CMD_imenu: + case CMD_inoremenu: + case CMD_iunmenu: + case CMD_cmenu: + case CMD_cnoremenu: + case CMD_cunmenu: + case CMD_tlmenu: + case CMD_tlnoremenu: + case CMD_tlunmenu: + case CMD_tmenu: + case CMD_tunmenu: + case CMD_popup: + case CMD_emenu: + return (const char *)set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit); + + case CMD_colorscheme: + xp->xp_context = EXPAND_COLORS; + xp->xp_pattern = (char *)arg; + break; + + case CMD_compiler: + xp->xp_context = EXPAND_COMPILER; + xp->xp_pattern = (char *)arg; + break; + + case CMD_ownsyntax: + xp->xp_context = EXPAND_OWNSYNTAX; + xp->xp_pattern = (char *)arg; + break; + + case CMD_setfiletype: + xp->xp_context = EXPAND_FILETYPE; + xp->xp_pattern = (char *)arg; + break; + + case CMD_packadd: + xp->xp_context = EXPAND_PACKADD; + xp->xp_pattern = (char *)arg; + break; + +#ifdef HAVE_WORKING_LIBINTL + case CMD_language: + p = (const char *)skiptowhite((const char_u *)arg); + if (*p == NUL) { + xp->xp_context = EXPAND_LANGUAGE; + xp->xp_pattern = (char *)arg; + } else { + if (strncmp(arg, "messages", (size_t)(p - arg)) == 0 + || strncmp(arg, "ctype", (size_t)(p - arg)) == 0 + || strncmp(arg, "time", (size_t)(p - arg)) == 0 + || strncmp(arg, "collate", (size_t)(p - arg)) == 0) { + xp->xp_context = EXPAND_LOCALES; + xp->xp_pattern = skipwhite(p); + } else { + xp->xp_context = EXPAND_NOTHING; + } + } + break; +#endif + case CMD_profile: + set_context_in_profile_cmd(xp, arg); + break; + case CMD_checkhealth: + xp->xp_context = EXPAND_CHECKHEALTH; + xp->xp_pattern = (char *)arg; + break; + case CMD_behave: + xp->xp_context = EXPAND_BEHAVE; + xp->xp_pattern = (char *)arg; + break; + + case CMD_messages: + xp->xp_context = EXPAND_MESSAGES; + xp->xp_pattern = (char *)arg; + break; + + case CMD_history: + xp->xp_context = EXPAND_HISTORY; + xp->xp_pattern = (char *)arg; + break; + case CMD_syntime: + xp->xp_context = EXPAND_SYNTIME; + xp->xp_pattern = (char *)arg; + break; + + case CMD_argdelete: + while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL) { + arg = (const char *)(xp->xp_pattern + 1); + } + xp->xp_context = EXPAND_ARGLIST; + xp->xp_pattern = (char *)arg; + break; + + case CMD_lua: + xp->xp_context = EXPAND_LUA; + break; + + default: + break; + } + return NULL; +} + +/// @param str start of command line +/// @param len length of command line (excl. NUL) +/// @param col position of cursor +/// @param use_ccline use ccline for info +void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline) +{ + CmdlineInfo *const ccline = get_cmdline_info(); + char_u old_char = NUL; + + // Avoid a UMR warning from Purify, only save the character if it has been + // written before. + if (col < len) { + old_char = str[col]; + } + str[col] = NUL; + const char *nextcomm = (const char *)str; + + if (use_ccline && ccline->cmdfirstc == '=') { + // pass CMD_SIZE because there is no real command + set_context_for_expression(xp, (char *)str, CMD_SIZE); + } else if (use_ccline && ccline->input_fn) { + xp->xp_context = ccline->xp_context; + xp->xp_pattern = (char *)ccline->cmdbuff; + xp->xp_arg = (char *)ccline->xp_arg; + } else { + while (nextcomm != NULL) { + nextcomm = set_one_cmd_context(xp, nextcomm); + } + } + + // Store the string here so that call_user_expand_func() can get to them + // easily. + xp->xp_line = (char *)str; + xp->xp_col = col; + + str[col] = old_char; +} + +/// Expand the command line "str" from context "xp". +/// "xp" must have been set by set_cmd_context(). +/// xp->xp_pattern points into "str", to where the text that is to be expanded +/// starts. +/// Returns EXPAND_UNSUCCESSFUL when there is something illegal before the +/// cursor. +/// Returns EXPAND_NOTHING when there is nothing to expand, might insert the +/// key that triggered expansion literally. +/// Returns EXPAND_OK otherwise. +/// +/// @param str start of command line +/// @param col position of cursor +/// @param matchcount return: nr of matches +/// @param matches return: array of pointers to matches +int expand_cmdline(expand_T *xp, char_u *str, int col, int *matchcount, char ***matches) +{ + char_u *file_str = NULL; + int options = WILD_ADD_SLASH|WILD_SILENT; + + if (xp->xp_context == EXPAND_UNSUCCESSFUL) { + beep_flush(); + return EXPAND_UNSUCCESSFUL; // Something illegal on command line + } + if (xp->xp_context == EXPAND_NOTHING) { + // Caller can use the character as a normal char instead + return EXPAND_NOTHING; + } + + // add star to file name, or convert to regexp if not exp. files. + assert((str + col) - (char_u *)xp->xp_pattern >= 0); + xp->xp_pattern_len = (size_t)((str + col) - (char_u *)xp->xp_pattern); + file_str = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); + + if (p_wic) { + options += WILD_ICASE; + } + + // find all files that match the description + if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL) { + *matchcount = 0; + *matches = NULL; + } + xfree(file_str); + + return EXPAND_OK; +} + +/// Function given to ExpandGeneric() to obtain the possible arguments of the +/// ":behave {mswin,xterm}" command. +static char *get_behave_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) +{ + if (idx == 0) { + return "mswin"; + } + if (idx == 1) { + return "xterm"; + } + return NULL; +} + +/// Function given to ExpandGeneric() to obtain the possible arguments of the +/// ":messages {clear}" command. +static char *get_messages_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) +{ + if (idx == 0) { + return "clear"; + } + return NULL; +} + +static char *get_mapclear_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) +{ + if (idx == 0) { + return "<buffer>"; + } + return NULL; +} + +/// Completion for |:checkhealth| command. +/// +/// Given to ExpandGeneric() to obtain all available heathcheck names. +/// @param[in] idx Index of the healthcheck item. +/// @param[in] xp Not used. +static char *get_healthcheck_names(expand_T *xp FUNC_ATTR_UNUSED, int idx) +{ + static Object names = OBJECT_INIT; + static unsigned last_gen = 0; + + if (last_gen != get_cmdline_last_prompt_id() || last_gen == 0) { + Array a = ARRAY_DICT_INIT; + Error err = ERROR_INIT; + Object res = nlua_exec(STATIC_CSTR_AS_STRING("return vim.health._complete()"), a, &err); + api_clear_error(&err); + api_free_object(names); + names = res; + last_gen = get_cmdline_last_prompt_id(); + } + + if (names.type == kObjectTypeArray && idx < (int)names.data.array.size) { + return names.data.array.items[idx].data.string.data; + } + return NULL; +} + +/// Do the expansion based on xp->xp_context and "pat". +/// +/// @param options WILD_ flags +static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char ***file, int options) +{ + regmatch_T regmatch; + int ret; + int flags; + + flags = EW_DIR; // include directories + if (options & WILD_LIST_NOTFOUND) { + flags |= EW_NOTFOUND; + } + if (options & WILD_ADD_SLASH) { + flags |= EW_ADDSLASH; + } + if (options & WILD_KEEP_ALL) { + flags |= EW_KEEPALL; + } + if (options & WILD_SILENT) { + flags |= EW_SILENT; + } + if (options & WILD_NOERROR) { + flags |= EW_NOERROR; + } + if (options & WILD_ALLLINKS) { + flags |= EW_ALLLINKS; + } + + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_DIRECTORIES + || xp->xp_context == EXPAND_FILES_IN_PATH) { + // Expand file or directory names. + bool free_pat = false; + int i; + + // for ":set path=" and ":set tags=" halve backslashes for escaped space + if (xp->xp_backslash != XP_BS_NONE) { + free_pat = true; + pat = vim_strsave(pat); + for (i = 0; pat[i]; i++) { + if (pat[i] == '\\') { + if (xp->xp_backslash == XP_BS_THREE + && pat[i + 1] == '\\' + && pat[i + 2] == '\\' + && pat[i + 3] == ' ') { + STRMOVE(pat + i, pat + i + 3); + } + if (xp->xp_backslash == XP_BS_ONE + && pat[i + 1] == ' ') { + STRMOVE(pat + i, pat + i + 1); + } + } + } + } + + if (xp->xp_context == EXPAND_FILES) { + flags |= EW_FILE; + } else if (xp->xp_context == EXPAND_FILES_IN_PATH) { + flags |= (EW_FILE | EW_PATH); + } else { + flags = (flags | EW_DIR) & ~EW_FILE; + } + if (options & WILD_ICASE) { + flags |= EW_ICASE; + } + + // Expand wildcards, supporting %:h and the like. + ret = expand_wildcards_eval(&pat, num_file, file, flags); + if (free_pat) { + xfree(pat); + } +#ifdef BACKSLASH_IN_FILENAME + if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0) { + for (int i = 0; i < *num_file; i++) { + char_u *ptr = (*file)[i]; + while (*ptr != NUL) { + if (p_csl[0] == 's' && *ptr == '\\') { + *ptr = '/'; + } else if (p_csl[0] == 'b' && *ptr == '/') { + *ptr = '\\'; + } + ptr += utfc_ptr2len(ptr); + } + } + } +#endif + return ret; + } + + *file = NULL; + *num_file = 0; + if (xp->xp_context == EXPAND_HELP) { + // With an empty argument we would get all the help tags, which is + // very slow. Get matches for "help" instead. + if (find_help_tags(*pat == NUL ? "help" : (char *)pat, + num_file, file, false) == OK) { + cleanup_help_tags(*num_file, *file); + return OK; + } + return FAIL; + } + + if (xp->xp_context == EXPAND_SHELLCMD) { + *file = NULL; + expand_shellcmd(pat, num_file, file, flags); + return OK; + } + if (xp->xp_context == EXPAND_OLD_SETTING) { + ExpandOldSetting(num_file, file); + return OK; + } + if (xp->xp_context == EXPAND_BUFFERS) { + return ExpandBufnames((char *)pat, num_file, file, options); + } + if (xp->xp_context == EXPAND_DIFF_BUFFERS) { + return ExpandBufnames((char *)pat, num_file, file, options | BUF_DIFF_FILTER); + } + if (xp->xp_context == EXPAND_TAGS + || xp->xp_context == EXPAND_TAGS_LISTFILES) { + return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file); + } + if (xp->xp_context == EXPAND_COLORS) { + char *directories[] = { "colors", NULL }; + return ExpandRTDir(pat, DIP_START + DIP_OPT + DIP_LUA, num_file, file, directories); + } + if (xp->xp_context == EXPAND_COMPILER) { + char *directories[] = { "compiler", NULL }; + return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); + } + if (xp->xp_context == EXPAND_OWNSYNTAX) { + char *directories[] = { "syntax", NULL }; + return ExpandRTDir(pat, 0, num_file, file, directories); + } + if (xp->xp_context == EXPAND_FILETYPE) { + char *directories[] = { "syntax", "indent", "ftplugin", NULL }; + return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); + } + if (xp->xp_context == EXPAND_USER_LIST) { + return ExpandUserList(xp, num_file, file); + } + if (xp->xp_context == EXPAND_USER_LUA) { + return ExpandUserLua(xp, num_file, file); + } + if (xp->xp_context == EXPAND_PACKADD) { + return ExpandPackAddDir(pat, num_file, file); + } + + // When expanding a function name starting with s:, match the <SNR>nr_ + // prefix. + char *tofree = NULL; + if (xp->xp_context == EXPAND_USER_FUNC && STRNCMP(pat, "^s:", 3) == 0) { + const size_t len = STRLEN(pat) + 20; + + tofree = xmalloc(len); + snprintf(tofree, len, "^<SNR>\\d\\+_%s", pat + 3); + pat = (char_u *)tofree; + } + + if (xp->xp_context == EXPAND_LUA) { + ILOG("PAT %s", pat); + return nlua_expand_pat(xp, pat, num_file, file); + } + + regmatch.regprog = vim_regcomp((char *)pat, p_magic ? RE_MAGIC : 0); + if (regmatch.regprog == NULL) { + return FAIL; + } + + // set ignore-case according to p_ic, p_scs and pat + regmatch.rm_ic = ignorecase(pat); + + if (xp->xp_context == EXPAND_SETTINGS + || xp->xp_context == EXPAND_BOOL_SETTINGS) { + ret = ExpandSettings(xp, ®match, num_file, file); + } else if (xp->xp_context == EXPAND_MAPPINGS) { + ret = ExpandMappings(®match, num_file, file); + } else if (xp->xp_context == EXPAND_USER_DEFINED) { + ret = ExpandUserDefined(xp, ®match, num_file, file); + } else { + typedef CompleteListItemGetter ExpandFunc; + static struct expgen { + int context; + ExpandFunc func; + int ic; + int escaped; + } tab[] = { + { EXPAND_COMMANDS, get_command_name, false, true }, + { EXPAND_BEHAVE, get_behave_arg, true, true }, + { EXPAND_MAPCLEAR, get_mapclear_arg, true, true }, + { EXPAND_MESSAGES, get_messages_arg, true, true }, + { EXPAND_HISTORY, get_history_arg, true, true }, + { EXPAND_USER_COMMANDS, get_user_commands, false, true }, + { EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, false, true }, + { EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, false, true }, + { EXPAND_USER_NARGS, get_user_cmd_nargs, false, true }, + { EXPAND_USER_COMPLETE, get_user_cmd_complete, false, true }, + { EXPAND_USER_VARS, get_user_var_name, false, true }, + { EXPAND_FUNCTIONS, get_function_name, false, true }, + { EXPAND_USER_FUNC, get_user_func_name, false, true }, + { EXPAND_EXPRESSION, get_expr_name, false, true }, + { EXPAND_MENUS, get_menu_name, false, true }, + { EXPAND_MENUNAMES, get_menu_names, false, true }, + { EXPAND_SYNTAX, get_syntax_name, true, true }, + { EXPAND_SYNTIME, get_syntime_arg, true, true }, + { EXPAND_HIGHLIGHT, (ExpandFunc)get_highlight_name, true, true }, + { EXPAND_EVENTS, expand_get_event_name, true, false }, + { EXPAND_AUGROUP, expand_get_augroup_name, true, false }, + { EXPAND_CSCOPE, get_cscope_name, true, true }, + { EXPAND_SIGN, get_sign_name, true, true }, + { EXPAND_PROFILE, get_profile_name, true, true }, +#ifdef HAVE_WORKING_LIBINTL + { EXPAND_LANGUAGE, get_lang_arg, true, false }, + { EXPAND_LOCALES, get_locales, true, false }, +#endif + { EXPAND_ENV_VARS, get_env_name, true, true }, + { EXPAND_USER, get_users, true, false }, + { EXPAND_ARGLIST, get_arglist_name, true, false }, + { EXPAND_CHECKHEALTH, get_healthcheck_names, true, false }, + }; + + // Find a context in the table and call the ExpandGeneric() with the + // right function to do the expansion. + ret = FAIL; + for (int i = 0; i < (int)ARRAY_SIZE(tab); i++) { + if (xp->xp_context == tab[i].context) { + if (tab[i].ic) { + regmatch.rm_ic = true; + } + ExpandGeneric(xp, ®match, num_file, file, tab[i].func, tab[i].escaped); + ret = OK; + break; + } + } + } + + vim_regfree(regmatch.regprog); + xfree(tofree); + + return ret; +} + +/// Expand a list of names. +/// +/// Generic function for command line completion. It calls a function to +/// obtain strings, one by one. The strings are matched against a regexp +/// program. Matching strings are copied into an array, which is returned. +/// +/// @param func returns a string from the list +static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file, + CompleteListItemGetter func, int escaped) +{ + int i; + size_t count = 0; + char_u *str; + + // count the number of matching names + for (i = 0;; i++) { + str = (char_u *)(*func)(xp, i); + if (str == NULL) { // end of list + break; + } + if (*str == NUL) { // skip empty strings + continue; + } + if (vim_regexec(regmatch, (char *)str, (colnr_T)0)) { + count++; + } + } + if (count == 0) { + return; + } + assert(count < INT_MAX); + *num_file = (int)count; + *file = xmalloc(count * sizeof(char_u *)); + + // copy the matching names into allocated memory + count = 0; + for (i = 0;; i++) { + str = (char_u *)(*func)(xp, i); + if (str == NULL) { // End of list. + break; + } + if (*str == NUL) { // Skip empty strings. + continue; + } + if (vim_regexec(regmatch, (char *)str, (colnr_T)0)) { + if (escaped) { + str = vim_strsave_escaped(str, (char_u *)" \t\\."); + } else { + str = vim_strsave(str); + } + (*file)[count++] = (char *)str; + if (func == get_menu_names) { + // Test for separator added by get_menu_names(). + str += STRLEN(str) - 1; + if (*str == '\001') { + *str = '.'; + } + } + } + } + + // Sort the results. Keep menu's in the specified order. + if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS) { + if (xp->xp_context == EXPAND_EXPRESSION + || xp->xp_context == EXPAND_FUNCTIONS + || xp->xp_context == EXPAND_USER_FUNC) { + // <SNR> functions should be sorted to the end. + qsort((void *)(*file), (size_t)(*num_file), sizeof(char_u *), + sort_func_compare); + } else { + sort_strings(*file, *num_file); + } + } + + // Reset the variables used for special highlight names expansion, so that + // they don't show up when getting normal highlight names by ID. + reset_expand_highlight(); +} + +/// Complete a shell command. +/// +/// @param filepat is a pattern to match with command names. +/// @param[out] num_file is pointer to number of matches. +/// @param[out] file is pointer to array of pointers to matches. +/// *file will either be set to NULL or point to +/// allocated memory. +/// @param flagsarg is a combination of EW_* flags. +static void expand_shellcmd(char_u *filepat, int *num_file, char ***file, int flagsarg) + FUNC_ATTR_NONNULL_ALL +{ + char_u *pat; + int i; + char_u *path = NULL; + garray_T ga; + char *buf = xmalloc(MAXPATHL); + size_t l; + char_u *s, *e; + int flags = flagsarg; + int ret; + bool did_curdir = false; + + // for ":set path=" and ":set tags=" halve backslashes for escaped space + pat = vim_strsave(filepat); + for (i = 0; pat[i]; i++) { + if (pat[i] == '\\' && pat[i + 1] == ' ') { + STRMOVE(pat + i, pat + i + 1); + } + } + + flags |= EW_FILE | EW_EXEC | EW_SHELLCMD; + + bool mustfree = false; // Track memory allocation for *path. + if (pat[0] == '.' && (vim_ispathsep(pat[1]) + || (pat[1] == '.' && vim_ispathsep(pat[2])))) { + path = (char_u *)"."; + } else { + // For an absolute name we don't use $PATH. + if (!path_is_absolute(pat)) { + path = (char_u *)vim_getenv("PATH"); + } + if (path == NULL) { + path = (char_u *)""; + } else { + mustfree = true; + } + } + + // Go over all directories in $PATH. Expand matches in that directory and + // collect them in "ga". When "." is not in $PATH also expaned for the + // current directory, to find "subdir/cmd". + ga_init(&ga, (int)sizeof(char *), 10); + hashtab_T found_ht; + hash_init(&found_ht); + for (s = path;; s = e) { + e = (char_u *)vim_strchr((char *)s, ENV_SEPCHAR); + if (e == NULL) { + e = s + STRLEN(s); + } + + if (*s == NUL) { + if (did_curdir) { + break; + } + // Find directories in the current directory, path is empty. + did_curdir = true; + flags |= EW_DIR; + } else if (STRNCMP(s, ".", e - s) == 0) { + did_curdir = true; + flags |= EW_DIR; + } else { + // Do not match directories inside a $PATH item. + flags &= ~EW_DIR; + } + + l = (size_t)(e - s); + if (l > MAXPATHL - 5) { + break; + } + STRLCPY(buf, s, l + 1); + add_pathsep(buf); + l = STRLEN(buf); + STRLCPY(buf + l, pat, MAXPATHL - l); + + // Expand matches in one directory of $PATH. + ret = expand_wildcards(1, &buf, num_file, file, flags); + if (ret == OK) { + ga_grow(&ga, *num_file); + { + for (i = 0; i < *num_file; i++) { + char_u *name = (char_u *)(*file)[i]; + + if (STRLEN(name) > l) { + // Check if this name was already found. + hash_T hash = hash_hash(name + l); + hashitem_T *hi = + hash_lookup(&found_ht, (const char *)(name + l), + STRLEN(name + l), hash); + if (HASHITEM_EMPTY(hi)) { + // Remove the path that was prepended. + STRMOVE(name, name + l); + ((char_u **)ga.ga_data)[ga.ga_len++] = name; + hash_add_item(&found_ht, hi, name, hash); + name = NULL; + } + } + xfree(name); + } + xfree(*file); + } + } + if (*e != NUL) { + e++; + } + } + *file = ga.ga_data; + *num_file = ga.ga_len; + + xfree(buf); + xfree(pat); + if (mustfree) { + xfree(path); + } + hash_clear(&found_ht); +} + +/// Call "user_expand_func()" to invoke a user defined Vim script function and +/// return the result (either a string, a List or NULL). +static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T *xp, int *num_file, + char ***file) + FUNC_ATTR_NONNULL_ALL +{ + CmdlineInfo *const ccline = get_cmdline_info(); + char_u keep = 0; + typval_T args[4]; + char_u *pat = NULL; + const sctx_T save_current_sctx = current_sctx; + + if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL) { + return NULL; + } + *num_file = 0; + *file = NULL; + + if (ccline->cmdbuff != NULL) { + keep = ccline->cmdbuff[ccline->cmdlen]; + ccline->cmdbuff[ccline->cmdlen] = 0; + } + + pat = vim_strnsave((char_u *)xp->xp_pattern, xp->xp_pattern_len); + args[0].v_type = VAR_STRING; + args[1].v_type = VAR_STRING; + args[2].v_type = VAR_NUMBER; + args[3].v_type = VAR_UNKNOWN; + args[0].vval.v_string = (char *)pat; + args[1].vval.v_string = xp->xp_line; + args[2].vval.v_number = xp->xp_col; + + current_sctx = xp->xp_script_ctx; + + void *const ret = user_expand_func((char_u *)xp->xp_arg, 3, args); + + current_sctx = save_current_sctx; + if (ccline->cmdbuff != NULL) { + ccline->cmdbuff[ccline->cmdlen] = keep; + } + + xfree(pat); + return ret; +} + +/// Expand names with a function defined by the user. +static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file) +{ + char_u *e; + garray_T ga; + + char_u *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file, + file); + + if (retstr == NULL) { + return FAIL; + } + + ga_init(&ga, (int)sizeof(char *), 3); + for (char_u *s = retstr; *s != NUL; s = e) { + e = (char_u *)vim_strchr((char *)s, '\n'); + if (e == NULL) { + e = s + STRLEN(s); + } + const char_u keep = *e; + *e = NUL; + + const bool skip = xp->xp_pattern[0] + && vim_regexec(regmatch, (char *)s, (colnr_T)0) == 0; + *e = keep; + if (!skip) { + GA_APPEND(char_u *, &ga, vim_strnsave(s, (size_t)(e - s))); + } + + if (*e != NUL) { + e++; + } + } + xfree(retstr); + *file = ga.ga_data; + *num_file = ga.ga_len; + return OK; +} + +/// Expand names with a list returned by a function defined by the user. +static int ExpandUserList(expand_T *xp, int *num_file, char ***file) +{ + list_T *const retlist = call_user_expand_func((user_expand_func_T)call_func_retlist, xp, num_file, + file); + if (retlist == NULL) { + return FAIL; + } + + garray_T ga; + ga_init(&ga, (int)sizeof(char *), 3); + // Loop over the items in the list. + TV_LIST_ITER_CONST(retlist, li, { + if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING + || TV_LIST_ITEM_TV(li)->vval.v_string == NULL) { + continue; // Skip non-string items and empty strings. + } + + GA_APPEND(char *, &ga, xstrdup((const char *)TV_LIST_ITEM_TV(li)->vval.v_string)); + }); + tv_list_unref(retlist); + + *file = ga.ga_data; + *num_file = ga.ga_len; + return OK; +} + +static int ExpandUserLua(expand_T *xp, int *num_file, char ***file) +{ + typval_T rettv; + nlua_call_user_expand_func(xp, &rettv); + if (rettv.v_type != VAR_LIST) { + tv_clear(&rettv); + return FAIL; + } + + list_T *const retlist = rettv.vval.v_list; + + garray_T ga; + ga_init(&ga, (int)sizeof(char *), 3); + // Loop over the items in the list. + TV_LIST_ITER_CONST(retlist, li, { + if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING + || TV_LIST_ITEM_TV(li)->vval.v_string == NULL) { + continue; // Skip non-string items and empty strings. + } + + GA_APPEND(char *, &ga, xstrdup((const char *)TV_LIST_ITEM_TV(li)->vval.v_string)); + }); + tv_list_unref(retlist); + + *file = ga.ga_data; + *num_file = ga.ga_len; + return OK; +} + +/// Expand `file` for all comma-separated directories in `path`. +/// Adds matches to `ga`. +void globpath(char *path, char_u *file, garray_T *ga, int expand_options) +{ + expand_T xpc; + ExpandInit(&xpc); + xpc.xp_context = EXPAND_FILES; + + char_u *buf = xmalloc(MAXPATHL); + + // Loop over all entries in {path}. + while (*path != NUL) { + // Copy one item of the path to buf[] and concatenate the file name. + copy_option_part(&path, (char *)buf, MAXPATHL, ","); + if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL) { + add_pathsep((char *)buf); + STRCAT(buf, file); // NOLINT + + char **p; + int num_p = 0; + (void)ExpandFromContext(&xpc, buf, &num_p, &p, + WILD_SILENT | expand_options); + if (num_p > 0) { + ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT | expand_options); + + // Concatenate new results to previous ones. + ga_grow(ga, num_p); + // take over the pointers and put them in "ga" + for (int i = 0; i < num_p; i++) { + ((char_u **)ga->ga_data)[ga->ga_len] = (char_u *)p[i]; + ga->ga_len++; + } + xfree(p); + } + } + } + + xfree(buf); +} + +/// Translate some keys pressed when 'wildmenu' is used. +int wildmenu_translate_key(CmdlineInfo *cclp, int key, expand_T *xp, int did_wild_list) +{ + int c = key; + + if (did_wild_list) { + if (c == K_LEFT) { + c = Ctrl_P; + } else if (c == K_RIGHT) { + c = Ctrl_N; + } + } + + // Hitting CR after "emenu Name.": complete submenu + if (xp->xp_context == EXPAND_MENUNAMES + && cclp->cmdpos > 1 + && cclp->cmdbuff[cclp->cmdpos - 1] == '.' + && cclp->cmdbuff[cclp->cmdpos - 2] != '\\' + && (c == '\n' || c == '\r' || c == K_KENTER)) { + c = K_DOWN; + } + + return c; +} + +/// Delete characters on the command line, from "from" to the current position. +static void cmdline_del(CmdlineInfo *cclp, int from) +{ + assert(cclp->cmdpos <= cclp->cmdlen); + memmove(cclp->cmdbuff + from, cclp->cmdbuff + cclp->cmdpos, + (size_t)cclp->cmdlen - (size_t)cclp->cmdpos + 1); + cclp->cmdlen -= cclp->cmdpos - from; + cclp->cmdpos = from; +} + +/// Handle a key pressed when wild menu is displayed +int wildmenu_process_key(CmdlineInfo *cclp, int key, expand_T *xp) +{ + int c = key; + + // Special translations for 'wildmenu' + if (xp->xp_context == EXPAND_MENUNAMES) { + // Hitting <Down> after "emenu Name.": complete submenu + if (c == K_DOWN && cclp->cmdpos > 0 + && cclp->cmdbuff[cclp->cmdpos - 1] == '.') { + c = (int)p_wc; + KeyTyped = true; // in case the key was mapped + } else if (c == K_UP) { + // Hitting <Up>: Remove one submenu name in front of the + // cursor + int found = false; + + int j = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); + int i = 0; + while (--j > 0) { + // check for start of menu name + if (cclp->cmdbuff[j] == ' ' + && cclp->cmdbuff[j - 1] != '\\') { + i = j + 1; + break; + } + + // check for start of submenu name + if (cclp->cmdbuff[j] == '.' + && cclp->cmdbuff[j - 1] != '\\') { + if (found) { + i = j + 1; + break; + } else { + found = true; + } + } + } + if (i > 0) { + cmdline_del(cclp, i); + } + c = (int)p_wc; + KeyTyped = true; // in case the key was mapped + xp->xp_context = EXPAND_NOTHING; + } + } + if (xp->xp_context == EXPAND_FILES + || xp->xp_context == EXPAND_DIRECTORIES + || xp->xp_context == EXPAND_SHELLCMD) { + char_u upseg[5]; + + upseg[0] = PATHSEP; + upseg[1] = '.'; + upseg[2] = '.'; + upseg[3] = PATHSEP; + upseg[4] = NUL; + + if (c == K_DOWN + && cclp->cmdpos > 0 + && cclp->cmdbuff[cclp->cmdpos - 1] == PATHSEP + && (cclp->cmdpos < 3 + || cclp->cmdbuff[cclp->cmdpos - 2] != '.' + || cclp->cmdbuff[cclp->cmdpos - 3] != '.')) { + // go down a directory + c = (int)p_wc; + KeyTyped = true; // in case the key was mapped + } else if (STRNCMP(xp->xp_pattern, upseg + 1, 3) == 0 + && c == K_DOWN) { + // If in a direct ancestor, strip off one ../ to go down + int found = false; + + int j = cclp->cmdpos; + int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); + while (--j > i) { + j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); + if (vim_ispathsep(cclp->cmdbuff[j])) { + found = true; + break; + } + } + if (found + && cclp->cmdbuff[j - 1] == '.' + && cclp->cmdbuff[j - 2] == '.' + && (vim_ispathsep(cclp->cmdbuff[j - 3]) || j == i + 2)) { + cmdline_del(cclp, j - 2); + c = (int)p_wc; + KeyTyped = true; // in case the key was mapped + } + } else if (c == K_UP) { + // go up a directory + int found = false; + + int j = cclp->cmdpos - 1; + int i = (int)((char_u *)xp->xp_pattern - cclp->cmdbuff); + while (--j > i) { + j -= utf_head_off(cclp->cmdbuff, cclp->cmdbuff + j); + if (vim_ispathsep(cclp->cmdbuff[j]) +#ifdef BACKSLASH_IN_FILENAME + && vim_strchr((const char_u *)" *?[{`$%#", cclp->cmdbuff[j + 1]) + == NULL +#endif + ) { + if (found) { + i = j + 1; + break; + } else { + found = true; + } + } + } + + if (!found) { + j = i; + } else if (STRNCMP(cclp->cmdbuff + j, upseg, 4) == 0) { + j += 4; + } else if (STRNCMP(cclp->cmdbuff + j, upseg + 1, 3) == 0 + && j == i) { + j += 3; + } else { + j = 0; + } + + if (j > 0) { + // TODO(tarruda): this is only for DOS/Unix systems - need to put in + // machine-specific stuff here and in upseg init + cmdline_del(cclp, j); + put_on_cmdline(upseg + 1, 3, false); + } else if (cclp->cmdpos > i) { + cmdline_del(cclp, i); + } + + // Now complete in the new directory. Set KeyTyped in case the + // Up key came from a mapping. + c = (int)p_wc; + KeyTyped = true; + } + } + + return c; +} + +/// Free expanded names when finished walking through the matches +void wildmenu_cleanup(CmdlineInfo *cclp) +{ + if (!p_wmnu || wild_menu_showing == 0) { + return; + } + + const bool skt = KeyTyped; + const int old_RedrawingDisabled = RedrawingDisabled; + + if (cclp->input_fn) { + RedrawingDisabled = 0; + } + + if (wild_menu_showing == WM_SCROLLED) { + // Entered command line, move it up + cmdline_row--; + redrawcmd(); + wild_menu_showing = 0; + } else if (save_p_ls != -1) { + // restore 'laststatus' and 'winminheight' + p_ls = save_p_ls; + p_wmh = save_p_wmh; + last_status(false); + update_screen(VALID); // redraw the screen NOW + redrawcmd(); + save_p_ls = -1; + wild_menu_showing = 0; + // don't redraw statusline if WM_LIST is showing + } else if (wild_menu_showing != WM_LIST) { + win_redraw_last_status(topframe); + wild_menu_showing = 0; // must be before redraw_statuslines #8385 + redraw_statuslines(); + } else { + wild_menu_showing = 0; + } + KeyTyped = skt; + if (cclp->input_fn) { + RedrawingDisabled = old_RedrawingDisabled; + } +} + +/// "getcompletion()" function +void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) +{ + char_u *pat; + expand_T xpc; + bool filtered = false; + int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH + | WILD_NO_BEEP | WILD_HOME_REPLACE; + + if (argvars[1].v_type != VAR_STRING) { + semsg(_(e_invarg2), "type must be a string"); + return; + } + const char *const type = tv_get_string(&argvars[1]); + + if (argvars[2].v_type != VAR_UNKNOWN) { + filtered = (bool)tv_get_number_chk(&argvars[2], NULL); + } + + if (p_wic) { + options |= WILD_ICASE; + } + + // For filtered results, 'wildignore' is used + if (!filtered) { + options |= WILD_KEEP_ALL; + } + + if (argvars[0].v_type != VAR_STRING) { + emsg(_(e_invarg)); + return; + } + const char *pattern = tv_get_string(&argvars[0]); + + if (strcmp(type, "cmdline") == 0) { + set_one_cmd_context(&xpc, pattern); + xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); + xpc.xp_col = (int)STRLEN(pattern); + goto theend; + } + + ExpandInit(&xpc); + xpc.xp_pattern = (char *)pattern; + xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); + xpc.xp_context = cmdcomplete_str_to_type(type); + if (xpc.xp_context == EXPAND_NOTHING) { + semsg(_(e_invarg2), type); + return; + } + + if (xpc.xp_context == EXPAND_MENUS) { + set_context_in_menu_cmd(&xpc, "menu", xpc.xp_pattern, false); + xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); + } + + if (xpc.xp_context == EXPAND_CSCOPE) { + set_context_in_cscope_cmd(&xpc, (const char *)xpc.xp_pattern, CMD_cscope); + xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); + } + + if (xpc.xp_context == EXPAND_SIGN) { + set_context_in_sign_cmd(&xpc, (char_u *)xpc.xp_pattern); + xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); + } + +theend: + pat = addstar((char_u *)xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context); + ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP); + tv_list_alloc_ret(rettv, xpc.xp_numfiles); + + for (int i = 0; i < xpc.xp_numfiles; i++) { + tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], + -1); + } + xfree(pat); + ExpandCleanup(&xpc); +} diff --git a/src/nvim/cmdexpand.h b/src/nvim/cmdexpand.h new file mode 100644 index 0000000000..93e91af169 --- /dev/null +++ b/src/nvim/cmdexpand.h @@ -0,0 +1,44 @@ +#ifndef NVIM_CMDEXPAND_H +#define NVIM_CMDEXPAND_H + +#include "nvim/eval/typval.h" +#include "nvim/ex_getln.h" +#include "nvim/garray.h" +#include "nvim/types.h" + +// Values for nextwild() and ExpandOne(). See ExpandOne() for meaning. + +enum { + WILD_FREE = 1, + WILD_EXPAND_FREE = 2, + WILD_EXPAND_KEEP = 3, + WILD_NEXT = 4, + WILD_PREV = 5, + WILD_ALL = 6, + WILD_LONGEST = 7, + WILD_ALL_KEEP = 8, + WILD_CANCEL = 9, + WILD_APPLY = 10, +}; + +enum { + WILD_LIST_NOTFOUND = 0x01, + WILD_HOME_REPLACE = 0x02, + WILD_USE_NL = 0x04, + WILD_NO_BEEP = 0x08, + WILD_ADD_SLASH = 0x10, + WILD_KEEP_ALL = 0x20, + WILD_SILENT = 0x40, + WILD_ESCAPE = 0x80, + WILD_ICASE = 0x100, + WILD_ALLLINKS = 0x200, + WILD_IGNORE_COMPLETESLASH = 0x400, + WILD_NOERROR = 0x800, ///< sets EW_NOERROR + WILD_BUFLASTUSED = 0x1000, + BUF_DIFF_FILTER = 0x2000, +}; + +#ifdef INCLUDE_GENERATED_DECLARATIONS +# include "cmdexpand.h.generated.h" +#endif +#endif // NVIM_CMDEXPAND_H diff --git a/src/nvim/cmdhist.c b/src/nvim/cmdhist.c index 5725a6655d..13f97ba1e8 100644 --- a/src/nvim/cmdhist.c +++ b/src/nvim/cmdhist.c @@ -6,6 +6,7 @@ #include "nvim/ascii.h" #include "nvim/charset.h" #include "nvim/cmdhist.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_getln.h" #include "nvim/regexp.h" #include "nvim/strings.h" diff --git a/src/nvim/drawscreen.c b/src/nvim/drawscreen.c index 41d7d22934..2abff6c894 100644 --- a/src/nvim/drawscreen.c +++ b/src/nvim/drawscreen.c @@ -61,6 +61,7 @@ #include "nvim/buffer.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/diff.h" #include "nvim/drawscreen.h" #include "nvim/ex_getln.h" diff --git a/src/nvim/eval.c b/src/nvim/eval.c index c39fe44162..cb46e26f82 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -28,6 +28,7 @@ #include "nvim/eval/typval.h" #include "nvim/eval/userfunc.h" #include "nvim/eval/vars.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 940f245d53..9c3c859771 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -14,6 +14,7 @@ #include "nvim/change.h" #include "nvim/channel.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cmdhist.h" #include "nvim/context.h" #include "nvim/cursor.h" @@ -28,6 +29,7 @@ #include "nvim/eval/typval.h" #include "nvim/eval/userfunc.h" #include "nvim/eval/vars.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" #include "nvim/ex_getln.h" @@ -2751,84 +2753,6 @@ static void f_getcmdwintype(typval_T *argvars, typval_T *rettv, FunPtr fptr) rettv->vval.v_string[0] = (char)cmdwin_type; } -/// "getcompletion()" function -static void f_getcompletion(typval_T *argvars, typval_T *rettv, FunPtr fptr) -{ - char_u *pat; - expand_T xpc; - bool filtered = false; - int options = WILD_SILENT | WILD_USE_NL | WILD_ADD_SLASH - | WILD_NO_BEEP | WILD_HOME_REPLACE; - - if (argvars[1].v_type != VAR_STRING) { - semsg(_(e_invarg2), "type must be a string"); - return; - } - const char *const type = tv_get_string(&argvars[1]); - - if (argvars[2].v_type != VAR_UNKNOWN) { - filtered = (bool)tv_get_number_chk(&argvars[2], NULL); - } - - if (p_wic) { - options |= WILD_ICASE; - } - - // For filtered results, 'wildignore' is used - if (!filtered) { - options |= WILD_KEEP_ALL; - } - - if (argvars[0].v_type != VAR_STRING) { - emsg(_(e_invarg)); - return; - } - const char *pattern = tv_get_string(&argvars[0]); - - if (strcmp(type, "cmdline") == 0) { - set_one_cmd_context(&xpc, pattern); - xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); - xpc.xp_col = (int)STRLEN(pattern); - goto theend; - } - - ExpandInit(&xpc); - xpc.xp_pattern = (char *)pattern; - xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); - xpc.xp_context = cmdcomplete_str_to_type(type); - if (xpc.xp_context == EXPAND_NOTHING) { - semsg(_(e_invarg2), type); - return; - } - - if (xpc.xp_context == EXPAND_MENUS) { - set_context_in_menu_cmd(&xpc, "menu", xpc.xp_pattern, false); - xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); - } - - if (xpc.xp_context == EXPAND_CSCOPE) { - set_context_in_cscope_cmd(&xpc, (const char *)xpc.xp_pattern, CMD_cscope); - xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); - } - - if (xpc.xp_context == EXPAND_SIGN) { - set_context_in_sign_cmd(&xpc, (char_u *)xpc.xp_pattern); - xpc.xp_pattern_len = STRLEN(xpc.xp_pattern); - } - -theend: - pat = addstar((char_u *)xpc.xp_pattern, xpc.xp_pattern_len, xpc.xp_context); - ExpandOne(&xpc, pat, NULL, options, WILD_ALL_KEEP); - tv_list_alloc_ret(rettv, xpc.xp_numfiles); - - for (int i = 0; i < xpc.xp_numfiles; i++) { - tv_list_append_string(rettv->vval.v_list, (const char *)xpc.xp_files[i], - -1); - } - xfree(pat); - ExpandCleanup(&xpc); -} - /// `getcwd([{win}[, {tab}]])` function /// /// Every scope not specified implies the currently selected scope object. @@ -7705,9 +7629,9 @@ static void f_setenv(typval_T *argvars, typval_T *rettv, FunPtr fptr) if (argvars[1].v_type == VAR_SPECIAL && argvars[1].vval.v_special == kSpecialVarNull) { - os_unsetenv(name); + vim_unsetenv_ext(name); } else { - os_setenv(name, tv_get_string_buf(&argvars[1], valbuf), 1); + vim_setenv_ext(name, tv_get_string_buf(&argvars[1], valbuf)); } } @@ -9709,7 +9633,7 @@ static void f_visualmode(typval_T *argvars, typval_T *rettv, FunPtr fptr) /// "wildmenumode()" function static void f_wildmenumode(typval_T *argvars, typval_T *rettv, FunPtr fptr) { - if (wild_menu_showing || ((State & MODE_CMDLINE) && pum_visible())) { + if (wild_menu_showing || ((State & MODE_CMDLINE) && cmdline_pum_active())) { rettv->vval.v_number = 1; } } diff --git a/src/nvim/eval/vars.c b/src/nvim/eval/vars.c index 1ede7b35d3..b38849730a 100644 --- a/src/nvim/eval/vars.c +++ b/src/nvim/eval/vars.c @@ -593,15 +593,7 @@ static char *ex_let_one(char *arg, typval_T *const tv, const bool copy, const bo } } if (p != NULL) { - os_setenv(name, p, 1); - if (STRICMP(name, "HOME") == 0) { - init_homedir(); - } else if (didset_vim && STRICMP(name, "VIM") == 0) { - didset_vim = false; - } else if (didset_vimruntime - && STRICMP(name, "VIMRUNTIME") == 0) { - didset_vimruntime = false; - } + vim_setenv_ext(name, p); arg_end = arg; } name[len] = c1; @@ -859,7 +851,7 @@ static int do_unlet_var(lval_T *lp, char *name_end, exarg_T *eap, int deep FUNC_ // Environment variable, normal name or expanded name. if (*lp->ll_name == '$') { - os_unsetenv(lp->ll_name + 1); + vim_unsetenv_ext(lp->ll_name + 1); } else if (do_unlet(lp->ll_name, lp->ll_name_len, forceit) == FAIL) { ret = FAIL; } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index 6cd6e32e72..7bf272fbba 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -14,6 +14,7 @@ #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/debugger.h" @@ -3067,820 +3068,22 @@ void f_fullcommand(typval_T *argvars, typval_T *rettv, FunPtr fptr) : (char_u *)cmdnames[ea.cmdidx].cmd_name); } -/// This is all pretty much copied from do_one_cmd(), with all the extra stuff -/// we don't need/want deleted. Maybe this could be done better if we didn't -/// repeat all this stuff. The only problem is that they may not stay -/// perfectly compatible with each other, but then the command line syntax -/// probably won't change that much -- webb. -/// -/// @param buff buffer for command string -const char *set_one_cmd_context(expand_T *xp, const char *buff) +cmdidx_T excmd_get_cmdidx(const char *cmd, size_t len) { - size_t len = 0; - exarg_T ea; - int context = EXPAND_NOTHING; - bool forceit = false; - bool usefilter = false; // Filter instead of file name. - - ExpandInit(xp); - xp->xp_pattern = (char *)buff; - xp->xp_line = (char *)buff; - xp->xp_context = EXPAND_COMMANDS; // Default until we get past command - ea.argt = 0; - - // 2. skip comment lines and leading space, colons or bars - const char *cmd; - for (cmd = buff; vim_strchr(" \t:|", *cmd) != NULL; cmd++) {} - xp->xp_pattern = (char *)cmd; - - if (*cmd == NUL) { - return NULL; - } - if (*cmd == '"') { // ignore comment lines - xp->xp_context = EXPAND_NOTHING; - return NULL; - } - - // 3. parse a range specifier of the form: addr [,addr] [;addr] .. - cmd = (const char *)skip_range(cmd, &xp->xp_context); - - // 4. parse command - xp->xp_pattern = (char *)cmd; - if (*cmd == NUL) { - return NULL; - } - if (*cmd == '"') { - xp->xp_context = EXPAND_NOTHING; - return NULL; - } - - if (*cmd == '|' || *cmd == '\n') { - return cmd + 1; // There's another command - } - // Isolate the command and search for it in the command table. - // Exceptions: - // - the 'k' command can directly be followed by any character, but - // do accept "keepmarks", "keepalt" and "keepjumps". - // - the 's' command can be followed directly by 'c', 'g', 'i', 'I' or 'r' - const char *p; - if (*cmd == 'k' && cmd[1] != 'e') { - ea.cmdidx = CMD_k; - p = cmd + 1; - } else { - p = cmd; - while (ASCII_ISALPHA(*p) || *p == '*') { // Allow * wild card - p++; - } - // a user command may contain digits - if (ASCII_ISUPPER(cmd[0])) { - while (ASCII_ISALNUM(*p) || *p == '*') { - p++; - } - } - // for python 3.x: ":py3*" commands completion - if (cmd[0] == 'p' && cmd[1] == 'y' && p == cmd + 2 && *p == '3') { - p++; - while (ASCII_ISALPHA(*p) || *p == '*') { - p++; - } - } - // check for non-alpha command - if (p == cmd && vim_strchr("@*!=><&~#", *p) != NULL) { - p++; - } - len = (size_t)(p - cmd); - - if (len == 0) { - xp->xp_context = EXPAND_UNSUCCESSFUL; - return NULL; - } - for (ea.cmdidx = (cmdidx_T)0; (int)ea.cmdidx < CMD_SIZE; - ea.cmdidx = (cmdidx_T)((int)ea.cmdidx + 1)) { - if (STRNCMP(cmdnames[(int)ea.cmdidx].cmd_name, cmd, len) == 0) { - break; - } - } - - if (cmd[0] >= 'A' && cmd[0] <= 'Z') { - while (ASCII_ISALNUM(*p) || *p == '*') { // Allow * wild card - p++; - } - } - } - - // - // If the cursor is touching the command, and it ends in an alphanumeric - // character, complete the command name. - // - if (*p == NUL && ASCII_ISALNUM(p[-1])) { - return NULL; - } - - if (ea.cmdidx == CMD_SIZE) { - if (*cmd == 's' && vim_strchr("cgriI", cmd[1]) != NULL) { - ea.cmdidx = CMD_substitute; - p = cmd + 1; - } else if (cmd[0] >= 'A' && cmd[0] <= 'Z') { - ea.cmd = (char *)cmd; - p = (const char *)find_ucmd(&ea, (char *)p, NULL, xp, &context); - if (p == NULL) { - ea.cmdidx = CMD_SIZE; // Ambiguous user command. - } - } - } - if (ea.cmdidx == CMD_SIZE) { - // Not still touching the command and it was an illegal one - xp->xp_context = EXPAND_UNSUCCESSFUL; - return NULL; - } - - xp->xp_context = EXPAND_NOTHING; // Default now that we're past command - - if (*p == '!') { // forced commands - forceit = true; - p++; - } - - // 5. parse arguments - if (!IS_USER_CMDIDX(ea.cmdidx)) { - ea.argt = cmdnames[(int)ea.cmdidx].cmd_argt; - } - - const char *arg = (const char *)skipwhite(p); - - // Skip over ++argopt argument - if ((ea.argt & EX_ARGOPT) && *arg != NUL && strncmp(arg, "++", 2) == 0) { - p = arg; - while (*p && !ascii_isspace(*p)) { - MB_PTR_ADV(p); - } - arg = (const char *)skipwhite(p); - } + cmdidx_T idx; - if (ea.cmdidx == CMD_write || ea.cmdidx == CMD_update) { - if (*arg == '>') { // Append. - if (*++arg == '>') { - arg++; - } - arg = (const char *)skipwhite(arg); - } else if (*arg == '!' && ea.cmdidx == CMD_write) { // :w !filter - arg++; - usefilter = true; - } - } - - if (ea.cmdidx == CMD_read) { - usefilter = forceit; // :r! filter if forced - if (*arg == '!') { // :r !filter - arg++; - usefilter = true; - } - } - - if (ea.cmdidx == CMD_lshift || ea.cmdidx == CMD_rshift) { - while (*arg == *cmd) { // allow any number of '>' or '<' - arg++; - } - arg = (const char *)skipwhite(arg); - } - - // Does command allow "+command"? - if ((ea.argt & EX_CMDARG) && !usefilter && *arg == '+') { - // Check if we're in the +command - p = arg + 1; - arg = (const char *)skip_cmd_arg((char *)arg, false); - - // Still touching the command after '+'? - if (*arg == NUL) { - return p; - } - - // Skip space(s) after +command to get to the real argument. - arg = (const char *)skipwhite(arg); - } - - // Check for '|' to separate commands and '"' to start comments. - // Don't do this for ":read !cmd" and ":write !cmd". - if ((ea.argt & EX_TRLBAR) && !usefilter) { - p = arg; - // ":redir @" is not the start of a comment - if (ea.cmdidx == CMD_redir && p[0] == '@' && p[1] == '"') { - p += 2; - } - while (*p) { - if (*p == Ctrl_V) { - if (p[1] != NUL) { - p++; - } - } else if ((*p == '"' && !(ea.argt & EX_NOTRLCOM)) - || *p == '|' - || *p == '\n') { - if (*(p - 1) != '\\') { - if (*p == '|' || *p == '\n') { - return p + 1; - } - return NULL; // It's a comment - } - } - MB_PTR_ADV(p); - } - } - - if (!(ea.argt & EX_EXTRA) && *arg != NUL && strchr("|\"", *arg) == NULL) { - // no arguments allowed but there is something - return NULL; - } - - // Find start of last argument (argument just before cursor): - p = buff; - xp->xp_pattern = (char *)p; - len = strlen(buff); - while (*p && p < buff + len) { - if (*p == ' ' || *p == TAB) { - // Argument starts after a space. - xp->xp_pattern = (char *)++p; - } else { - if (*p == '\\' && *(p + 1) != NUL) { - p++; // skip over escaped character - } - MB_PTR_ADV(p); - } - } - - if (ea.argt & EX_XFILE) { - int in_quote = false; - const char *bow = NULL; // Beginning of word. - - // Allow spaces within back-quotes to count as part of the argument - // being expanded. - xp->xp_pattern = skipwhite(arg); - p = (const char *)xp->xp_pattern; - while (*p != NUL) { - int c = utf_ptr2char(p); - if (c == '\\' && p[1] != NUL) { - p++; - } else if (c == '`') { - if (!in_quote) { - xp->xp_pattern = (char *)p; - bow = p + 1; - } - in_quote = !in_quote; - // An argument can contain just about everything, except - // characters that end the command and white space. - } else if (c == '|' || c == '\n' || c == '"' || ascii_iswhite(c)) { - len = 0; // avoid getting stuck when space is in 'isfname' - while (*p != NUL) { - c = utf_ptr2char(p); - if (c == '`' || vim_isfilec_or_wc(c)) { - break; - } - len = (size_t)utfc_ptr2len(p); - MB_PTR_ADV(p); - } - if (in_quote) { - bow = p; - } else { - xp->xp_pattern = (char *)p; - } - p -= len; - } - MB_PTR_ADV(p); - } - - // If we are still inside the quotes, and we passed a space, just - // expand from there. - if (bow != NULL && in_quote) { - xp->xp_pattern = (char *)bow; - } - xp->xp_context = EXPAND_FILES; - - // For a shell command more chars need to be escaped. - if (usefilter || ea.cmdidx == CMD_bang || ea.cmdidx == CMD_terminal) { -#ifndef BACKSLASH_IN_FILENAME - xp->xp_shell = true; -#endif - // When still after the command name expand executables. - if (xp->xp_pattern == skipwhite(arg)) { - xp->xp_context = EXPAND_SHELLCMD; - } - } - - // Check for environment variable. - if (*xp->xp_pattern == '$') { - for (p = (const char *)xp->xp_pattern + 1; *p != NUL; p++) { - if (!vim_isIDc((uint8_t)(*p))) { - break; - } - } - if (*p == NUL) { - xp->xp_context = EXPAND_ENV_VARS; - xp->xp_pattern++; - // Avoid that the assignment uses EXPAND_FILES again. - if (context != EXPAND_USER_DEFINED && context != EXPAND_USER_LIST) { - context = EXPAND_ENV_VARS; - } - } - } - // Check for user names. - if (*xp->xp_pattern == '~') { - for (p = (const char *)xp->xp_pattern + 1; *p != NUL && *p != '/'; p++) {} - // Complete ~user only if it partially matches a user name. - // A full match ~user<Tab> will be replaced by user's home - // directory i.e. something like ~user<Tab> -> /home/user/ - if (*p == NUL && p > (const char *)xp->xp_pattern + 1 - && match_user((char_u *)xp->xp_pattern + 1) >= 1) { - xp->xp_context = EXPAND_USER; - xp->xp_pattern++; - } - } - } - - // 6. switch on command name - switch (ea.cmdidx) { - case CMD_find: - case CMD_sfind: - case CMD_tabfind: - if (xp->xp_context == EXPAND_FILES) { - xp->xp_context = EXPAND_FILES_IN_PATH; - } - break; - case CMD_cd: - case CMD_chdir: - case CMD_lcd: - case CMD_lchdir: - case CMD_tcd: - case CMD_tchdir: - if (xp->xp_context == EXPAND_FILES) { - xp->xp_context = EXPAND_DIRECTORIES; - } - break; - case CMD_help: - xp->xp_context = EXPAND_HELP; - xp->xp_pattern = (char *)arg; - break; - - // Command modifiers: return the argument. - // Also for commands with an argument that is a command. - case CMD_aboveleft: - case CMD_argdo: - case CMD_belowright: - case CMD_botright: - case CMD_browse: - case CMD_bufdo: - case CMD_cdo: - case CMD_cfdo: - case CMD_confirm: - case CMD_debug: - case CMD_folddoclosed: - case CMD_folddoopen: - case CMD_hide: - case CMD_keepalt: - case CMD_keepjumps: - case CMD_keepmarks: - case CMD_keeppatterns: - case CMD_ldo: - case CMD_leftabove: - case CMD_lfdo: - case CMD_lockmarks: - case CMD_noautocmd: - case CMD_noswapfile: - case CMD_rightbelow: - case CMD_sandbox: - case CMD_silent: - case CMD_tab: - case CMD_tabdo: - case CMD_topleft: - case CMD_verbose: - case CMD_vertical: - case CMD_windo: - return arg; - - case CMD_filter: - if (*arg != NUL) { - arg = (const char *)skip_vimgrep_pat((char *)arg, NULL, NULL); - } - if (arg == NULL || *arg == NUL) { - xp->xp_context = EXPAND_NOTHING; - return NULL; - } - return (const char *)skipwhite(arg); - - case CMD_match: - if (*arg == NUL || !ends_excmd(*arg)) { - // also complete "None" - set_context_in_echohl_cmd(xp, arg); - arg = (const char *)skipwhite((char *)skiptowhite((const char_u *)arg)); - if (*arg != NUL) { - xp->xp_context = EXPAND_NOTHING; - arg = (const char *)skip_regexp((char_u *)arg + 1, (uint8_t)(*arg), - p_magic, NULL); - } - } - return (const char *)find_nextcmd((char_u *)arg); - - // All completion for the +cmdline_compl feature goes here. - - case CMD_command: - return set_context_in_user_cmd(xp, arg); - - case CMD_delcommand: - xp->xp_context = EXPAND_USER_COMMANDS; - xp->xp_pattern = (char *)arg; - break; - - case CMD_global: - case CMD_vglobal: { - const int delim = (uint8_t)(*arg); // Get the delimiter. - if (delim) { - arg++; // Skip delimiter if there is one. - } - - while (arg[0] != NUL && (uint8_t)arg[0] != delim) { - if (arg[0] == '\\' && arg[1] != NUL) { - arg++; - } - arg++; - } - if (arg[0] != NUL) { - return arg + 1; - } - break; - } - case CMD_and: - case CMD_substitute: { - const int delim = (uint8_t)(*arg); - if (delim) { - // Skip "from" part. - arg++; - arg = (const char *)skip_regexp((char_u *)arg, delim, p_magic, NULL); - } - // Skip "to" part. - while (arg[0] != NUL && (uint8_t)arg[0] != delim) { - if (arg[0] == '\\' && arg[1] != NUL) { - arg++; - } - arg++; - } - if (arg[0] != NUL) { // Skip delimiter. - arg++; - } - while (arg[0] && strchr("|\"#", arg[0]) == NULL) { - arg++; - } - if (arg[0] != NUL) { - return arg; + for (idx = (cmdidx_T)0; (int)idx < (int)CMD_SIZE; idx = (cmdidx_T)((int)idx + 1)) { + if (strncmp(cmdnames[(int)idx].cmd_name, cmd, len) == 0) { + break; } - break; } - case CMD_isearch: - case CMD_dsearch: - case CMD_ilist: - case CMD_dlist: - case CMD_ijump: - case CMD_psearch: - case CMD_djump: - case CMD_isplit: - case CMD_dsplit: - // Skip count. - arg = (const char *)skipwhite(skipdigits(arg)); - if (*arg == '/') { // Match regexp, not just whole words. - for (++arg; *arg && *arg != '/'; arg++) { - if (*arg == '\\' && arg[1] != NUL) { - arg++; - } - } - if (*arg) { - arg = (const char *)skipwhite(arg + 1); - - // Check for trailing illegal characters. - if (*arg && strchr("|\"\n", *arg) == NULL) { - xp->xp_context = EXPAND_NOTHING; - } else { - return arg; - } - } - } - break; - case CMD_autocmd: - return (const char *)set_context_in_autocmd(xp, (char *)arg, false); - - case CMD_doautocmd: - case CMD_doautoall: - return (const char *)set_context_in_autocmd(xp, (char *)arg, true); - case CMD_set: - set_context_in_set_cmd(xp, (char_u *)arg, 0); - break; - case CMD_setglobal: - set_context_in_set_cmd(xp, (char_u *)arg, OPT_GLOBAL); - break; - case CMD_setlocal: - set_context_in_set_cmd(xp, (char_u *)arg, OPT_LOCAL); - break; - case CMD_tag: - case CMD_stag: - case CMD_ptag: - case CMD_ltag: - case CMD_tselect: - case CMD_stselect: - case CMD_ptselect: - case CMD_tjump: - case CMD_stjump: - case CMD_ptjump: - if (wop_flags & WOP_TAGFILE) { - xp->xp_context = EXPAND_TAGS_LISTFILES; - } else { - xp->xp_context = EXPAND_TAGS; - } - xp->xp_pattern = (char *)arg; - break; - case CMD_augroup: - xp->xp_context = EXPAND_AUGROUP; - xp->xp_pattern = (char *)arg; - break; - case CMD_syntax: - set_context_in_syntax_cmd(xp, arg); - break; - case CMD_const: - case CMD_let: - case CMD_if: - case CMD_elseif: - case CMD_while: - case CMD_for: - case CMD_echo: - case CMD_echon: - case CMD_execute: - case CMD_echomsg: - case CMD_echoerr: - case CMD_call: - case CMD_return: - case CMD_cexpr: - case CMD_caddexpr: - case CMD_cgetexpr: - case CMD_lexpr: - case CMD_laddexpr: - case CMD_lgetexpr: - set_context_for_expression(xp, (char *)arg, ea.cmdidx); - break; - - case CMD_unlet: - while ((xp->xp_pattern = strchr(arg, ' ')) != NULL) { - arg = (const char *)xp->xp_pattern + 1; - } - - xp->xp_context = EXPAND_USER_VARS; - xp->xp_pattern = (char *)arg; - - if (*xp->xp_pattern == '$') { - xp->xp_context = EXPAND_ENV_VARS; - xp->xp_pattern++; - } - - break; - - case CMD_function: - case CMD_delfunction: - xp->xp_context = EXPAND_USER_FUNC; - xp->xp_pattern = (char *)arg; - break; - - case CMD_echohl: - set_context_in_echohl_cmd(xp, arg); - break; - case CMD_highlight: - set_context_in_highlight_cmd(xp, arg); - break; - case CMD_cscope: - case CMD_lcscope: - case CMD_scscope: - set_context_in_cscope_cmd(xp, arg, ea.cmdidx); - break; - case CMD_sign: - set_context_in_sign_cmd(xp, (char_u *)arg); - break; - case CMD_bdelete: - case CMD_bwipeout: - case CMD_bunload: - while ((xp->xp_pattern = strchr(arg, ' ')) != NULL) { - arg = (const char *)xp->xp_pattern + 1; - } - FALLTHROUGH; - case CMD_buffer: - case CMD_sbuffer: - case CMD_checktime: - xp->xp_context = EXPAND_BUFFERS; - xp->xp_pattern = (char *)arg; - break; - case CMD_diffget: - case CMD_diffput: - // If current buffer is in diff mode, complete buffer names - // which are in diff mode, and different than current buffer. - xp->xp_context = EXPAND_DIFF_BUFFERS; - xp->xp_pattern = (char *)arg; - break; - - case CMD_USER: - case CMD_USER_BUF: - if (context != EXPAND_NOTHING) { - // EX_XFILE: file names are handled above. - if (!(ea.argt & EX_XFILE)) { - if (context == EXPAND_MENUS) { - return (const char *)set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit); - } else if (context == EXPAND_COMMANDS) { - return arg; - } else if (context == EXPAND_MAPPINGS) { - return (const char *)set_context_in_map_cmd(xp, "map", (char_u *)arg, forceit, - false, false, - CMD_map); - } - // Find start of last argument. - p = arg; - while (*p) { - if (*p == ' ') { - // argument starts after a space - arg = p + 1; - } else if (*p == '\\' && *(p + 1) != NUL) { - p++; // skip over escaped character - } - MB_PTR_ADV(p); - } - xp->xp_pattern = (char *)arg; - } - xp->xp_context = context; - } - break; - case CMD_map: - case CMD_noremap: - case CMD_nmap: - case CMD_nnoremap: - case CMD_vmap: - case CMD_vnoremap: - case CMD_omap: - case CMD_onoremap: - case CMD_imap: - case CMD_inoremap: - case CMD_cmap: - case CMD_cnoremap: - case CMD_lmap: - case CMD_lnoremap: - case CMD_smap: - case CMD_snoremap: - case CMD_xmap: - case CMD_xnoremap: - return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, false, - false, ea.cmdidx); - case CMD_unmap: - case CMD_nunmap: - case CMD_vunmap: - case CMD_ounmap: - case CMD_iunmap: - case CMD_cunmap: - case CMD_lunmap: - case CMD_sunmap: - case CMD_xunmap: - return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, false, - true, ea.cmdidx); - case CMD_mapclear: - case CMD_nmapclear: - case CMD_vmapclear: - case CMD_omapclear: - case CMD_imapclear: - case CMD_cmapclear: - case CMD_lmapclear: - case CMD_smapclear: - case CMD_xmapclear: - xp->xp_context = EXPAND_MAPCLEAR; - xp->xp_pattern = (char *)arg; - break; - - case CMD_abbreviate: - case CMD_noreabbrev: - case CMD_cabbrev: - case CMD_cnoreabbrev: - case CMD_iabbrev: - case CMD_inoreabbrev: - return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, true, - false, ea.cmdidx); - case CMD_unabbreviate: - case CMD_cunabbrev: - case CMD_iunabbrev: - return (const char *)set_context_in_map_cmd(xp, (char *)cmd, (char_u *)arg, forceit, true, - true, ea.cmdidx); - case CMD_menu: - case CMD_noremenu: - case CMD_unmenu: - case CMD_amenu: - case CMD_anoremenu: - case CMD_aunmenu: - case CMD_nmenu: - case CMD_nnoremenu: - case CMD_nunmenu: - case CMD_vmenu: - case CMD_vnoremenu: - case CMD_vunmenu: - case CMD_omenu: - case CMD_onoremenu: - case CMD_ounmenu: - case CMD_imenu: - case CMD_inoremenu: - case CMD_iunmenu: - case CMD_cmenu: - case CMD_cnoremenu: - case CMD_cunmenu: - case CMD_tlmenu: - case CMD_tlnoremenu: - case CMD_tlunmenu: - case CMD_tmenu: - case CMD_tunmenu: - case CMD_popup: - case CMD_emenu: - return (const char *)set_context_in_menu_cmd(xp, cmd, (char *)arg, forceit); - - case CMD_colorscheme: - xp->xp_context = EXPAND_COLORS; - xp->xp_pattern = (char *)arg; - break; - - case CMD_compiler: - xp->xp_context = EXPAND_COMPILER; - xp->xp_pattern = (char *)arg; - break; - - case CMD_ownsyntax: - xp->xp_context = EXPAND_OWNSYNTAX; - xp->xp_pattern = (char *)arg; - break; - - case CMD_setfiletype: - xp->xp_context = EXPAND_FILETYPE; - xp->xp_pattern = (char *)arg; - break; - - case CMD_packadd: - xp->xp_context = EXPAND_PACKADD; - xp->xp_pattern = (char *)arg; - break; - -#ifdef HAVE_WORKING_LIBINTL - case CMD_language: - p = (const char *)skiptowhite((const char_u *)arg); - if (*p == NUL) { - xp->xp_context = EXPAND_LANGUAGE; - xp->xp_pattern = (char *)arg; - } else { - if (strncmp(arg, "messages", (size_t)(p - arg)) == 0 - || strncmp(arg, "ctype", (size_t)(p - arg)) == 0 - || strncmp(arg, "time", (size_t)(p - arg)) == 0 - || strncmp(arg, "collate", (size_t)(p - arg)) == 0) { - xp->xp_context = EXPAND_LOCALES; - xp->xp_pattern = skipwhite(p); - } else { - xp->xp_context = EXPAND_NOTHING; - } - } - break; -#endif - case CMD_profile: - set_context_in_profile_cmd(xp, arg); - break; - case CMD_checkhealth: - xp->xp_context = EXPAND_CHECKHEALTH; - xp->xp_pattern = (char *)arg; - break; - case CMD_behave: - xp->xp_context = EXPAND_BEHAVE; - xp->xp_pattern = (char *)arg; - break; - case CMD_messages: - xp->xp_context = EXPAND_MESSAGES; - xp->xp_pattern = (char *)arg; - break; - - case CMD_history: - xp->xp_context = EXPAND_HISTORY; - xp->xp_pattern = (char *)arg; - break; - case CMD_syntime: - xp->xp_context = EXPAND_SYNTIME; - xp->xp_pattern = (char *)arg; - break; - - case CMD_argdelete: - while ((xp->xp_pattern = vim_strchr(arg, ' ')) != NULL) { - arg = (const char *)(xp->xp_pattern + 1); - } - xp->xp_context = EXPAND_ARGLIST; - xp->xp_pattern = (char *)arg; - break; - - case CMD_lua: - xp->xp_context = EXPAND_LUA; - break; + return idx; +} - default: - break; - } - return NULL; +uint32_t excmd_get_argt(cmdidx_T idx) +{ + return cmdnames[(int)idx].cmd_argt; } /// Skip a range specifier of the form: addr [,addr] [;addr] .. @@ -4749,7 +3952,7 @@ static char *getargcmd(char **argp) /// Find end of "+command" argument. Skip over "\ " and "\\". /// /// @param rembs true to halve the number of backslashes -static char *skip_cmd_arg(char *p, int rembs) +char *skip_cmd_arg(char *p, int rembs) { while (*p && !ascii_isspace(*p)) { if (*p == '\\' && p[1] != NUL) { @@ -7756,37 +6959,6 @@ static void ex_behave(exarg_T *eap) } } -/// Function given to ExpandGeneric() to obtain the possible arguments of the -/// ":behave {mswin,xterm}" command. -char *get_behave_arg(expand_T *xp, int idx) -{ - if (idx == 0) { - return "mswin"; - } - if (idx == 1) { - return "xterm"; - } - return NULL; -} - -/// Function given to ExpandGeneric() to obtain the possible arguments of the -/// ":messages {clear}" command. -char *get_messages_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) -{ - if (idx == 0) { - return "clear"; - } - return NULL; -} - -char *get_mapclear_arg(expand_T *xp FUNC_ATTR_UNUSED, int idx) -{ - if (idx == 0) { - return "<buffer>"; - } - return NULL; -} - static TriState filetype_detect = kNone; static TriState filetype_plugin = kNone; static TriState filetype_indent = kNone; diff --git a/src/nvim/ex_getln.c b/src/nvim/ex_getln.c index 4629cb98ea..a0bcccb5be 100644 --- a/src/nvim/ex_getln.c +++ b/src/nvim/ex_getln.c @@ -12,14 +12,13 @@ #include <string.h> #include "nvim/api/extmark.h" -#include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" #include "nvim/arabic.h" -#include "nvim/arglist.h" #include "nvim/ascii.h" #include "nvim/assert.h" #include "nvim/buffer.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cmdhist.h" #include "nvim/cursor.h" #include "nvim/cursor_shape.h" @@ -27,11 +26,8 @@ #include "nvim/drawscreen.h" #include "nvim/edit.h" #include "nvim/eval.h" -#include "nvim/eval/funcs.h" -#include "nvim/eval/userfunc.h" #include "nvim/event/loop.h" #include "nvim/ex_cmds.h" -#include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" #include "nvim/ex_getln.h" @@ -41,23 +37,19 @@ #include "nvim/getchar.h" #include "nvim/globals.h" #include "nvim/grid.h" -#include "nvim/help.h" #include "nvim/highlight.h" #include "nvim/highlight_defs.h" #include "nvim/highlight_group.h" -#include "nvim/if_cscope.h" #include "nvim/indent.h" #include "nvim/keycodes.h" #include "nvim/lib/kvec.h" #include "nvim/log.h" -#include "nvim/lua/executor.h" #include "nvim/main.h" #include "nvim/mapping.h" #include "nvim/mark.h" #include "nvim/mbyte.h" #include "nvim/memline.h" #include "nvim/memory.h" -#include "nvim/menu.h" #include "nvim/message.h" #include "nvim/mouse.h" #include "nvim/move.h" @@ -65,87 +57,22 @@ #include "nvim/option.h" #include "nvim/optionstr.h" #include "nvim/os/input.h" -#include "nvim/os/os.h" #include "nvim/os/time.h" -#include "nvim/os_unix.h" #include "nvim/path.h" #include "nvim/popupmenu.h" #include "nvim/profile.h" #include "nvim/regexp.h" #include "nvim/search.h" -#include "nvim/sign.h" #include "nvim/state.h" #include "nvim/strings.h" -#include "nvim/syntax.h" -#include "nvim/tag.h" #include "nvim/ui.h" #include "nvim/undo.h" +#include "nvim/usercmd.h" #include "nvim/vim.h" #include "nvim/viml/parser/expressions.h" #include "nvim/viml/parser/parser.h" #include "nvim/window.h" -/// Command-line colors: one chunk -/// -/// Defines a region which has the same highlighting. -typedef struct { - int start; ///< Colored chunk start. - int end; ///< Colored chunk end (exclusive, > start). - int attr; ///< Highlight attr. -} CmdlineColorChunk; - -/// Command-line colors -/// -/// Holds data about all colors. -typedef kvec_t(CmdlineColorChunk) CmdlineColors; - -/// Command-line coloring -/// -/// Holds both what are the colors and what have been colored. Latter is used to -/// suppress unnecessary calls to coloring callbacks. -typedef struct { - unsigned prompt_id; ///< ID of the prompt which was colored last. - char *cmdbuff; ///< What exactly was colored last time or NULL. - CmdlineColors colors; ///< Last colors. -} ColoredCmdline; - -/// Keeps track how much state must be sent to external ui. -typedef enum { - kCmdRedrawNone, - kCmdRedrawPos, - kCmdRedrawAll, -} CmdRedraw; - -// Variables shared between getcmdline(), redrawcmdline() and others. -// These need to be saved when using CTRL-R |, that's why they are in a -// structure. -struct cmdline_info { - char_u *cmdbuff; // pointer to command line buffer - int cmdbufflen; // length of cmdbuff - int cmdlen; // number of chars in command line - int cmdpos; // current cursor position - int cmdspos; // cursor column on screen - int cmdfirstc; // ':', '/', '?', '=', '>' or NUL - int cmdindent; // number of spaces before cmdline - char_u *cmdprompt; // message in front of cmdline - int cmdattr; // attributes for prompt - int overstrike; // Typing mode on the command line. Shared by - // getcmdline() and put_on_cmdline(). - expand_T *xpc; // struct being used for expansion, xp_pattern - // may point into cmdbuff - int xp_context; // type of expansion - char_u *xp_arg; // user-defined expansion arg - int input_fn; // when TRUE Invoked for input() function - unsigned prompt_id; ///< Prompt number, used to disable coloring on errors. - Callback highlight_callback; ///< Callback used for coloring user input. - ColoredCmdline last_colors; ///< Last cmdline colors - int level; // current cmdline level - struct cmdline_info *prev_ccline; ///< pointer to saved cmdline state - char special_char; ///< last putcmdline char (used for redraws) - bool special_shift; ///< shift of last putcmdline char - CmdRedraw redraw_state; ///< needed redraw for external cmdline -}; - /// Last value of prompt_id, incremented when doing new prompt static unsigned last_prompt_id = 0; @@ -227,39 +154,22 @@ typedef struct cmdpreview_info { garray_T save_view; } CpInfo; -typedef struct cmdline_info CmdlineInfo; - /// The current cmdline_info. It is initialized in getcmdline() and after that /// used by other functions. When invoking getcmdline() recursively it needs /// to be saved with save_cmdline() and restored with restore_cmdline(). -static struct cmdline_info ccline; - -static int cmd_showtail; // Only show path tail in lists ? +static CmdlineInfo ccline; static int new_cmdpos; // position set by set_cmdline_pos() /// currently displayed block of context static Array cmdline_block = ARRAY_DICT_INIT; -/* - * Type used by call_user_expand_func - */ -typedef void *(*user_expand_func_T)(const char_u *, int, typval_T *); - /// Flag for command_line_handle_key to ignore <C-c> /// /// Used if it was received while processing highlight function in order for /// user interrupting highlight function to not interrupt command-line. static bool getln_interrupted_highlight = false; -// "compl_match_array" points the currently displayed list of entries in the -// popup menu. It is NULL when there is no popup menu. -static pumitem_T *compl_match_array = NULL; -static int compl_match_arraysize; -// First column in cmdline of the matched item for completion. -static int compl_startcol; -static int compl_selected; - #ifdef INCLUDE_GENERATED_DECLARATIONS # include "ex_getln.c.generated.h" #endif @@ -304,32 +214,6 @@ static void init_incsearch_state(incsearch_state_T *s) save_viewstate(curwin, &s->old_viewstate); } -/// Completion for |:checkhealth| command. -/// -/// Given to ExpandGeneric() to obtain all available heathcheck names. -/// @param[in] idx Index of the healthcheck item. -/// @param[in] xp Not used. -static char *get_healthcheck_names(expand_T *xp, int idx) -{ - static Object names = OBJECT_INIT; - static unsigned last_gen = 0; - - if (last_gen != last_prompt_id || last_gen == 0) { - Array a = ARRAY_DICT_INIT; - Error err = ERROR_INIT; - Object res = nlua_exec(STATIC_CSTR_AS_STRING("return vim.health._complete()"), a, &err); - api_clear_error(&err); - api_free_object(names); - names = res; - last_gen = last_prompt_id; - } - - if (names.type == kObjectTypeArray && idx < (int)names.data.array.size) { - return names.data.array.items[idx].data.string.data; - } - return NULL; -} - // Return true when 'incsearch' highlighting is to be done. // Sets search_first_line and search_last_line to the address range. static bool do_incsearch_highlighting(int firstc, int *search_delim, incsearch_state_T *s, @@ -1137,41 +1021,24 @@ static int command_line_execute(VimState *state, int key) s->c = Ctrl_P; } - // Special translations for 'wildmenu' - if (s->did_wild_list && p_wmnu) { - if (s->c == K_LEFT) { - s->c = Ctrl_P; - } else if (s->c == K_RIGHT) { - s->c = Ctrl_N; - } + if (p_wmnu) { + s->c = wildmenu_translate_key(&ccline, s->c, &s->xpc, s->did_wild_list); } - if (compl_match_array || s->did_wild_list) { - if (s->c == Ctrl_E) { - s->res = nextwild(&s->xpc, WILD_CANCEL, WILD_NO_BEEP, - s->firstc != '@'); - } else if (s->c == Ctrl_Y) { - s->res = nextwild(&s->xpc, WILD_APPLY, WILD_NO_BEEP, - s->firstc != '@'); + + if (cmdline_pum_active() || s->did_wild_list) { + if (s->c == Ctrl_E || s->c == Ctrl_Y) { + const int wild_type = (s->c == Ctrl_E) ? WILD_CANCEL : WILD_APPLY; + s->res = nextwild(&s->xpc, wild_type, WILD_NO_BEEP, s->firstc != '@'); s->c = Ctrl_E; } } - // Hitting CR after "emenu Name.": complete submenu - if (s->xpc.xp_context == EXPAND_MENUNAMES && p_wmnu - && ccline.cmdpos > 1 - && ccline.cmdbuff[ccline.cmdpos - 1] == '.' - && ccline.cmdbuff[ccline.cmdpos - 2] != '\\' - && (s->c == '\n' || s->c == '\r' || s->c == K_KENTER)) { - s->c = K_DOWN; - } - // free expanded names when finished walking through matches if (!(s->c == p_wc && KeyTyped) && s->c != p_wcm && s->c != Ctrl_Z && s->c != Ctrl_N && s->c != Ctrl_P && s->c != Ctrl_A && s->c != Ctrl_L) { - if (compl_match_array) { - pum_undisplay(true); - XFREE_CLEAR(compl_match_array); + if (cmdline_pum_active()) { + cmdline_pum_remove(); } if (s->xpc.xp_numfiles != -1) { (void)ExpandOne(&s->xpc, NULL, NULL, 0, WILD_FREE); @@ -1181,174 +1048,11 @@ static int command_line_execute(VimState *state, int key) s->xpc.xp_context = EXPAND_NOTHING; } s->wim_index = 0; - if (p_wmnu && wild_menu_showing != 0) { - const bool skt = KeyTyped; - int old_RedrawingDisabled = RedrawingDisabled; - - if (ccline.input_fn) { - RedrawingDisabled = 0; - } - - if (wild_menu_showing == WM_SCROLLED) { - // Entered command line, move it up - cmdline_row--; - redrawcmd(); - wild_menu_showing = 0; - } else if (save_p_ls != -1) { - // restore 'laststatus' and 'winminheight' - p_ls = save_p_ls; - p_wmh = save_p_wmh; - last_status(false); - update_screen(VALID); // redraw the screen NOW - redrawcmd(); - save_p_ls = -1; - wild_menu_showing = 0; - // don't redraw statusline if WM_LIST is showing - } else if (wild_menu_showing != WM_LIST) { - win_redraw_last_status(topframe); - wild_menu_showing = 0; // must be before redraw_statuslines #8385 - redraw_statuslines(); - } else { - wild_menu_showing = 0; - } - KeyTyped = skt; - if (ccline.input_fn) { - RedrawingDisabled = old_RedrawingDisabled; - } - } - } - - // Special translations for 'wildmenu' - if (s->xpc.xp_context == EXPAND_MENUNAMES && p_wmnu) { - // Hitting <Down> after "emenu Name.": complete submenu - if (s->c == K_DOWN && ccline.cmdpos > 0 - && ccline.cmdbuff[ccline.cmdpos - 1] == '.') { - s->c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - } else if (s->c == K_UP) { - // Hitting <Up>: Remove one submenu name in front of the - // cursor - int found = false; - - int j = (int)((char_u *)s->xpc.xp_pattern - ccline.cmdbuff); - int i = 0; - while (--j > 0) { - // check for start of menu name - if (ccline.cmdbuff[j] == ' ' - && ccline.cmdbuff[j - 1] != '\\') { - i = j + 1; - break; - } - - // check for start of submenu name - if (ccline.cmdbuff[j] == '.' - && ccline.cmdbuff[j - 1] != '\\') { - if (found) { - i = j + 1; - break; - } else { - found = true; - } - } - } - if (i > 0) { - cmdline_del(i); - } - s->c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - s->xpc.xp_context = EXPAND_NOTHING; - } + wildmenu_cleanup(&ccline); } - if ((s->xpc.xp_context == EXPAND_FILES - || s->xpc.xp_context == EXPAND_DIRECTORIES - || s->xpc.xp_context == EXPAND_SHELLCMD) && p_wmnu) { - char_u upseg[5]; - upseg[0] = PATHSEP; - upseg[1] = '.'; - upseg[2] = '.'; - upseg[3] = PATHSEP; - upseg[4] = NUL; - - if (s->c == K_DOWN - && ccline.cmdpos > 0 - && ccline.cmdbuff[ccline.cmdpos - 1] == PATHSEP - && (ccline.cmdpos < 3 - || ccline.cmdbuff[ccline.cmdpos - 2] != '.' - || ccline.cmdbuff[ccline.cmdpos - 3] != '.')) { - // go down a directory - s->c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - } else if (STRNCMP(s->xpc.xp_pattern, upseg + 1, 3) == 0 - && s->c == K_DOWN) { - // If in a direct ancestor, strip off one ../ to go down - int found = false; - - int j = ccline.cmdpos; - int i = (int)((char_u *)s->xpc.xp_pattern - ccline.cmdbuff); - while (--j > i) { - j -= utf_head_off(ccline.cmdbuff, ccline.cmdbuff + j); - if (vim_ispathsep(ccline.cmdbuff[j])) { - found = true; - break; - } - } - if (found - && ccline.cmdbuff[j - 1] == '.' - && ccline.cmdbuff[j - 2] == '.' - && (vim_ispathsep(ccline.cmdbuff[j - 3]) || j == i + 2)) { - cmdline_del(j - 2); - s->c = (int)p_wc; - KeyTyped = true; // in case the key was mapped - } - } else if (s->c == K_UP) { - // go up a directory - int found = false; - - int j = ccline.cmdpos - 1; - int i = (int)((char_u *)s->xpc.xp_pattern - ccline.cmdbuff); - while (--j > i) { - j -= utf_head_off(ccline.cmdbuff, ccline.cmdbuff + j); - if (vim_ispathsep(ccline.cmdbuff[j]) -#ifdef BACKSLASH_IN_FILENAME - && vim_strchr((const char_u *)" *?[{`$%#", ccline.cmdbuff[j + 1]) - == NULL -#endif - ) { - if (found) { - i = j + 1; - break; - } else { - found = true; - } - } - } - - if (!found) { - j = i; - } else if (STRNCMP(ccline.cmdbuff + j, upseg, 4) == 0) { - j += 4; - } else if (STRNCMP(ccline.cmdbuff + j, upseg + 1, 3) == 0 - && j == i) { - j += 3; - } else { - j = 0; - } - - if (j > 0) { - // TODO(tarruda): this is only for DOS/Unix systems - need to put in - // machine-specific stuff here and in upseg init - cmdline_del(j); - put_on_cmdline(upseg + 1, 3, false); - } else if (ccline.cmdpos > i) { - cmdline_del(i); - } - - // Now complete in the new directory. Set KeyTyped in case the - // Up key came from a mapping. - s->c = (int)p_wc; - KeyTyped = true; - } + if (p_wmnu) { + s->c = wildmenu_process_key(&ccline, s->c, &s->xpc); } // CTRL-\ CTRL-N goes to Normal mode, CTRL-\ e prompts for an expression. @@ -1573,8 +1277,8 @@ static int command_line_execute(VimState *state, int key) // <S-Tab> goes to last match, in a clumsy way if (s->c == K_S_TAB && KeyTyped) { if (nextwild(&s->xpc, WILD_EXPAND_KEEP, 0, s->firstc != '@') == OK) { - showmatches(&s->xpc, p_wmnu - && ((wim_flags[s->wim_index] & WIM_LIST) == 0)); + // Trigger the popup menu when wildoptions=pum + showmatches(&s->xpc, p_wmnu && ((wim_flags[s->wim_index] & WIM_LIST) == 0)); nextwild(&s->xpc, WILD_PREV, 0, s->firstc != '@'); nextwild(&s->xpc, WILD_PREV, 0, s->firstc != '@'); return command_line_changed(s); @@ -2097,6 +1801,10 @@ static int command_line_handle_key(CommandLineState *s) if (nextwild(&s->xpc, WILD_ALL, 0, s->firstc != '@') == FAIL) { break; } + if (cmdline_pum_active()) { + cmdline_pum_cleanup(&ccline); + s->xpc.xp_context = EXPAND_NOTHING; + } return command_line_changed(s); case Ctrl_L: @@ -2895,7 +2603,7 @@ static int cmd_startcol(void) } /// Compute the column position for a byte position on the command line. -static int cmd_screencol(int bytepos) +int cmd_screencol(int bytepos) { int m; // maximum column @@ -2982,10 +2690,8 @@ static void alloc_cmdbuff(int len) ccline.cmdbufflen = len; } -/* - * Re-allocate the command line to length len + something extra. - */ -static void realloc_cmdbuff(int len) +/// Re-allocate the command line to length len + something extra. +void realloc_cmdbuff(int len) { if (len < ccline.cmdbufflen) { return; // no need to resize @@ -3742,7 +3448,7 @@ void put_on_cmdline(char_u *str, int len, int redraw) /// Save ccline, because obtaining the "=" register may execute "normal :cmd" /// and overwrite it. -static void save_cmdline(struct cmdline_info *ccp) +static void save_cmdline(CmdlineInfo *ccp) { *ccp = ccline; CLEAR_FIELD(ccline); @@ -3751,7 +3457,7 @@ static void save_cmdline(struct cmdline_info *ccp) } /// Restore ccline after it has been saved with save_cmdline(). -static void restore_cmdline(struct cmdline_info *ccp) +static void restore_cmdline(CmdlineInfo *ccp) FUNC_ATTR_NONNULL_ALL { ccline = *ccp; @@ -3860,16 +3566,6 @@ void cmdline_paste_str(char_u *s, int literally) } } -/// Delete characters on the command line, from "from" to the current position. -static void cmdline_del(int from) -{ - assert(ccline.cmdpos <= ccline.cmdlen); - memmove(ccline.cmdbuff + from, ccline.cmdbuff + ccline.cmdpos, - (size_t)ccline.cmdlen - (size_t)ccline.cmdpos + 1); - ccline.cmdlen -= ccline.cmdpos - from; - ccline.cmdpos = from; -} - // This function is called when the screen size changes and with incremental // search and in other situations where the command line may have been // overwritten. @@ -3977,7 +3673,7 @@ void compute_cmdrow(void) lines_left = cmdline_row; } -static void cursorcmd(void) +void cursorcmd(void) { if (cmd_silent) { return; @@ -4064,462 +3760,6 @@ static int ccheck_abbr(int c) return check_abbr(c, ccline.cmdbuff, ccline.cmdpos, spos); } -static int sort_func_compare(const void *s1, const void *s2) -{ - char_u *p1 = *(char_u **)s1; - char_u *p2 = *(char_u **)s2; - - if (*p1 != '<' && *p2 == '<') { - return -1; - } - if (*p1 == '<' && *p2 != '<') { - return 1; - } - return STRCMP(p1, p2); -} - -/// Return FAIL if this is not an appropriate context in which to do -/// completion of anything, return OK if it is (even if there are no matches). -/// For the caller, this means that the character is just passed through like a -/// normal character (instead of being expanded). This allows :s/^I^D etc. -/// -/// @param options extra options for ExpandOne() -/// @param escape if TRUE, escape the returned matches -static int nextwild(expand_T *xp, int type, int options, int escape) -{ - int i, j; - char_u *p1; - char_u *p2; - int difflen; - - if (xp->xp_numfiles == -1) { - set_expand_context(xp); - cmd_showtail = expand_showtail(xp); - } - - if (xp->xp_context == EXPAND_UNSUCCESSFUL) { - beep_flush(); - return OK; // Something illegal on command line - } - if (xp->xp_context == EXPAND_NOTHING) { - // Caller can use the character as a normal char instead - return FAIL; - } - - if (!(ui_has(kUICmdline) || ui_has(kUIWildmenu))) { - msg_puts("..."); // show that we are busy - ui_flush(); - } - - i = (int)((char_u *)xp->xp_pattern - ccline.cmdbuff); - assert(ccline.cmdpos >= i); - xp->xp_pattern_len = (size_t)ccline.cmdpos - (size_t)i; - - if (type == WILD_NEXT || type == WILD_PREV) { - // Get next/previous match for a previous expanded pattern. - p2 = ExpandOne(xp, NULL, NULL, 0, type); - } else { - // Translate string into pattern and expand it. - p1 = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); - const int use_options = ( - options - | WILD_HOME_REPLACE - | WILD_ADD_SLASH - | WILD_SILENT - | (escape ? WILD_ESCAPE : 0) - | (p_wic ? WILD_ICASE : 0)); - p2 = ExpandOne(xp, p1, vim_strnsave(&ccline.cmdbuff[i], xp->xp_pattern_len), - use_options, type); - xfree(p1); - - // xp->xp_pattern might have been modified by ExpandOne (for example, - // in lua completion), so recompute the pattern index and length - i = (int)((char_u *)xp->xp_pattern - ccline.cmdbuff); - xp->xp_pattern_len = (size_t)ccline.cmdpos - (size_t)i; - - // Longest match: make sure it is not shorter, happens with :help. - if (p2 != NULL && type == WILD_LONGEST) { - for (j = 0; (size_t)j < xp->xp_pattern_len; j++) { - if (ccline.cmdbuff[i + j] == '*' - || ccline.cmdbuff[i + j] == '?') { - break; - } - } - if ((int)STRLEN(p2) < j) { - XFREE_CLEAR(p2); - } - } - } - - if (p2 != NULL && !got_int) { - difflen = (int)STRLEN(p2) - (int)(xp->xp_pattern_len); - if (ccline.cmdlen + difflen + 4 > ccline.cmdbufflen) { - realloc_cmdbuff(ccline.cmdlen + difflen + 4); - xp->xp_pattern = (char *)ccline.cmdbuff + i; - } - assert(ccline.cmdpos <= ccline.cmdlen); - memmove(&ccline.cmdbuff[ccline.cmdpos + difflen], - &ccline.cmdbuff[ccline.cmdpos], - (size_t)ccline.cmdlen - (size_t)ccline.cmdpos + 1); - memmove(&ccline.cmdbuff[i], p2, STRLEN(p2)); - ccline.cmdlen += difflen; - ccline.cmdpos += difflen; - } - xfree(p2); - - redrawcmd(); - cursorcmd(); - - /* When expanding a ":map" command and no matches are found, assume that - * the key is supposed to be inserted literally */ - if (xp->xp_context == EXPAND_MAPPINGS && p2 == NULL) { - return FAIL; - } - - if (xp->xp_numfiles <= 0 && p2 == NULL) { - beep_flush(); - } else if (xp->xp_numfiles == 1) { - // free expanded pattern - (void)ExpandOne(xp, NULL, NULL, 0, WILD_FREE); - } - - return OK; -} - -/// Do wildcard expansion on the string 'str'. -/// Chars that should not be expanded must be preceded with a backslash. -/// Return a pointer to allocated memory containing the new string. -/// Return NULL for failure. -/// -/// "orig" is the originally expanded string, copied to allocated memory. It -/// should either be kept in orig_save or freed. When "mode" is WILD_NEXT or -/// WILD_PREV "orig" should be NULL. -/// -/// Results are cached in xp->xp_files and xp->xp_numfiles, except when "mode" -/// is WILD_EXPAND_FREE or WILD_ALL. -/// -/// mode = WILD_FREE: just free previously expanded matches -/// mode = WILD_EXPAND_FREE: normal expansion, do not keep matches -/// mode = WILD_EXPAND_KEEP: normal expansion, keep matches -/// mode = WILD_NEXT: use next match in multiple match, wrap to first -/// mode = WILD_PREV: use previous match in multiple match, wrap to first -/// mode = WILD_ALL: return all matches concatenated -/// mode = WILD_LONGEST: return longest matched part -/// mode = WILD_ALL_KEEP: get all matches, keep matches -/// -/// options = WILD_LIST_NOTFOUND: list entries without a match -/// options = WILD_HOME_REPLACE: do home_replace() for buffer names -/// options = WILD_USE_NL: Use '\n' for WILD_ALL -/// options = WILD_NO_BEEP: Don't beep for multiple matches -/// options = WILD_ADD_SLASH: add a slash after directory names -/// options = WILD_KEEP_ALL: don't remove 'wildignore' entries -/// options = WILD_SILENT: don't print warning messages -/// options = WILD_ESCAPE: put backslash before special chars -/// options = WILD_ICASE: ignore case for files -/// -/// The variables xp->xp_context and xp->xp_backslash must have been set! -/// -/// @param orig allocated copy of original of expanded string -char_u *ExpandOne(expand_T *xp, char_u *str, char_u *orig, int options, int mode) -{ - char_u *ss = NULL; - static int findex; - static char_u *orig_save = NULL; // kept value of orig - int orig_saved = FALSE; - int i; - int non_suf_match; // number without matching suffix - - /* - * first handle the case of using an old match - */ - if (mode == WILD_NEXT || mode == WILD_PREV) { - if (xp->xp_numfiles > 0) { - if (mode == WILD_PREV) { - if (findex == -1) { - findex = xp->xp_numfiles; - } - findex--; - } else { // mode == WILD_NEXT - findex++; - } - - /* - * When wrapping around, return the original string, set findex to - * -1. - */ - if (findex < 0) { - if (orig_save == NULL) { - findex = xp->xp_numfiles - 1; - } else { - findex = -1; - } - } - if (findex >= xp->xp_numfiles) { - if (orig_save == NULL) { - findex = 0; - } else { - findex = -1; - } - } - if (compl_match_array) { - compl_selected = findex; - cmdline_pum_display(false); - } else if (p_wmnu) { - redraw_wildmenu(xp, xp->xp_numfiles, xp->xp_files, findex, cmd_showtail); - } - if (findex == -1) { - return vim_strsave(orig_save); - } - return vim_strsave((char_u *)xp->xp_files[findex]); - } else { - return NULL; - } - } - - if (mode == WILD_CANCEL) { - ss = vim_strsave(orig_save ? orig_save : (char_u *)""); - } else if (mode == WILD_APPLY) { - ss = vim_strsave(findex == -1 ? (orig_save ? orig_save : (char_u *)"") : - (char_u *)xp->xp_files[findex]); - } - - // free old names - if (xp->xp_numfiles != -1 && mode != WILD_ALL && mode != WILD_LONGEST) { - FreeWild(xp->xp_numfiles, xp->xp_files); - xp->xp_numfiles = -1; - XFREE_CLEAR(orig_save); - } - findex = 0; - - if (mode == WILD_FREE) { // only release file name - return NULL; - } - - if (xp->xp_numfiles == -1 && mode != WILD_APPLY && mode != WILD_CANCEL) { - xfree(orig_save); - orig_save = orig; - orig_saved = TRUE; - - /* - * Do the expansion. - */ - if (ExpandFromContext(xp, str, &xp->xp_numfiles, &xp->xp_files, options) == FAIL) { -#ifdef FNAME_ILLEGAL - /* Illegal file name has been silently skipped. But when there - * are wildcards, the real problem is that there was no match, - * causing the pattern to be added, which has illegal characters. - */ - if (!(options & WILD_SILENT) && (options & WILD_LIST_NOTFOUND)) { - semsg(_(e_nomatch2), str); - } -#endif - } else if (xp->xp_numfiles == 0) { - if (!(options & WILD_SILENT)) { - semsg(_(e_nomatch2), str); - } - } else { - // Escape the matches for use on the command line. - ExpandEscape(xp, str, xp->xp_numfiles, xp->xp_files, options); - - /* - * Check for matching suffixes in file names. - */ - if (mode != WILD_ALL && mode != WILD_ALL_KEEP - && mode != WILD_LONGEST) { - if (xp->xp_numfiles) { - non_suf_match = xp->xp_numfiles; - } else { - non_suf_match = 1; - } - if ((xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_DIRECTORIES) - && xp->xp_numfiles > 1) { - /* - * More than one match; check suffix. - * The files will have been sorted on matching suffix in - * expand_wildcards, only need to check the first two. - */ - non_suf_match = 0; - for (i = 0; i < 2; i++) { - if (match_suffix((char_u *)xp->xp_files[i])) { - non_suf_match++; - } - } - } - if (non_suf_match != 1) { - /* Can we ever get here unless it's while expanding - * interactively? If not, we can get rid of this all - * together. Don't really want to wait for this message - * (and possibly have to hit return to continue!). - */ - if (!(options & WILD_SILENT)) { - emsg(_(e_toomany)); - } else if (!(options & WILD_NO_BEEP)) { - beep_flush(); - } - } - if (!(non_suf_match != 1 && mode == WILD_EXPAND_FREE)) { - ss = vim_strsave((char_u *)xp->xp_files[0]); - } - } - } - } - - // Find longest common part - if (mode == WILD_LONGEST && xp->xp_numfiles > 0) { - size_t len = 0; - - for (size_t mb_len; xp->xp_files[0][len]; len += mb_len) { - mb_len = (size_t)utfc_ptr2len(&xp->xp_files[0][len]); - int c0 = utf_ptr2char(&xp->xp_files[0][len]); - for (i = 1; i < xp->xp_numfiles; i++) { - int ci = utf_ptr2char(&xp->xp_files[i][len]); - - if (p_fic && (xp->xp_context == EXPAND_DIRECTORIES - || xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_SHELLCMD - || xp->xp_context == EXPAND_BUFFERS)) { - if (mb_tolower(c0) != mb_tolower(ci)) { - break; - } - } else if (c0 != ci) { - break; - } - } - if (i < xp->xp_numfiles) { - if (!(options & WILD_NO_BEEP)) { - vim_beep(BO_WILD); - } - break; - } - } - - ss = (char_u *)xstrndup(xp->xp_files[0], len); - findex = -1; // next p_wc gets first one - } - - // Concatenate all matching names - // TODO(philix): use xstpcpy instead of strcat in a loop (ExpandOne) - if (mode == WILD_ALL && xp->xp_numfiles > 0) { - size_t len = 0; - for (i = 0; i < xp->xp_numfiles; ++i) { - len += STRLEN(xp->xp_files[i]) + 1; - } - ss = xmalloc(len); - *ss = NUL; - for (i = 0; i < xp->xp_numfiles; ++i) { - STRCAT(ss, xp->xp_files[i]); - if (i != xp->xp_numfiles - 1) { - STRCAT(ss, (options & WILD_USE_NL) ? "\n" : " "); - } - } - } - - if (mode == WILD_EXPAND_FREE || mode == WILD_ALL) { - ExpandCleanup(xp); - } - - // Free "orig" if it wasn't stored in "orig_save". - if (!orig_saved) { - xfree(orig); - } - - return ss; -} - -/* - * Prepare an expand structure for use. - */ -void ExpandInit(expand_T *xp) - FUNC_ATTR_NONNULL_ALL -{ - CLEAR_POINTER(xp); - xp->xp_backslash = XP_BS_NONE; - xp->xp_numfiles = -1; -} - -/* - * Cleanup an expand structure after use. - */ -void ExpandCleanup(expand_T *xp) -{ - if (xp->xp_numfiles >= 0) { - FreeWild(xp->xp_numfiles, xp->xp_files); - xp->xp_numfiles = -1; - } -} - -void ExpandEscape(expand_T *xp, char_u *str, int numfiles, char **files, int options) -{ - int i; - char_u *p; - const int vse_what = xp->xp_context == EXPAND_BUFFERS ? VSE_BUFFER : VSE_NONE; - - /* - * May change home directory back to "~" - */ - if (options & WILD_HOME_REPLACE) { - tilde_replace(str, numfiles, files); - } - - if (options & WILD_ESCAPE) { - if (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_FILES_IN_PATH - || xp->xp_context == EXPAND_SHELLCMD - || xp->xp_context == EXPAND_BUFFERS - || xp->xp_context == EXPAND_DIRECTORIES) { - /* - * Insert a backslash into a file name before a space, \, %, # - * and wildmatch characters, except '~'. - */ - for (i = 0; i < numfiles; ++i) { - // for ":set path=" we need to escape spaces twice - if (xp->xp_backslash == XP_BS_THREE) { - p = vim_strsave_escaped((char_u *)files[i], (char_u *)" "); - xfree(files[i]); - files[i] = (char *)p; -#if defined(BACKSLASH_IN_FILENAME) - p = vim_strsave_escaped(files[i], (char_u *)" "); - xfree(files[i]); - files[i] = p; -#endif - } -#ifdef BACKSLASH_IN_FILENAME - p = (char_u *)vim_strsave_fnameescape((const char *)files[i], vse_what); -#else - p = (char_u *)vim_strsave_fnameescape((const char *)files[i], - xp->xp_shell ? VSE_SHELL : vse_what); -#endif - xfree(files[i]); - files[i] = (char *)p; - - /* If 'str' starts with "\~", replace "~" at start of - * files[i] with "\~". */ - if (str[0] == '\\' && str[1] == '~' && files[i][0] == '~') { - escape_fname(&files[i]); - } - } - xp->xp_backslash = XP_BS_NONE; - - /* If the first file starts with a '+' escape it. Otherwise it - * could be seen as "+cmd". */ - if (*files[0] == '+') { - escape_fname(&files[0]); - } - } else if (xp->xp_context == EXPAND_TAGS) { - /* - * Insert a backslash before characters in a tag name that - * would terminate the ":tag" command. - */ - for (i = 0; i < numfiles; i++) { - p = vim_strsave_escaped((char_u *)files[i], (char_u *)"\\|\""); - xfree(files[i]); - files[i] = (char *)p; - } - } - } -} - /// Escape special characters in "fname", depending on "what": /// /// @param[in] fname File name to escape. @@ -4576,10 +3816,8 @@ char *vim_strsave_fnameescape(const char *const fname, const int what) return p; } -/* - * Put a backslash before the file name in "pp", which is in allocated memory. - */ -static void escape_fname(char **pp) +/// Put a backslash before the file name in "pp", which is in allocated memory. +void escape_fname(char **pp) { char_u *p = xmalloc(STRLEN(*pp) + 2); p[0] = '\\'; @@ -4603,1168 +3841,20 @@ void tilde_replace(char_u *orig_pat, int num_files, char **files) } } -void cmdline_pum_display(bool changed_array) +/// Get a pointer to the current command line info. +CmdlineInfo *get_cmdline_info(void) { - pum_display(compl_match_array, compl_match_arraysize, compl_selected, - changed_array, compl_startcol); + return &ccline; } -/* - * Show all matches for completion on the command line. - * Returns EXPAND_NOTHING when the character that triggered expansion should - * be inserted like a normal character. - */ -static int showmatches(expand_T *xp, int wildmenu) +unsigned get_cmdline_last_prompt_id(void) { -#define L_SHOWFILE(m) (showtail \ - ? sm_gettail(files_found[m], false) : files_found[m]) - int num_files; - char **files_found; - int i, j, k; - int maxlen; - int lines; - int columns; - char_u *p; - int lastlen; - int attr; - int showtail; - - if (xp->xp_numfiles == -1) { - set_expand_context(xp); - i = expand_cmdline(xp, ccline.cmdbuff, ccline.cmdpos, - &num_files, &files_found); - showtail = expand_showtail(xp); - if (i != EXPAND_OK) { - return i; - } - } else { - num_files = xp->xp_numfiles; - files_found = xp->xp_files; - showtail = cmd_showtail; - } - - bool compl_use_pum = (ui_has(kUICmdline) - ? ui_has(kUIPopupmenu) - : wildmenu && (wop_flags & WOP_PUM)) - || ui_has(kUIWildmenu); - - if (compl_use_pum) { - assert(num_files >= 0); - compl_match_arraysize = num_files; - compl_match_array = xcalloc((size_t)compl_match_arraysize, - sizeof(pumitem_T)); - for (i = 0; i < num_files; i++) { - compl_match_array[i].pum_text = (char_u *)L_SHOWFILE(i); - } - char_u *endpos = (char_u *)(showtail ? sm_gettail(xp->xp_pattern, true) : xp->xp_pattern); - if (ui_has(kUICmdline)) { - compl_startcol = (int)(endpos - ccline.cmdbuff); - } else { - compl_startcol = cmd_screencol((int)(endpos - ccline.cmdbuff)); - } - compl_selected = -1; - cmdline_pum_display(true); - return EXPAND_OK; - } - - if (!wildmenu) { - msg_didany = false; // lines_left will be set - msg_start(); // prepare for paging - msg_putchar('\n'); - ui_flush(); - cmdline_row = msg_row; - msg_didany = false; // lines_left will be set again - msg_start(); // prepare for paging - } - - if (got_int) { - got_int = false; // only int. the completion, not the cmd line - } else if (wildmenu) { - redraw_wildmenu(xp, num_files, files_found, -1, showtail); - } else { - // find the length of the longest file name - maxlen = 0; - for (i = 0; i < num_files; ++i) { - if (!showtail && (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_SHELLCMD - || xp->xp_context == EXPAND_BUFFERS)) { - home_replace(NULL, files_found[i], (char *)NameBuff, MAXPATHL, true); - j = vim_strsize((char *)NameBuff); - } else { - j = vim_strsize(L_SHOWFILE(i)); - } - if (j > maxlen) { - maxlen = j; - } - } - - if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - lines = num_files; - } else { - // compute the number of columns and lines for the listing - maxlen += 2; // two spaces between file names - columns = (Columns + 2) / maxlen; - if (columns < 1) { - columns = 1; - } - lines = (num_files + columns - 1) / columns; - } - - attr = HL_ATTR(HLF_D); // find out highlighting for directories - - if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - msg_puts_attr(_("tagname"), HL_ATTR(HLF_T)); - msg_clr_eos(); - msg_advance(maxlen - 3); - msg_puts_attr(_(" kind file\n"), HL_ATTR(HLF_T)); - } - - // list the files line by line - for (i = 0; i < lines; ++i) { - lastlen = 999; - for (k = i; k < num_files; k += lines) { - if (xp->xp_context == EXPAND_TAGS_LISTFILES) { - msg_outtrans_attr((char_u *)files_found[k], HL_ATTR(HLF_D)); - p = (char_u *)files_found[k] + STRLEN(files_found[k]) + 1; - msg_advance(maxlen + 1); - msg_puts((const char *)p); - msg_advance(maxlen + 3); - msg_outtrans_long_attr(p + 2, HL_ATTR(HLF_D)); - break; - } - for (j = maxlen - lastlen; --j >= 0;) { - msg_putchar(' '); - } - if (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_SHELLCMD - || xp->xp_context == EXPAND_BUFFERS) { - // highlight directories - if (xp->xp_numfiles != -1) { - // Expansion was done before and special characters - // were escaped, need to halve backslashes. Also - // $HOME has been replaced with ~/. - char_u *exp_path = expand_env_save_opt((char_u *)files_found[k], true); - char_u *path = exp_path != NULL ? exp_path : (char_u *)files_found[k]; - char_u *halved_slash = backslash_halve_save(path); - j = os_isdir(halved_slash); - xfree(exp_path); - if (halved_slash != path) { - xfree(halved_slash); - } - } else { - // Expansion was done here, file names are literal. - j = os_isdir((char_u *)files_found[k]); - } - if (showtail) { - p = (char_u *)L_SHOWFILE(k); - } else { - home_replace(NULL, files_found[k], (char *)NameBuff, MAXPATHL, true); - p = NameBuff; - } - } else { - j = false; - p = (char_u *)L_SHOWFILE(k); - } - lastlen = msg_outtrans_attr(p, j ? attr : 0); - } - if (msg_col > 0) { // when not wrapped around - msg_clr_eos(); - msg_putchar('\n'); - } - ui_flush(); // show one line at a time - if (got_int) { - got_int = FALSE; - break; - } - } - - /* - * we redraw the command below the lines that we have just listed - * This is a bit tricky, but it saves a lot of screen updating. - */ - cmdline_row = msg_row; // will put it back later - } - - if (xp->xp_numfiles == -1) { - FreeWild(num_files, files_found); - } - - return EXPAND_OK; -} - -/// Private path_tail for showmatches() (and redraw_wildmenu()): -/// Find tail of file name path, but ignore trailing "/". -char *sm_gettail(char *s, bool eager) -{ - char_u *p; - char_u *t = (char_u *)s; - int had_sep = false; - - for (p = (char_u *)s; *p != NUL;) { - if (vim_ispathsep(*p) -#ifdef BACKSLASH_IN_FILENAME - && !rem_backslash(p) -#endif - ) { - if (eager) { - t = p + 1; - } else { - had_sep = true; - } - } else if (had_sep) { - t = p; - had_sep = FALSE; - } - MB_PTR_ADV(p); - } - return (char *)t; -} - -/* - * Return TRUE if we only need to show the tail of completion matches. - * When not completing file names or there is a wildcard in the path FALSE is - * returned. - */ -static int expand_showtail(expand_T *xp) -{ - char_u *s; - char_u *end; - - // When not completing file names a "/" may mean something different. - if (xp->xp_context != EXPAND_FILES - && xp->xp_context != EXPAND_SHELLCMD - && xp->xp_context != EXPAND_DIRECTORIES) { - return FALSE; - } - - end = (char_u *)path_tail(xp->xp_pattern); - if (end == (char_u *)xp->xp_pattern) { // there is no path separator - return false; - } - - for (s = (char_u *)xp->xp_pattern; s < end; s++) { - // Skip escaped wildcards. Only when the backslash is not a path - // separator, on DOS the '*' "path\*\file" must not be skipped. - if (rem_backslash(s)) { - s++; - } else if (vim_strchr("*?[", *s) != NULL) { - return false; - } - } - return TRUE; -} - -/// Prepare a string for expansion. -/// -/// When expanding file names: The string will be used with expand_wildcards(). -/// Copy "fname[len]" into allocated memory and add a '*' at the end. -/// When expanding other names: The string will be used with regcomp(). Copy -/// the name into allocated memory and prepend "^". -/// -/// @param context EXPAND_FILES etc. -char_u *addstar(char_u *fname, size_t len, int context) - FUNC_ATTR_NONNULL_RET -{ - char_u *retval; - size_t i, j; - size_t new_len; - char_u *tail; - int ends_in_star; - - if (context != EXPAND_FILES - && context != EXPAND_FILES_IN_PATH - && context != EXPAND_SHELLCMD - && context != EXPAND_DIRECTORIES) { - /* - * Matching will be done internally (on something other than files). - * So we convert the file-matching-type wildcards into our kind for - * use with vim_regcomp(). First work out how long it will be: - */ - - // For help tags the translation is done in find_help_tags(). - // For a tag pattern starting with "/" no translation is needed. - if (context == EXPAND_HELP - || context == EXPAND_CHECKHEALTH - || context == EXPAND_COLORS - || context == EXPAND_COMPILER - || context == EXPAND_OWNSYNTAX - || context == EXPAND_FILETYPE - || context == EXPAND_PACKADD - || ((context == EXPAND_TAGS_LISTFILES || context == EXPAND_TAGS) - && fname[0] == '/')) { - retval = vim_strnsave(fname, len); - } else { - new_len = len + 2; // +2 for '^' at start, NUL at end - for (i = 0; i < len; i++) { - if (fname[i] == '*' || fname[i] == '~') { - new_len++; /* '*' needs to be replaced by ".*" - '~' needs to be replaced by "\~" */ - } - // Buffer names are like file names. "." should be literal - if (context == EXPAND_BUFFERS && fname[i] == '.') { - new_len++; // "." becomes "\." - } - /* Custom expansion takes care of special things, match - * backslashes literally (perhaps also for other types?) */ - if ((context == EXPAND_USER_DEFINED - || context == EXPAND_USER_LIST) && fname[i] == '\\') { - new_len++; // '\' becomes "\\" - } - } - retval = xmalloc(new_len); - { - retval[0] = '^'; - j = 1; - for (i = 0; i < len; i++, j++) { - /* Skip backslash. But why? At least keep it for custom - * expansion. */ - if (context != EXPAND_USER_DEFINED - && context != EXPAND_USER_LIST - && fname[i] == '\\' - && ++i == len) { - break; - } - - switch (fname[i]) { - case '*': - retval[j++] = '.'; - break; - case '~': - retval[j++] = '\\'; - break; - case '?': - retval[j] = '.'; - continue; - case '.': - if (context == EXPAND_BUFFERS) { - retval[j++] = '\\'; - } - break; - case '\\': - if (context == EXPAND_USER_DEFINED - || context == EXPAND_USER_LIST) { - retval[j++] = '\\'; - } - break; - } - retval[j] = fname[i]; - } - retval[j] = NUL; - } - } - } else { - retval = xmalloc(len + 4); - STRLCPY(retval, fname, len + 1); - - /* - * Don't add a star to *, ~, ~user, $var or `cmd`. - * * would become **, which walks the whole tree. - * ~ would be at the start of the file name, but not the tail. - * $ could be anywhere in the tail. - * ` could be anywhere in the file name. - * When the name ends in '$' don't add a star, remove the '$'. - */ - tail = (char_u *)path_tail((char *)retval); - ends_in_star = (len > 0 && retval[len - 1] == '*'); -#ifndef BACKSLASH_IN_FILENAME - for (ssize_t k = (ssize_t)len - 2; k >= 0; k--) { - if (retval[k] != '\\') { - break; - } - ends_in_star = !ends_in_star; - } -#endif - if ((*retval != '~' || tail != retval) - && !ends_in_star - && vim_strchr((char *)tail, '$') == NULL - && vim_strchr((char *)retval, '`') == NULL) { - retval[len++] = '*'; - } else if (len > 0 && retval[len - 1] == '$') { - len--; - } - retval[len] = NUL; - } - return retval; -} - -/* - * Must parse the command line so far to work out what context we are in. - * Completion can then be done based on that context. - * This routine sets the variables: - * xp->xp_pattern The start of the pattern to be expanded within - * the command line (ends at the cursor). - * xp->xp_context The type of thing to expand. Will be one of: - * - * EXPAND_UNSUCCESSFUL Used sometimes when there is something illegal on - * the command line, like an unknown command. Caller - * should beep. - * EXPAND_NOTHING Unrecognised context for completion, use char like - * a normal char, rather than for completion. eg - * :s/^I/ - * EXPAND_COMMANDS Cursor is still touching the command, so complete - * it. - * EXPAND_BUFFERS Complete file names for :buf and :sbuf commands. - * EXPAND_FILES After command with EX_XFILE set, or after setting - * with P_EXPAND set. eg :e ^I, :w>>^I - * EXPAND_DIRECTORIES In some cases this is used instead of the latter - * when we know only directories are of interest. eg - * :set dir=^I - * EXPAND_SHELLCMD After ":!cmd", ":r !cmd" or ":w !cmd". - * EXPAND_SETTINGS Complete variable names. eg :set d^I - * EXPAND_BOOL_SETTINGS Complete boolean variables only, eg :set no^I - * EXPAND_TAGS Complete tags from the files in p_tags. eg :ta a^I - * EXPAND_TAGS_LISTFILES As above, but list filenames on ^D, after :tselect - * EXPAND_HELP Complete tags from the file 'helpfile'/tags - * EXPAND_EVENTS Complete event names - * EXPAND_SYNTAX Complete :syntax command arguments - * EXPAND_HIGHLIGHT Complete highlight (syntax) group names - * EXPAND_AUGROUP Complete autocommand group names - * EXPAND_USER_VARS Complete user defined variable names, eg :unlet a^I - * EXPAND_MAPPINGS Complete mapping and abbreviation names, - * eg :unmap a^I , :cunab x^I - * EXPAND_FUNCTIONS Complete internal or user defined function names, - * eg :call sub^I - * EXPAND_USER_FUNC Complete user defined function names, eg :delf F^I - * EXPAND_EXPRESSION Complete internal or user defined function/variable - * names in expressions, eg :while s^I - * EXPAND_ENV_VARS Complete environment variable names - * EXPAND_USER Complete user names - */ -void set_expand_context(expand_T *xp) -{ - // only expansion for ':', '>' and '=' command-lines - if (ccline.cmdfirstc != ':' - && ccline.cmdfirstc != '>' && ccline.cmdfirstc != '=' - && !ccline.input_fn) { - xp->xp_context = EXPAND_NOTHING; - return; - } - set_cmd_context(xp, ccline.cmdbuff, ccline.cmdlen, ccline.cmdpos, true); -} - -/// @param str start of command line -/// @param len length of command line (excl. NUL) -/// @param col position of cursor -/// @param use_ccline use ccline for info -void set_cmd_context(expand_T *xp, char_u *str, int len, int col, int use_ccline) -{ - char_u old_char = NUL; - - /* - * Avoid a UMR warning from Purify, only save the character if it has been - * written before. - */ - if (col < len) { - old_char = str[col]; - } - str[col] = NUL; - const char *nextcomm = (const char *)str; - - if (use_ccline && ccline.cmdfirstc == '=') { - // pass CMD_SIZE because there is no real command - set_context_for_expression(xp, (char *)str, CMD_SIZE); - } else if (use_ccline && ccline.input_fn) { - xp->xp_context = ccline.xp_context; - xp->xp_pattern = (char *)ccline.cmdbuff; - xp->xp_arg = (char *)ccline.xp_arg; - } else { - while (nextcomm != NULL) { - nextcomm = set_one_cmd_context(xp, nextcomm); - } - } - - /* Store the string here so that call_user_expand_func() can get to them - * easily. */ - xp->xp_line = (char *)str; - xp->xp_col = col; - - str[col] = old_char; -} - -/// Expand the command line "str" from context "xp". -/// "xp" must have been set by set_cmd_context(). -/// xp->xp_pattern points into "str", to where the text that is to be expanded -/// starts. -/// Returns EXPAND_UNSUCCESSFUL when there is something illegal before the -/// cursor. -/// Returns EXPAND_NOTHING when there is nothing to expand, might insert the -/// key that triggered expansion literally. -/// Returns EXPAND_OK otherwise. -/// -/// @param str start of command line -/// @param col position of cursor -/// @param matchcount return: nr of matches -/// @param matches return: array of pointers to matches -int expand_cmdline(expand_T *xp, char_u *str, int col, int *matchcount, char ***matches) -{ - char_u *file_str = NULL; - int options = WILD_ADD_SLASH|WILD_SILENT; - - if (xp->xp_context == EXPAND_UNSUCCESSFUL) { - beep_flush(); - return EXPAND_UNSUCCESSFUL; // Something illegal on command line - } - if (xp->xp_context == EXPAND_NOTHING) { - // Caller can use the character as a normal char instead - return EXPAND_NOTHING; - } - - // add star to file name, or convert to regexp if not exp. files. - assert((str + col) - (char_u *)xp->xp_pattern >= 0); - xp->xp_pattern_len = (size_t)((str + col) - (char_u *)xp->xp_pattern); - file_str = addstar((char_u *)xp->xp_pattern, xp->xp_pattern_len, xp->xp_context); - - if (p_wic) { - options += WILD_ICASE; - } - - // find all files that match the description - if (ExpandFromContext(xp, file_str, matchcount, matches, options) == FAIL) { - *matchcount = 0; - *matches = NULL; - } - xfree(file_str); - - return EXPAND_OK; -} - -typedef char *(*ExpandFunc)(expand_T *, int); - -/// Do the expansion based on xp->xp_context and "pat". -/// -/// @param options WILD_ flags -static int ExpandFromContext(expand_T *xp, char_u *pat, int *num_file, char ***file, int options) -{ - regmatch_T regmatch; - int ret; - int flags; - - flags = EW_DIR; // include directories - if (options & WILD_LIST_NOTFOUND) { - flags |= EW_NOTFOUND; - } - if (options & WILD_ADD_SLASH) { - flags |= EW_ADDSLASH; - } - if (options & WILD_KEEP_ALL) { - flags |= EW_KEEPALL; - } - if (options & WILD_SILENT) { - flags |= EW_SILENT; - } - if (options & WILD_NOERROR) { - flags |= EW_NOERROR; - } - if (options & WILD_ALLLINKS) { - flags |= EW_ALLLINKS; - } - - if (xp->xp_context == EXPAND_FILES - || xp->xp_context == EXPAND_DIRECTORIES - || xp->xp_context == EXPAND_FILES_IN_PATH) { - /* - * Expand file or directory names. - */ - int free_pat = FALSE; - int i; - - // for ":set path=" and ":set tags=" halve backslashes for escaped space - if (xp->xp_backslash != XP_BS_NONE) { - free_pat = TRUE; - pat = vim_strsave(pat); - for (i = 0; pat[i]; ++i) { - if (pat[i] == '\\') { - if (xp->xp_backslash == XP_BS_THREE - && pat[i + 1] == '\\' - && pat[i + 2] == '\\' - && pat[i + 3] == ' ') { - STRMOVE(pat + i, pat + i + 3); - } - if (xp->xp_backslash == XP_BS_ONE - && pat[i + 1] == ' ') { - STRMOVE(pat + i, pat + i + 1); - } - } - } - } - - if (xp->xp_context == EXPAND_FILES) { - flags |= EW_FILE; - } else if (xp->xp_context == EXPAND_FILES_IN_PATH) { - flags |= (EW_FILE | EW_PATH); - } else { - flags = (flags | EW_DIR) & ~EW_FILE; - } - if (options & WILD_ICASE) { - flags |= EW_ICASE; - } - - // Expand wildcards, supporting %:h and the like. - ret = expand_wildcards_eval(&pat, num_file, file, flags); - if (free_pat) { - xfree(pat); - } -#ifdef BACKSLASH_IN_FILENAME - if (p_csl[0] != NUL && (options & WILD_IGNORE_COMPLETESLASH) == 0) { - for (int i = 0; i < *num_file; i++) { - char_u *ptr = (*file)[i]; - while (*ptr != NUL) { - if (p_csl[0] == 's' && *ptr == '\\') { - *ptr = '/'; - } else if (p_csl[0] == 'b' && *ptr == '/') { - *ptr = '\\'; - } - ptr += utfc_ptr2len(ptr); - } - } - } -#endif - return ret; - } - - *file = NULL; - *num_file = 0; - if (xp->xp_context == EXPAND_HELP) { - /* With an empty argument we would get all the help tags, which is - * very slow. Get matches for "help" instead. */ - if (find_help_tags(*pat == NUL ? "help" : (char *)pat, - num_file, file, false) == OK) { - cleanup_help_tags(*num_file, *file); - return OK; - } - return FAIL; - } - - if (xp->xp_context == EXPAND_SHELLCMD) { - *file = NULL; - expand_shellcmd(pat, num_file, file, flags); - return OK; - } - if (xp->xp_context == EXPAND_OLD_SETTING) { - ExpandOldSetting(num_file, file); - return OK; - } - if (xp->xp_context == EXPAND_BUFFERS) { - return ExpandBufnames((char *)pat, num_file, file, options); - } - if (xp->xp_context == EXPAND_DIFF_BUFFERS) { - return ExpandBufnames((char *)pat, num_file, file, options | BUF_DIFF_FILTER); - } - if (xp->xp_context == EXPAND_TAGS - || xp->xp_context == EXPAND_TAGS_LISTFILES) { - return expand_tags(xp->xp_context == EXPAND_TAGS, pat, num_file, file); - } - if (xp->xp_context == EXPAND_COLORS) { - char *directories[] = { "colors", NULL }; - return ExpandRTDir(pat, DIP_START + DIP_OPT + DIP_LUA, num_file, file, directories); - } - if (xp->xp_context == EXPAND_COMPILER) { - char *directories[] = { "compiler", NULL }; - return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); - } - if (xp->xp_context == EXPAND_OWNSYNTAX) { - char *directories[] = { "syntax", NULL }; - return ExpandRTDir(pat, 0, num_file, file, directories); - } - if (xp->xp_context == EXPAND_FILETYPE) { - char *directories[] = { "syntax", "indent", "ftplugin", NULL }; - return ExpandRTDir(pat, DIP_LUA, num_file, file, directories); - } - if (xp->xp_context == EXPAND_USER_LIST) { - return ExpandUserList(xp, num_file, file); - } - if (xp->xp_context == EXPAND_USER_LUA) { - return ExpandUserLua(xp, num_file, file); - } - if (xp->xp_context == EXPAND_PACKADD) { - return ExpandPackAddDir(pat, num_file, file); - } - - // When expanding a function name starting with s:, match the <SNR>nr_ - // prefix. - char *tofree = NULL; - if (xp->xp_context == EXPAND_USER_FUNC && STRNCMP(pat, "^s:", 3) == 0) { - const size_t len = STRLEN(pat) + 20; - - tofree = xmalloc(len); - snprintf(tofree, len, "^<SNR>\\d\\+_%s", pat + 3); - pat = (char_u *)tofree; - } - - if (xp->xp_context == EXPAND_LUA) { - ILOG("PAT %s", pat); - return nlua_expand_pat(xp, pat, num_file, file); - } - - regmatch.regprog = vim_regcomp((char *)pat, p_magic ? RE_MAGIC : 0); - if (regmatch.regprog == NULL) { - return FAIL; - } - - // set ignore-case according to p_ic, p_scs and pat - regmatch.rm_ic = ignorecase(pat); - - if (xp->xp_context == EXPAND_SETTINGS - || xp->xp_context == EXPAND_BOOL_SETTINGS) { - ret = ExpandSettings(xp, ®match, num_file, file); - } else if (xp->xp_context == EXPAND_MAPPINGS) { - ret = ExpandMappings(®match, num_file, file); - } else if (xp->xp_context == EXPAND_USER_DEFINED) { - ret = ExpandUserDefined(xp, ®match, num_file, file); - } else { - static struct expgen { - int context; - ExpandFunc func; - int ic; - int escaped; - } tab[] = { - { EXPAND_COMMANDS, get_command_name, false, true }, - { EXPAND_BEHAVE, get_behave_arg, true, true }, - { EXPAND_MAPCLEAR, get_mapclear_arg, true, true }, - { EXPAND_MESSAGES, get_messages_arg, true, true }, - { EXPAND_HISTORY, get_history_arg, true, true }, - { EXPAND_USER_COMMANDS, get_user_commands, false, true }, - { EXPAND_USER_ADDR_TYPE, get_user_cmd_addr_type, false, true }, - { EXPAND_USER_CMD_FLAGS, get_user_cmd_flags, false, true }, - { EXPAND_USER_NARGS, get_user_cmd_nargs, false, true }, - { EXPAND_USER_COMPLETE, get_user_cmd_complete, false, true }, - { EXPAND_USER_VARS, get_user_var_name, false, true }, - { EXPAND_FUNCTIONS, get_function_name, false, true }, - { EXPAND_USER_FUNC, get_user_func_name, false, true }, - { EXPAND_EXPRESSION, get_expr_name, false, true }, - { EXPAND_MENUS, get_menu_name, false, true }, - { EXPAND_MENUNAMES, get_menu_names, false, true }, - { EXPAND_SYNTAX, get_syntax_name, true, true }, - { EXPAND_SYNTIME, get_syntime_arg, true, true }, - { EXPAND_HIGHLIGHT, (ExpandFunc)get_highlight_name, true, true }, - { EXPAND_EVENTS, expand_get_event_name, true, false }, - { EXPAND_AUGROUP, expand_get_augroup_name, true, false }, - { EXPAND_CSCOPE, get_cscope_name, true, true }, - { EXPAND_SIGN, get_sign_name, true, true }, - { EXPAND_PROFILE, get_profile_name, true, true }, -#ifdef HAVE_WORKING_LIBINTL - { EXPAND_LANGUAGE, get_lang_arg, true, false }, - { EXPAND_LOCALES, get_locales, true, false }, -#endif - { EXPAND_ENV_VARS, get_env_name, true, true }, - { EXPAND_USER, get_users, true, false }, - { EXPAND_ARGLIST, get_arglist_name, true, false }, - { EXPAND_CHECKHEALTH, get_healthcheck_names, true, false }, - }; - int i; - - /* - * Find a context in the table and call the ExpandGeneric() with the - * right function to do the expansion. - */ - ret = FAIL; - for (i = 0; i < (int)ARRAY_SIZE(tab); ++i) { - if (xp->xp_context == tab[i].context) { - if (tab[i].ic) { - regmatch.rm_ic = TRUE; - } - ExpandGeneric(xp, ®match, num_file, file, tab[i].func, tab[i].escaped); - ret = OK; - break; - } - } - } - - vim_regfree(regmatch.regprog); - xfree(tofree); - - return ret; -} - -/// Expand a list of names. -/// -/// Generic function for command line completion. It calls a function to -/// obtain strings, one by one. The strings are matched against a regexp -/// program. Matching strings are copied into an array, which is returned. -/// -/// @param func returns a string from the list -static void ExpandGeneric(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file, - CompleteListItemGetter func, int escaped) -{ - int i; - size_t count = 0; - char_u *str; - - // count the number of matching names - for (i = 0;; i++) { - str = (char_u *)(*func)(xp, i); - if (str == NULL) { // end of list - break; - } - if (*str == NUL) { // skip empty strings - continue; - } - if (vim_regexec(regmatch, (char *)str, (colnr_T)0)) { - count++; - } - } - if (count == 0) { - return; - } - assert(count < INT_MAX); - *num_file = (int)count; - *file = xmalloc(count * sizeof(char_u *)); - - // copy the matching names into allocated memory - count = 0; - for (i = 0;; i++) { - str = (char_u *)(*func)(xp, i); - if (str == NULL) { // End of list. - break; - } - if (*str == NUL) { // Skip empty strings. - continue; - } - if (vim_regexec(regmatch, (char *)str, (colnr_T)0)) { - if (escaped) { - str = vim_strsave_escaped(str, (char_u *)" \t\\."); - } else { - str = vim_strsave(str); - } - (*file)[count++] = (char *)str; - if (func == get_menu_names) { - // Test for separator added by get_menu_names(). - str += STRLEN(str) - 1; - if (*str == '\001') { - *str = '.'; - } - } - } - } - - // Sort the results. Keep menu's in the specified order. - if (xp->xp_context != EXPAND_MENUNAMES && xp->xp_context != EXPAND_MENUS) { - if (xp->xp_context == EXPAND_EXPRESSION - || xp->xp_context == EXPAND_FUNCTIONS - || xp->xp_context == EXPAND_USER_FUNC) { - // <SNR> functions should be sorted to the end. - qsort((void *)*file, (size_t)*num_file, sizeof(char_u *), - sort_func_compare); - } else { - sort_strings(*file, *num_file); - } - } - - /* Reset the variables used for special highlight names expansion, so that - * they don't show up when getting normal highlight names by ID. */ - reset_expand_highlight(); -} - -/// Complete a shell command. -/// -/// @param filepat is a pattern to match with command names. -/// @param[out] num_file is pointer to number of matches. -/// @param[out] file is pointer to array of pointers to matches. -/// *file will either be set to NULL or point to -/// allocated memory. -/// @param flagsarg is a combination of EW_* flags. -static void expand_shellcmd(char_u *filepat, int *num_file, char ***file, int flagsarg) - FUNC_ATTR_NONNULL_ALL -{ - char_u *pat; - int i; - char_u *path = NULL; - garray_T ga; - char *buf = xmalloc(MAXPATHL); - size_t l; - char_u *s, *e; - int flags = flagsarg; - int ret; - bool did_curdir = false; - - // for ":set path=" and ":set tags=" halve backslashes for escaped space - pat = vim_strsave(filepat); - for (i = 0; pat[i]; ++i) { - if (pat[i] == '\\' && pat[i + 1] == ' ') { - STRMOVE(pat + i, pat + i + 1); - } - } - - flags |= EW_FILE | EW_EXEC | EW_SHELLCMD; - - bool mustfree = false; // Track memory allocation for *path. - if (pat[0] == '.' && (vim_ispathsep(pat[1]) - || (pat[1] == '.' && vim_ispathsep(pat[2])))) { - path = (char_u *)"."; - } else { - // For an absolute name we don't use $PATH. - if (!path_is_absolute(pat)) { - path = (char_u *)vim_getenv("PATH"); - } - if (path == NULL) { - path = (char_u *)""; - } else { - mustfree = true; - } - } - - /* - * Go over all directories in $PATH. Expand matches in that directory and - * collect them in "ga". When "." is not in $PATH also expaned for the - * current directory, to find "subdir/cmd". - */ - ga_init(&ga, (int)sizeof(char *), 10); - hashtab_T found_ht; - hash_init(&found_ht); - for (s = path;; s = e) { - e = (char_u *)vim_strchr((char *)s, ENV_SEPCHAR); - if (e == NULL) { - e = s + STRLEN(s); - } - - if (*s == NUL) { - if (did_curdir) { - break; - } - // Find directories in the current directory, path is empty. - did_curdir = true; - flags |= EW_DIR; - } else if (STRNCMP(s, ".", e - s) == 0) { - did_curdir = true; - flags |= EW_DIR; - } else { - // Do not match directories inside a $PATH item. - flags &= ~EW_DIR; - } - - l = (size_t)(e - s); - if (l > MAXPATHL - 5) { - break; - } - STRLCPY(buf, s, l + 1); - add_pathsep(buf); - l = STRLEN(buf); - STRLCPY(buf + l, pat, MAXPATHL - l); - - // Expand matches in one directory of $PATH. - ret = expand_wildcards(1, &buf, num_file, file, flags); - if (ret == OK) { - ga_grow(&ga, *num_file); - { - for (i = 0; i < *num_file; i++) { - char_u *name = (char_u *)(*file)[i]; - - if (STRLEN(name) > l) { - // Check if this name was already found. - hash_T hash = hash_hash(name + l); - hashitem_T *hi = - hash_lookup(&found_ht, (const char *)(name + l), - STRLEN(name + l), hash); - if (HASHITEM_EMPTY(hi)) { - // Remove the path that was prepended. - STRMOVE(name, name + l); - ((char_u **)ga.ga_data)[ga.ga_len++] = name; - hash_add_item(&found_ht, hi, name, hash); - name = NULL; - } - } - xfree(name); - } - xfree(*file); - } - } - if (*e != NUL) { - e++; - } - } - *file = ga.ga_data; - *num_file = ga.ga_len; - - xfree(buf); - xfree(pat); - if (mustfree) { - xfree(path); - } - hash_clear(&found_ht); -} - -/// Call "user_expand_func()" to invoke a user defined Vim script function and -/// return the result (either a string, a List or NULL). -static void *call_user_expand_func(user_expand_func_T user_expand_func, expand_T *xp, int *num_file, - char ***file) - FUNC_ATTR_NONNULL_ALL -{ - char_u keep = 0; - typval_T args[4]; - char_u *pat = NULL; - const sctx_T save_current_sctx = current_sctx; - - if (xp->xp_arg == NULL || xp->xp_arg[0] == '\0' || xp->xp_line == NULL) { - return NULL; - } - *num_file = 0; - *file = NULL; - - if (ccline.cmdbuff != NULL) { - keep = ccline.cmdbuff[ccline.cmdlen]; - ccline.cmdbuff[ccline.cmdlen] = 0; - } - - pat = vim_strnsave((char_u *)xp->xp_pattern, xp->xp_pattern_len); - args[0].v_type = VAR_STRING; - args[1].v_type = VAR_STRING; - args[2].v_type = VAR_NUMBER; - args[3].v_type = VAR_UNKNOWN; - args[0].vval.v_string = (char *)pat; - args[1].vval.v_string = xp->xp_line; - args[2].vval.v_number = xp->xp_col; - - current_sctx = xp->xp_script_ctx; - - void *const ret = user_expand_func((char_u *)xp->xp_arg, 3, args); - - current_sctx = save_current_sctx; - if (ccline.cmdbuff != NULL) { - ccline.cmdbuff[ccline.cmdlen] = keep; - } - - xfree(pat); - return ret; -} - -/// Expand names with a function defined by the user. -static int ExpandUserDefined(expand_T *xp, regmatch_T *regmatch, int *num_file, char ***file) -{ - char_u *e; - garray_T ga; - - char_u *const retstr = call_user_expand_func((user_expand_func_T)call_func_retstr, xp, num_file, - file); - - if (retstr == NULL) { - return FAIL; - } - - ga_init(&ga, (int)sizeof(char *), 3); - for (char_u *s = retstr; *s != NUL; s = e) { - e = (char_u *)vim_strchr((char *)s, '\n'); - if (e == NULL) { - e = s + STRLEN(s); - } - const char_u keep = *e; - *e = NUL; - - const bool skip = xp->xp_pattern[0] - && vim_regexec(regmatch, (char *)s, (colnr_T)0) == 0; - *e = keep; - if (!skip) { - GA_APPEND(char_u *, &ga, vim_strnsave(s, (size_t)(e - s))); - } - - if (*e != NUL) { - e++; - } - } - xfree(retstr); - *file = ga.ga_data; - *num_file = ga.ga_len; - return OK; -} - -/// Expand names with a list returned by a function defined by the user. -static int ExpandUserList(expand_T *xp, int *num_file, char ***file) -{ - list_T *const retlist = call_user_expand_func((user_expand_func_T)call_func_retlist, xp, num_file, - file); - if (retlist == NULL) { - return FAIL; - } - - garray_T ga; - ga_init(&ga, (int)sizeof(char *), 3); - // Loop over the items in the list. - TV_LIST_ITER_CONST(retlist, li, { - if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING - || TV_LIST_ITEM_TV(li)->vval.v_string == NULL) { - continue; // Skip non-string items and empty strings. - } - - GA_APPEND(char *, &ga, xstrdup((const char *)TV_LIST_ITEM_TV(li)->vval.v_string)); - }); - tv_list_unref(retlist); - - *file = ga.ga_data; - *num_file = ga.ga_len; - return OK; -} - -static int ExpandUserLua(expand_T *xp, int *num_file, char ***file) -{ - typval_T rettv; - nlua_call_user_expand_func(xp, &rettv); - if (rettv.v_type != VAR_LIST) { - tv_clear(&rettv); - return FAIL; - } - - list_T *const retlist = rettv.vval.v_list; - - garray_T ga; - ga_init(&ga, (int)sizeof(char *), 3); - // Loop over the items in the list. - TV_LIST_ITER_CONST(retlist, li, { - if (TV_LIST_ITEM_TV(li)->v_type != VAR_STRING - || TV_LIST_ITEM_TV(li)->vval.v_string == NULL) { - continue; // Skip non-string items and empty strings. - } - - GA_APPEND(char *, &ga, xstrdup((const char *)TV_LIST_ITEM_TV(li)->vval.v_string)); - }); - tv_list_unref(retlist); - - *file = ga.ga_data; - *num_file = ga.ga_len; - return OK; -} - -/// Expand `file` for all comma-separated directories in `path`. -/// Adds matches to `ga`. -void globpath(char *path, char_u *file, garray_T *ga, int expand_options) -{ - expand_T xpc; - ExpandInit(&xpc); - xpc.xp_context = EXPAND_FILES; - - char_u *buf = xmalloc(MAXPATHL); - - // Loop over all entries in {path}. - while (*path != NUL) { - // Copy one item of the path to buf[] and concatenate the file name. - copy_option_part(&path, (char *)buf, MAXPATHL, ","); - if (STRLEN(buf) + STRLEN(file) + 2 < MAXPATHL) { - add_pathsep((char *)buf); - STRCAT(buf, file); // NOLINT - - char **p; - int num_p = 0; - (void)ExpandFromContext(&xpc, buf, &num_p, &p, - WILD_SILENT | expand_options); - if (num_p > 0) { - ExpandEscape(&xpc, buf, num_p, p, WILD_SILENT | expand_options); - - // Concatenate new results to previous ones. - ga_grow(ga, num_p); - // take over the pointers and put them in "ga" - for (int i = 0; i < num_p; i++) { - ((char_u **)ga->ga_data)[ga->ga_len] = (char_u *)p[i]; - ga->ga_len++; - } - xfree(p); - } - } - } - - xfree(buf); + return last_prompt_id; } /// Get pointer to the command line info to use. save_cmdline() may clear /// ccline and put the previous value in ccline.prev_ccline. -static struct cmdline_info *get_ccline_ptr(void) +static CmdlineInfo *get_ccline_ptr(void) { if ((State & MODE_CMDLINE) == 0) { return NULL; @@ -5783,7 +3873,7 @@ char_u *get_cmdline_completion(void) if (cmdline_star > 0) { return NULL; } - struct cmdline_info *p = get_ccline_ptr(); + CmdlineInfo *p = get_ccline_ptr(); if (p != NULL && p->xpc != NULL) { set_expand_context(p->xpc); @@ -5806,7 +3896,7 @@ char_u *get_cmdline_str(void) if (cmdline_star > 0) { return NULL; } - struct cmdline_info *p = get_ccline_ptr(); + CmdlineInfo *p = get_ccline_ptr(); if (p == NULL) { return NULL; @@ -5822,7 +3912,7 @@ char_u *get_cmdline_str(void) */ int get_cmdline_pos(void) { - struct cmdline_info *p = get_ccline_ptr(); + CmdlineInfo *p = get_ccline_ptr(); if (p == NULL) { return -1; @@ -5833,7 +3923,7 @@ int get_cmdline_pos(void) /// Get the command line cursor screen position. int get_cmdline_screen_pos(void) { - struct cmdline_info *p = get_ccline_ptr(); + CmdlineInfo *p = get_ccline_ptr(); if (p == NULL) { return -1; @@ -5848,7 +3938,7 @@ int get_cmdline_screen_pos(void) */ int set_cmdline_pos(int pos) { - struct cmdline_info *p = get_ccline_ptr(); + CmdlineInfo *p = get_ccline_ptr(); if (p == NULL) { return 1; @@ -5872,7 +3962,7 @@ int set_cmdline_pos(int pos) */ int get_cmdline_type(void) { - struct cmdline_info *p = get_ccline_ptr(); + CmdlineInfo *p = get_ccline_ptr(); if (p == NULL) { return NUL; diff --git a/src/nvim/ex_getln.h b/src/nvim/ex_getln.h index 2f6929924d..5e3ad20a31 100644 --- a/src/nvim/ex_getln.h +++ b/src/nvim/ex_getln.h @@ -2,42 +2,77 @@ #define NVIM_EX_GETLN_H #include "nvim/eval/typval.h" -#include "nvim/ex_cmds.h" -#include "nvim/regexp_defs.h" - -// Values for nextwild() and ExpandOne(). See ExpandOne() for meaning. -#define WILD_FREE 1 -#define WILD_EXPAND_FREE 2 -#define WILD_EXPAND_KEEP 3 -#define WILD_NEXT 4 -#define WILD_PREV 5 -#define WILD_ALL 6 -#define WILD_LONGEST 7 -#define WILD_ALL_KEEP 8 -#define WILD_CANCEL 9 -#define WILD_APPLY 10 - -#define WILD_LIST_NOTFOUND 0x01 -#define WILD_HOME_REPLACE 0x02 -#define WILD_USE_NL 0x04 -#define WILD_NO_BEEP 0x08 -#define WILD_ADD_SLASH 0x10 -#define WILD_KEEP_ALL 0x20 -#define WILD_SILENT 0x40 -#define WILD_ESCAPE 0x80 -#define WILD_ICASE 0x100 -#define WILD_ALLLINKS 0x200 -#define WILD_IGNORE_COMPLETESLASH 0x400 -#define WILD_NOERROR 0x800 // sets EW_NOERROR -#define WILD_BUFLASTUSED 0x1000 -#define BUF_DIFF_FILTER 0x2000 - -// flags used by vim_strsave_fnameescape() -#define VSE_NONE 0 -#define VSE_SHELL 1 ///< escape for a shell command -#define VSE_BUFFER 2 ///< escape for a ":buffer" command - -typedef char *(*CompleteListItemGetter)(expand_T *, int); +#include "nvim/ex_cmds_defs.h" +#include "nvim/types.h" + +/// Command-line colors: one chunk +/// +/// Defines a region which has the same highlighting. +typedef struct { + int start; ///< Colored chunk start. + int end; ///< Colored chunk end (exclusive, > start). + int attr; ///< Highlight attr. +} CmdlineColorChunk; + +/// Command-line colors +/// +/// Holds data about all colors. +typedef kvec_t(CmdlineColorChunk) CmdlineColors; + +/// Command-line coloring +/// +/// Holds both what are the colors and what have been colored. Latter is used to +/// suppress unnecessary calls to coloring callbacks. +typedef struct { + unsigned prompt_id; ///< ID of the prompt which was colored last. + char *cmdbuff; ///< What exactly was colored last time or NULL. + CmdlineColors colors; ///< Last colors. +} ColoredCmdline; + +/// Keeps track how much state must be sent to external ui. +typedef enum { + kCmdRedrawNone, + kCmdRedrawPos, + kCmdRedrawAll, +} CmdRedraw; + +/// Variables shared between getcmdline(), redrawcmdline() and others. +/// These need to be saved when using CTRL-R |, that's why they are in a +/// structure. +typedef struct cmdline_info CmdlineInfo; +struct cmdline_info { + char_u *cmdbuff; ///< pointer to command line buffer + int cmdbufflen; ///< length of cmdbuff + int cmdlen; ///< number of chars in command line + int cmdpos; ///< current cursor position + int cmdspos; ///< cursor column on screen + int cmdfirstc; ///< ':', '/', '?', '=', '>' or NUL + int cmdindent; ///< number of spaces before cmdline + char_u *cmdprompt; ///< message in front of cmdline + int cmdattr; ///< attributes for prompt + int overstrike; ///< Typing mode on the command line. Shared by + ///< getcmdline() and put_on_cmdline(). + expand_T *xpc; ///< struct being used for expansion, xp_pattern + ///< may point into cmdbuff + int xp_context; ///< type of expansion + char_u *xp_arg; ///< user-defined expansion arg + int input_fn; ///< when true Invoked for input() function + unsigned prompt_id; ///< Prompt number, used to disable coloring on errors. + Callback highlight_callback; ///< Callback used for coloring user input. + ColoredCmdline last_colors; ///< Last cmdline colors + int level; ///< current cmdline level + CmdlineInfo *prev_ccline; ///< pointer to saved cmdline state + char special_char; ///< last putcmdline char (used for redraws) + bool special_shift; ///< shift of last putcmdline char + CmdRedraw redraw_state; ///< needed redraw for external cmdline +}; + +/// flags used by vim_strsave_fnameescape() +enum { + VSE_NONE = 0, + VSE_SHELL = 1, ///< escape for a shell command + VSE_BUFFER = 2, ///< escape for a ":buffer" command +}; #ifdef INCLUDE_GENERATED_DECLARATIONS # include "ex_getln.h.generated.h" diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index a3af7dc372..0f55158733 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -20,6 +20,7 @@ #include "nvim/eval.h" #include "nvim/eval/typval.h" #include "nvim/event/loop.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_docmd.h" #include "nvim/ex_getln.h" #include "nvim/garray.h" @@ -2399,7 +2400,8 @@ static int vgetorpeek(bool advance) vgetc_busy++; if (advance) { - KeyStuffed = FALSE; + KeyStuffed = false; + typebuf_was_empty = false; } init_typebuf(); @@ -2625,6 +2627,11 @@ static int vgetorpeek(bool advance) } tc = c; + // set a flag to indicate this wasn't a normal char + if (advance) { + typebuf_was_empty = true; + } + // return 0 in normal_check() if (pending_exmode_active) { exmode_active = true; diff --git a/src/nvim/globals.h b/src/nvim/globals.h index 954b62883e..231220c319 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -705,6 +705,10 @@ EXTERN int recoverymode INIT(= false); // Set to true for "-r" option // typeahead buffer EXTERN typebuf_T typebuf INIT(= { NULL, NULL, 0, 0, 0, 0, 0, 0, 0 }); +/// Flag used to indicate that vgetorpeek() returned a char like Esc when the +/// :normal argument was exhausted. +EXTERN bool typebuf_was_empty INIT(= false); + EXTERN int ex_normal_busy INIT(= 0); // recursiveness of ex_normal() EXTERN int ex_normal_lock INIT(= 0); // forbid use of ex_normal() EXTERN int ignore_script INIT(= false); // ignore script input diff --git a/src/nvim/help.c b/src/nvim/help.c index 569f68e330..442f2e0b7b 100644 --- a/src/nvim/help.c +++ b/src/nvim/help.c @@ -8,9 +8,9 @@ #include "nvim/buffer.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/ex_cmds.h" #include "nvim/ex_docmd.h" -#include "nvim/ex_getln.h" #include "nvim/fileio.h" #include "nvim/garray.h" #include "nvim/globals.h" diff --git a/src/nvim/insexpand.c b/src/nvim/insexpand.c index c525a49bc3..938189f343 100644 --- a/src/nvim/insexpand.c +++ b/src/nvim/insexpand.c @@ -12,6 +12,7 @@ #include "nvim/buffer.h" #include "nvim/change.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cursor.h" #include "nvim/drawscreen.h" #include "nvim/edit.h" diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 5d97f90bb1..d1d1480696 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -22,6 +22,7 @@ #include "nvim/eval/userfunc.h" #include "nvim/event/loop.h" #include "nvim/event/time.h" +#include "nvim/ex_cmds.h" #include "nvim/ex_getln.h" #include "nvim/extmark.h" #include "nvim/func_attr.h" @@ -1939,8 +1940,13 @@ int nlua_do_ucmd(ucmd_T *cmd, exarg_T *eap, bool preview) // Split args by unescaped whitespace |<f-args>| (nargs dependent) if (cmd->uc_argt & EX_NOSPC) { - // Commands where nargs = 1 or "?" fargs is the same as args - lua_rawseti(lstate, -2, 1); + if ((cmd->uc_argt & EX_NEEDARG) || STRLEN(eap->arg)) { + // For commands where nargs is 1 or "?" and argument is passed, fargs = { args } + lua_rawseti(lstate, -2, 1); + } else { + // if nargs = "?" and no argument is passed, fargs = {} + lua_pop(lstate, 1); // Pop the reference of opts.args + } } else if (eap->args == NULL) { // For commands with more than one possible argument, split if argument list isn't available. lua_pop(lstate, 1); // Pop the reference of opts.args diff --git a/src/nvim/normal.c b/src/nvim/normal.c index 1d8a786c9f..2c7dadad0b 100644 --- a/src/nvim/normal.c +++ b/src/nvim/normal.c @@ -6943,10 +6943,10 @@ static void nv_esc(cmdarg_T *cap) got_int = false; // don't stop executing autocommands et al. return; } - } else if (cmdwin_type != 0 && ex_normal_busy) { + } else if (cmdwin_type != 0 && ex_normal_busy && typebuf_was_empty) { // When :normal runs out of characters while in the command line window - // vgetorpeek() will return ESC. Exit the cmdline window to break the - // loop. + // vgetorpeek() will repeatedly return ESC. Exit the cmdline window to + // break the loop. cmdwin_result = K_IGNORE; return; } diff --git a/src/nvim/optionstr.c b/src/nvim/optionstr.c index 4ff14f0122..c50225dfdf 100644 --- a/src/nvim/optionstr.c +++ b/src/nvim/optionstr.c @@ -614,7 +614,6 @@ static int shada_idx = -1; /// Handle string options that need some action to perform when changed. /// The new value must be allocated. -/// Returns NULL for success, or an error message for an error. /// /// @param opt_idx index in options[] table /// @param varp pointer to the option variable @@ -623,6 +622,8 @@ static int shada_idx = -1; /// @param errbuflen length of errors buffer /// @param opt_flags OPT_LOCAL and/or OPT_GLOBAL /// @param value_checked value was checked to be safe, no need to set P_INSECURE +/// +/// @return NULL for success, or an untranslated error message for an error char *did_set_string_option(int opt_idx, char_u **varp, char_u *oldval, char *errbuf, size_t errbuflen, int opt_flags, int *value_checked) { @@ -698,12 +699,10 @@ char *did_set_string_option(int opt_idx, char_u **varp, char_u *oldval, char *er } else if (varp == &p_hf) { // 'helpfile' // May compute new values for $VIM and $VIMRUNTIME if (didset_vim) { - os_setenv("VIM", "", 1); - didset_vim = false; + vim_unsetenv_ext("VIM"); } if (didset_vimruntime) { - os_setenv("VIMRUNTIME", "", 1); - didset_vimruntime = false; + vim_unsetenv_ext("VIMRUNTIME"); } } else if (varp == &p_rtp || varp == &p_pp) { // 'runtimepath' 'packpath' runtime_search_path_invalidate(); diff --git a/src/nvim/os/env.c b/src/nvim/os/env.c index 98ef4bd0f6..795bff66cb 100644 --- a/src/nvim/os/env.c +++ b/src/nvim/os/env.c @@ -8,8 +8,8 @@ #include "nvim/ascii.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/eval.h" -#include "nvim/ex_getln.h" #include "nvim/macros.h" #include "nvim/map.h" #include "nvim/memory.h" @@ -1229,3 +1229,29 @@ bool os_shell_is_cmdexe(const char *sh) } return striequal("cmd.exe", path_tail(sh)); } + +/// Removes environment variable "name" and take care of side effects. +void vim_unsetenv_ext(const char *var) +{ + os_unsetenv(var); + + // "homedir" is not cleared, keep using the old value until $HOME is set. + if (STRICMP(var, "VIM") == 0) { + didset_vim = false; + } else if (STRICMP(var, "VIMRUNTIME") == 0) { + didset_vimruntime = false; + } +} + +/// Set environment variable "name" and take care of side effects. +void vim_setenv_ext(const char *name, const char *val) +{ + os_setenv(name, val, 1); + if (STRICMP(name, "HOME") == 0) { + init_homedir(); + } else if (didset_vim && STRICMP(name, "VIM") == 0) { + didset_vim = false; + } else if (didset_vimruntime && STRICMP(name, "VIMRUNTIME") == 0) { + didset_vimruntime = false; + } +} diff --git a/src/nvim/path.c b/src/nvim/path.c index caea11debd..1500254de5 100644 --- a/src/nvim/path.c +++ b/src/nvim/path.c @@ -8,9 +8,9 @@ #include "nvim/ascii.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/eval.h" #include "nvim/ex_docmd.h" -#include "nvim/ex_getln.h" #include "nvim/file_search.h" #include "nvim/fileio.h" #include "nvim/garray.h" @@ -725,7 +725,7 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, // Find all matching entries. char_u *name; scandir_next_with_dots(NULL); // initialize - while ((name = (char_u *)scandir_next_with_dots(&dir)) != NULL) { + while (!got_int && (name = (char_u *)scandir_next_with_dots(&dir)) != NULL) { if ((name[0] != '.' || starts_with_dot || ((flags & EW_DODOT) @@ -774,8 +774,10 @@ static size_t do_path_expand(garray_T *gap, const char_u *path, size_t wildoff, xfree(buf); vim_regfree(regmatch.regprog); + // When interrupted the matches probably won't be used and sorting can be + // slow, thus skip it. size_t matches = (size_t)(gap->ga_len - start_len); - if (matches > 0) { + if (matches > 0 && !got_int) { qsort(((char_u **)gap->ga_data) + start_len, matches, sizeof(char_u *), pstrcmp); } @@ -1254,7 +1256,7 @@ int gen_expand_wildcards(int num_pat, char **pat, int *num_file, char ***file, i */ ga_init(&ga, (int)sizeof(char_u *), 30); - for (int i = 0; i < num_pat; ++i) { + for (int i = 0; i < num_pat && !got_int; i++) { add_pat = -1; p = (char_u *)pat[i]; @@ -2205,17 +2207,14 @@ int expand_wildcards(int num_pat, char **pat, int *num_files, char ***files, int } } - // // Move the names where 'suffixes' match to the end. - // + // Skip when interrupted, the result probably won't be used. assert(*num_files == 0 || *files != NULL); - if (*num_files > 1) { + if (*num_files > 1 && !got_int) { non_suf_match = 0; for (i = 0; i < *num_files; i++) { if (!match_suffix((char_u *)(*files)[i])) { - // // Move the name without matching suffix to the front of the list. - // p = (char_u *)(*files)[i]; for (j = i; j > non_suf_match; j--) { (*files)[j] = (*files)[j - 1]; diff --git a/src/nvim/runtime.c b/src/nvim/runtime.c index edcaa27e2b..914b21bb02 100644 --- a/src/nvim/runtime.c +++ b/src/nvim/runtime.c @@ -9,6 +9,7 @@ #include "nvim/ascii.h" #include "nvim/autocmd.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/debugger.h" #include "nvim/eval.h" #include "nvim/eval/userfunc.h" @@ -16,7 +17,6 @@ #include "nvim/ex_cmds2.h" #include "nvim/ex_docmd.h" #include "nvim/ex_eval.h" -#include "nvim/ex_getln.h" #include "nvim/lua/executor.h" #include "nvim/memline.h" #include "nvim/option.h" diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 4bc6e362eb..b471b93192 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -15,10 +15,10 @@ #include "nvim/buffer.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cursor.h" #include "nvim/drawscreen.h" #include "nvim/eval.h" -#include "nvim/ex_getln.h" #include "nvim/extmark.h" #include "nvim/fileio.h" #include "nvim/fold.h" diff --git a/src/nvim/tag.c b/src/nvim/tag.c index 5866f11aab..65c56bf01b 100644 --- a/src/nvim/tag.c +++ b/src/nvim/tag.c @@ -13,6 +13,7 @@ #include "nvim/ascii.h" #include "nvim/buffer.h" #include "nvim/charset.h" +#include "nvim/cmdexpand.h" #include "nvim/cursor.h" #include "nvim/drawscreen.h" #include "nvim/edit.h" diff --git a/src/nvim/testdir/test_cmdline.vim b/src/nvim/testdir/test_cmdline.vim index b9f027afb2..3f53ed04b6 100644 --- a/src/nvim/testdir/test_cmdline.vim +++ b/src/nvim/testdir/test_cmdline.vim @@ -1857,6 +1857,179 @@ func Test_recalling_cmdline() cunmap <Plug>(save-cmdline) endfunc +" Test for using a popup menu for the command line completion matches +" (wildoptions=pum) +func Test_wildmenu_pum() + CheckRunVimInTerminal + + let commands =<< trim [CODE] + set wildmenu + set wildoptions=pum + set shm+=I + set noruler + set noshowcmd + [CODE] + call writefile(commands, 'Xtest') + + let buf = RunVimInTerminal('-S Xtest', #{rows: 10}) + + call term_sendkeys(buf, ":sign \<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_01', {}) + + call term_sendkeys(buf, "\<Down>\<Down>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_02', {}) + + call term_sendkeys(buf, "\<C-N>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_03', {}) + + call term_sendkeys(buf, "\<C-P>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_04', {}) + + call term_sendkeys(buf, "\<Up>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_05', {}) + + " pressing <C-E> should end completion and go back to the original match + call term_sendkeys(buf, "\<C-E>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_06', {}) + + " pressing <C-Y> should select the current match and end completion + call term_sendkeys(buf, "\<Tab>\<C-P>\<C-P>\<C-Y>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_07', {}) + + " With 'wildmode' set to 'longest,full', completing a match should display + " the longest match, the wildmenu should not be displayed. + call term_sendkeys(buf, ":\<C-U>set wildmode=longest,full\<CR>") + call TermWait(buf) + call term_sendkeys(buf, ":sign u\<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_08', {}) + + " pressing <Tab> should display the wildmenu + call term_sendkeys(buf, "\<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_09', {}) + + " pressing <Tab> second time should select the next entry in the menu + call term_sendkeys(buf, "\<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_10', {}) + + call term_sendkeys(buf, ":\<C-U>set wildmode=full\<CR>") + " " showing popup menu in different columns in the cmdline + call term_sendkeys(buf, ":sign define \<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_11', {}) + + call term_sendkeys(buf, " \<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_12', {}) + + call term_sendkeys(buf, " \<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_13', {}) + + " Directory name completion + call mkdir('Xdir/XdirA/XdirB', 'p') + call writefile([], 'Xdir/XfileA') + call writefile([], 'Xdir/XdirA/XfileB') + call writefile([], 'Xdir/XdirA/XdirB/XfileC') + + call term_sendkeys(buf, "\<C-U>e Xdi\<Tab>\<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_14', {}) + + " Pressing <Right> on a directory name should go into that directory + call term_sendkeys(buf, "\<Right>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_15', {}) + + " Pressing <Left> on a directory name should go to the parent directory + call term_sendkeys(buf, "\<Left>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_16', {}) + + " Pressing <C-A> when the popup menu is displayed should list all the + " matches and remove the popup menu + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-A>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_17', {}) + + " Pressing <C-D> when the popup menu is displayed should remove the popup + " menu + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-D>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_18', {}) + + " Pressing <S-Tab> should open the popup menu with the last entry selected + call term_sendkeys(buf, "\<C-U>\<CR>:sign \<S-Tab>\<C-P>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_19', {}) + + " Pressing <Esc> should close the popup menu and cancel the cmd line + call term_sendkeys(buf, "\<C-U>\<CR>:sign \<Tab>\<Esc>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_20', {}) + + " Typing a character when the popup is open, should close the popup + call term_sendkeys(buf, ":sign \<Tab>x") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_21', {}) + + " When the popup is open, entering the cmdline window should close the popup + call term_sendkeys(buf, "\<C-U>sign \<Tab>\<C-F>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_22', {}) + call term_sendkeys(buf, ":q\<CR>") + + " After the last popup menu item, <C-N> should show the original string + call term_sendkeys(buf, ":sign u\<Tab>\<C-N>\<C-N>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_23', {}) + + " Use the popup menu for the command name + call term_sendkeys(buf, "\<C-U>bu\<Tab>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_24', {}) + + " Pressing the left arrow should remove the popup menu + call term_sendkeys(buf, "\<Left>\<Left>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_25', {}) + + " Pressing <BS> should remove the popup menu and erase the last character + call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<BS>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_26', {}) + + " Pressing <C-W> should remove the popup menu and erase the previous word + call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<C-W>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_27', {}) + + " Pressing <C-U> should remove the popup menu and erase the entire line + call term_sendkeys(buf, "\<C-E>\<C-U>sign \<Tab>\<C-U>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_28', {}) + + " Using <C-E> to cancel the popup menu and then pressing <Up> should recall + " the cmdline from history + call term_sendkeys(buf, "sign xyz\<Esc>:sign \<Tab>\<C-E>\<Up>") + call TermWait(buf) + call VerifyScreenDump(buf, 'Test_wildmenu_pum_29', {}) + + call term_sendkeys(buf, "\<C-U>\<CR>") + call StopVimInTerminal(buf) + call delete('Xtest') + call delete('Xdir', 'rf') +endfunc + " this was going over the end of IObuff func Test_report_error_with_composing() let caught = 'no' @@ -1926,4 +2099,14 @@ func Test_cmdline_redraw_tabline() call delete('Xcmdline_redraw_tabline') endfunc +func Test_wildmenu_pum_disable_while_shown() + set wildoptions=pum + set wildmenu + cnoremap <F2> <Cmd>set nowildmenu<CR> + call feedkeys(":sign \<Tab>\<F2>\<Esc>", 'tx') + call assert_equal(0, pumvisible()) + cunmap <F2> + set wildoptions& wildmenu& +endfunc + " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_environ.vim b/src/nvim/testdir/test_environ.vim index dd34983ee5..d8344817f5 100644 --- a/src/nvim/testdir/test_environ.vim +++ b/src/nvim/testdir/test_environ.vim @@ -28,6 +28,26 @@ func Test_setenv() call assert_equal(v:null, getenv('TEST ENV')) endfunc +func Test_special_env() + " The value for $HOME is cached internally by Vim, ensure the value is up to + " date. + let orig_ENV = $HOME + + let $HOME = 'foo' + call assert_equal('foo', expand('~')) + " old $HOME value is kept until a new one is set + unlet $HOME + call assert_equal('foo', expand('~')) + + call setenv('HOME', 'bar') + call assert_equal('bar', expand('~')) + " old $HOME value is kept until a new one is set + call setenv('HOME', v:null) + call assert_equal('bar', expand('~')) + + let $HOME = orig_ENV +endfunc + func Test_external_env() call setenv('FOO', 'HelloWorld') if has('win32') diff --git a/test/functional/api/command_spec.lua b/test/functional/api/command_spec.lua index 7eb7ee73f9..890710b6e6 100644 --- a/test/functional/api/command_spec.lua +++ b/test/functional/api/command_spec.lua @@ -326,7 +326,7 @@ describe('nvim_create_user_command', function() -- f-args doesn't split when command nargs is 1 or "?" exec_lua [[ result = {} - vim.api.nvim_create_user_command('CommandWithOneArg', function(opts) + vim.api.nvim_create_user_command('CommandWithOneOrNoArg', function(opts) result = opts end, { nargs = "?", @@ -366,7 +366,89 @@ describe('nvim_create_user_command', function() count = 2, reg = "", }, exec_lua [[ - vim.api.nvim_command('CommandWithOneArg hello I\'m one argument') + vim.api.nvim_command('CommandWithOneOrNoArg hello I\'m one argument') + return result + ]]) + + -- f-args is an empty table if no args were passed + eq({ + args = "", + fargs = {}, + bang = false, + line1 = 1, + line2 = 1, + mods = "", + smods = { + browse = false, + confirm = false, + emsg_silent = false, + hide = false, + keepalt = false, + keepjumps = false, + keepmarks = false, + keeppatterns = false, + lockmarks = false, + noautocmd = false, + noswapfile = false, + sandbox = false, + silent = false, + split = "", + tab = 0, + unsilent = false, + verbose = -1, + vertical = false, + }, + range = 0, + count = 2, + reg = "", + }, exec_lua [[ + vim.api.nvim_command('CommandWithOneOrNoArg') + return result + ]]) + + -- f-args is an empty table when the command nargs=0 + exec_lua [[ + result = {} + vim.api.nvim_create_user_command('CommandWithNoArgs', function(opts) + result = opts + end, { + nargs = 0, + bang = true, + count = 2, + }) + ]] + eq({ + args = "", + fargs = {}, + bang = false, + line1 = 1, + line2 = 1, + mods = "", + smods = { + browse = false, + confirm = false, + emsg_silent = false, + hide = false, + keepalt = false, + keepjumps = false, + keepmarks = false, + keeppatterns = false, + lockmarks = false, + noautocmd = false, + noswapfile = false, + sandbox = false, + silent = false, + split = "", + tab = 0, + unsilent = false, + verbose = -1, + vertical = false, + }, + range = 0, + count = 2, + reg = "", + }, exec_lua [[ + vim.cmd('CommandWithNoArgs') return result ]]) diff --git a/test/functional/fixtures/compdir/file1 b/test/functional/fixtures/wildpum/Xdir/XdirA/XdirB/XfileC index e69de29bb2..e69de29bb2 100644 --- a/test/functional/fixtures/compdir/file1 +++ b/test/functional/fixtures/wildpum/Xdir/XdirA/XdirB/XfileC diff --git a/test/functional/fixtures/compdir/file2 b/test/functional/fixtures/wildpum/Xdir/XdirA/XfileB index e69de29bb2..e69de29bb2 100644 --- a/test/functional/fixtures/compdir/file2 +++ b/test/functional/fixtures/wildpum/Xdir/XdirA/XfileB diff --git a/test/functional/fixtures/wildpum/Xdir/XfileA b/test/functional/fixtures/wildpum/Xdir/XfileA new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/test/functional/fixtures/wildpum/Xdir/XfileA diff --git a/test/functional/fixtures/wildpum/compdir/file1 b/test/functional/fixtures/wildpum/compdir/file1 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/test/functional/fixtures/wildpum/compdir/file1 diff --git a/test/functional/fixtures/wildpum/compdir/file2 b/test/functional/fixtures/wildpum/compdir/file2 new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/test/functional/fixtures/wildpum/compdir/file2 diff --git a/test/functional/ui/popupmenu_spec.lua b/test/functional/ui/popupmenu_spec.lua index 7b0005bcf1..f148e2643f 100644 --- a/test/functional/ui/popupmenu_spec.lua +++ b/test/functional/ui/popupmenu_spec.lua @@ -7,7 +7,6 @@ local insert = helpers.insert local meths = helpers.meths local command = helpers.command local funcs = helpers.funcs -local get_pathsep = helpers.get_pathsep local eq = helpers.eq local pcall_err = helpers.pcall_err local exec_lua = helpers.exec_lua @@ -1785,6 +1784,8 @@ describe('builtin popupmenu', function() screen:try_resize(32,10) command('set wildmenu') command('set wildoptions=pum') + command('set shellslash') + command("cd test/functional/fixtures/wildpum") feed(':sign ') screen:expect([[ @@ -1800,7 +1801,7 @@ describe('builtin popupmenu', function() :sign ^ | ]]) - feed('<tab>') + feed('<Tab>') screen:expect([[ | {1:~ }| @@ -1814,21 +1815,199 @@ describe('builtin popupmenu', function() :sign define^ | ]]) - feed('<left>') + feed('<Right><Right>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }{n: define }{1: }| + {1:~ }{n: jump }{1: }| + {1:~ }{s: list }{1: }| + {1:~ }{n: place }{1: }| + {1:~ }{n: undefine }{1: }| + {1:~ }{n: unplace }{1: }| + :sign list^ | + ]]) + + feed('<C-N>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }{n: define }{1: }| + {1:~ }{n: jump }{1: }| + {1:~ }{n: list }{1: }| + {1:~ }{s: place }{1: }| + {1:~ }{n: undefine }{1: }| + {1:~ }{n: unplace }{1: }| + :sign place^ | + ]]) + + feed('<C-P>') screen:expect([[ | {1:~ }| {1:~ }| {1:~ }{n: define }{1: }| {1:~ }{n: jump }{1: }| + {1:~ }{s: list }{1: }| + {1:~ }{n: place }{1: }| + {1:~ }{n: undefine }{1: }| + {1:~ }{n: unplace }{1: }| + :sign list^ | + ]]) + + feed('<Left>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }{n: define }{1: }| + {1:~ }{s: jump }{1: }| {1:~ }{n: list }{1: }| {1:~ }{n: place }{1: }| {1:~ }{n: undefine }{1: }| {1:~ }{n: unplace }{1: }| + :sign jump^ | + ]]) + + -- pressing <C-E> should end completion and go back to the original match + feed('<C-E>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| :sign ^ | ]]) - feed('<left>') + -- pressing <C-Y> should select the current match and end completion + feed('<Tab><C-P><C-P><C-Y>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :sign unplace^ | + ]]) + + -- showing popup menu in different columns in the cmdline + feed('<C-U>sign define <Tab>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }{s: culhl= }{1: }| + {1:~ }{n: icon= }{1: }| + {1:~ }{n: linehl= }{1: }| + {1:~ }{n: numhl= }{1: }| + {1:~ }{n: text= }{1: }| + {1:~ }{n: texthl= }{1: }| + :sign define culhl=^ | + ]]) + + feed('<Space><Tab>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }{s: culhl= }{1: }| + {1:~ }{n: icon= }{1: }| + {1:~ }{n: linehl= }{1: }| + {1:~ }{n: numhl= }{1: }| + {1:~ }{n: text= }{1: }| + {1:~ }{n: texthl= }{1: }| + :sign define culhl= culhl=^ | + ]]) + + feed('<C-U>e Xdi<Tab><Tab>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }{s: XdirA/ }{1: }| + {1:~ }{n: XfileA }{1: }| + :e Xdir/XdirA/^ | + ]]) + + -- Pressing <Down> on a directory name should go into that directory + feed('<Down>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }{s: XdirB/ }{1: }| + {1:~ }{n: XfileB }{1: }| + :e Xdir/XdirA/XdirB/^ | + ]]) + + -- Pressing <Up> on a directory name should go to the parent directory + feed('<Up>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }{s: XdirA/ }{1: }| + {1:~ }{n: XfileA }{1: }| + :e Xdir/XdirA/^ | + ]]) + + -- Pressing <C-A> when the popup menu is displayed should list all the + -- matches and remove the popup menu + feed(':<C-U>sign <Tab><C-A>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {4: }| + :sign define jump list place und| + efine unplace^ | + ]]) + + -- Pressing <C-D> when the popup menu is displayed should remove the popup + -- menu + feed('<C-U>sign <Tab><C-D>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {4: }| + :sign define | + define | + :sign define^ | + ]]) + + -- Pressing <S-Tab> should open the popup menu with the last entry selected + feed('<C-U><CR>:sign <S-Tab><C-P>') screen:expect([[ | {1:~ }| @@ -1837,23 +2016,146 @@ describe('builtin popupmenu', function() {1:~ }{n: jump }{1: }| {1:~ }{n: list }{1: }| {1:~ }{n: place }{1: }| + {1:~ }{s: undefine }{1: }| + {1:~ }{n: unplace }{1: }| + :sign undefine^ | + ]]) + + -- Pressing <Esc> should close the popup menu and cancel the cmd line + feed('<C-U><CR>:sign <Tab><Esc>') + screen:expect([[ + ^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + | + ]]) + + -- Typing a character when the popup is open, should close the popup + feed(':sign <Tab>x') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :sign definex^ | + ]]) + + -- When the popup is open, entering the cmdline window should close the popup + feed('<C-U>sign <Tab><C-F>') + screen:expect([[ + | + {3:[No Name] }| + {1::}sign define | + {1::}sign define^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {4:[Command Line] }| + :sign define | + ]]) + feed(':q<CR>') + + -- After the last popup menu item, <C-N> should show the original string + feed(':sign u<Tab><C-N><C-N>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| {1:~ }{n: undefine }{1: }| - {1:~ }{s: unplace }{1: }| - :sign unplace^ | + {1:~ }{n: unplace }{1: }| + :sign u^ | ]]) - feed('x') + -- Use the popup menu for the command name + feed('<C-U>bu<Tab>') screen:expect([[ | {1:~ }| {1:~ }| {1:~ }| {1:~ }| + {s: bufdo }{1: }| + {n: buffer }{1: }| + {n: buffers }{1: }| + {n: bunload }{1: }| + :bufdo^ | + ]]) + + -- Pressing <BS> should remove the popup menu and erase the last character + feed('<C-E><C-U>sign <Tab><BS>') + screen:expect([[ + | {1:~ }| {1:~ }| {1:~ }| {1:~ }| - :sign unplacex^ | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :sign defin^ | + ]]) + + -- Pressing <C-W> should remove the popup menu and erase the previous word + feed('<C-E><C-U>sign <Tab><C-W>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :sign ^ | + ]]) + + -- Pressing <C-U> should remove the popup menu and erase the entire line + feed('<C-E><C-U>sign <Tab><C-U>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :^ | + ]]) + + -- Using <C-E> to cancel the popup menu and then pressing <Up> should recall + -- the cmdline from history + feed('sign xyz<Esc>:sign <Tab><C-E><Up>') + screen:expect([[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + :sign xyz^ | ]]) feed('<esc>') @@ -1932,7 +2234,6 @@ describe('builtin popupmenu', function() feed('<esc>') command("close") command('set wildmode=full') - command("cd test/functional/fixtures/") feed(':e compdir/<tab>') screen:expect([[ | @@ -1949,7 +2250,7 @@ describe('builtin popupmenu', function() {1:~ }| {1:~ }{s: file1 }{1: }| {1:~ }{n: file2 }{1: }| - :e compdir]]..get_pathsep()..[[file1^ | + :e compdir/file1^ | ]]) end) @@ -2007,7 +2308,9 @@ describe('builtin popupmenu', function() command('set wildoptions=pum') command('set wildmode=longest,full') - feed(':sign u<tab>') + -- With 'wildmode' set to 'longest,full', completing a match should display + -- the longest match, the wildmenu should not be displayed. + feed(':sign u<Tab>') screen:expect{grid=[[ | {1:~ }| @@ -2020,7 +2323,8 @@ describe('builtin popupmenu', function() ]]} eq(0, funcs.wildmenumode()) - feed('<tab>') + -- pressing <Tab> should display the wildmenu + feed('<Tab>') screen:expect{grid=[[ | {1:~ }| @@ -2032,6 +2336,19 @@ describe('builtin popupmenu', function() :sign undefine^ | ]]} eq(1, funcs.wildmenumode()) + + -- pressing <Tab> second time should select the next entry in the menu + feed('<Tab>') + screen:expect{grid=[[ + | + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }| + {1:~ }{n: undefine }{1: }| + {1:~ }{s: unplace }{1: }| + :sign unplace^ | + ]]} end) it("'pumblend' RGB-color", function() |