diff options
Diffstat (limited to 'src')
65 files changed, 2731 insertions, 762 deletions
diff --git a/src/clint.py b/src/clint.py index 8dc41fdb93..9b4128a0c9 100755 --- a/src/clint.py +++ b/src/clint.py @@ -350,7 +350,7 @@ def IsErrorInSuppressedErrorsList(category, linenum): category: str, the category of the error. linenum: int, the current line number. Returns: - bool, True iff the error should be suppressed due to presense in + bool, True iff the error should be suppressed due to presence in suppressions file. """ return (category, linenum) in _error_suppressions_2 diff --git a/src/nvim/api/buffer.c b/src/nvim/api/buffer.c index 2811a2da12..c8dd85b39d 100644 --- a/src/nvim/api/buffer.c +++ b/src/nvim/api/buffer.c @@ -7,6 +7,7 @@ #include <stdint.h> #include <stdlib.h> #include <limits.h> + #include <lauxlib.h> #include "nvim/api/buffer.h" @@ -1285,6 +1286,10 @@ Array nvim_buf_get_extmarks(Buffer buffer, Integer ns_id, /// - hl_group : name of the highlight group used to highlight /// this mark. /// - virt_text : virtual text to link to this mark. +/// - ephemeral : for use with |nvim_set_decoration_provider| +/// callbacks. The mark will only be used for the current +/// redraw cycle, and not be permantently stored in the +/// buffer. /// @param[out] err Error details, if any /// @return Id of the created/updated extmark Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, @@ -1318,6 +1323,8 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, return 0; } + bool ephemeral = false; + uint64_t id = 0; int line2 = -1, hl_id = 0; colnr_T col2 = 0; @@ -1386,6 +1393,11 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, if (ERROR_SET(err)) { goto error; } + } else if (strequal("ephemeral", k.data)) { + ephemeral = api_is_truthy(*v, "ephemeral", false, err); + if (ERROR_SET(err)) { + goto error; + } } else { api_set_error(err, kErrorTypeValidation, "unexpected key: %s", k.data); goto error; @@ -1410,17 +1422,33 @@ Integer nvim_buf_set_extmark(Buffer buffer, Integer ns_id, col2 = 0; } - Decoration *decor = NULL; - if (kv_size(virt_text)) { - decor = xcalloc(1, sizeof(*decor)); - decor->hl_id = hl_id; - decor->virt_text = virt_text; - } else if (hl_id) { - decor = decoration_hl(hl_id); - } + // TODO(bfredl): synergize these two branches even more + if (ephemeral && redrawn_win && redrawn_win->w_buffer == buf) { + int attr_id = hl_id > 0 ? syn_id2attr(hl_id) : 0; + VirtText *vt_allocated = NULL; + if (kv_size(virt_text)) { + vt_allocated = xmalloc(sizeof *vt_allocated); + *vt_allocated = virt_text; + } + decorations_add_ephemeral(attr_id, (int)line, (colnr_T)col, + (int)line2, (colnr_T)col2, vt_allocated); + } else { + if (ephemeral) { + api_set_error(err, kErrorTypeException, "not yet implemented"); + goto error; + } + Decoration *decor = NULL; + if (kv_size(virt_text)) { + decor = xcalloc(1, sizeof(*decor)); + decor->hl_id = hl_id; + decor->virt_text = virt_text; + } else if (hl_id) { + decor = decoration_hl(hl_id); + } - id = extmark_set(buf, (uint64_t)ns_id, id, - (int)line, (colnr_T)col, line2, col2, decor, kExtmarkNoUndo); + id = extmark_set(buf, (uint64_t)ns_id, id, (int)line, (colnr_T)col, + line2, col2, decor, kExtmarkNoUndo); + } return (Integer)id; diff --git a/src/nvim/api/private/helpers.c b/src/nvim/api/private/helpers.c index e0d5862e02..84517c99fc 100644 --- a/src/nvim/api/private/helpers.c +++ b/src/nvim/api/private/helpers.c @@ -1619,14 +1619,28 @@ free_exit: return virt_text; } -bool api_is_truthy(Object obj, const char *what, Error *err) +bool api_is_truthy(Object obj, const char *what, bool nil_truthy, Error *err) { if (obj.type == kObjectTypeBoolean) { return obj.data.boolean; } else if (obj.type == kObjectTypeInteger) { - return obj.data.integer; // C semantics: non-zery int is true + return obj.data.integer; // C semantics: non-zero int is true + } else if (obj.type == kObjectTypeNil) { + return nil_truthy; // caller decides what NIL (missing retval in lua) means } else { api_set_error(err, kErrorTypeValidation, "%s is not an boolean", what); return false; } } + +const char *describe_ns(NS ns_id) +{ + String name; + handle_T id; + map_foreach(namespace_ids, name, id, { + if ((NS)id == ns_id && name.size) { + return name.data; + } + }) + return "(UNKNOWN PLUGIN)"; +} diff --git a/src/nvim/api/ui_events.in.h b/src/nvim/api/ui_events.in.h index ef5e90bf5c..e934d5dc92 100644 --- a/src/nvim/api/ui_events.in.h +++ b/src/nvim/api/ui_events.in.h @@ -1,7 +1,7 @@ #ifndef NVIM_API_UI_EVENTS_IN_H #define NVIM_API_UI_EVENTS_IN_H -// This file is not compiled, just parsed for definitons +// This file is not compiled, just parsed for definitions #ifdef INCLUDE_GENERATED_DECLARATIONS # error "don't include this file, include nvim/ui.h" #endif @@ -44,7 +44,7 @@ void option_set(String name, Object value) void stop(void) FUNC_API_NOEXPORT; -// First revison of the grid protocol, used by default +// First revision of the grid protocol, used by default void update_fg(Integer fg) FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY; void update_bg(Integer bg) @@ -68,7 +68,7 @@ void set_scroll_region(Integer top, Integer bot, Integer left, Integer right) void scroll(Integer count) FUNC_API_SINCE(3) FUNC_API_REMOTE_ONLY; -// Second revison of the grid protocol, used with ext_linegrid ui option +// Second revision of the grid protocol, used with ext_linegrid ui option void default_colors_set(Integer rgb_fg, Integer rgb_bg, Integer rgb_sp, Integer cterm_fg, Integer cterm_bg) FUNC_API_SINCE(4) FUNC_API_REMOTE_IMPL; @@ -91,7 +91,7 @@ void grid_scroll(Integer grid, Integer top, Integer bot, void grid_destroy(Integer grid) FUNC_API_SINCE(6) FUNC_API_REMOTE_ONLY; -// For perfomance and simplicity, we use the dense screen representation +// For performance and simplicity, we use the dense screen representation // in internal code, such as compositor and TUI. The remote_ui module will // translate this in to the public grid_line format. void raw_line(Integer grid, Integer row, Integer startcol, diff --git a/src/nvim/api/vim.c b/src/nvim/api/vim.c index 1de1472fc2..876b052a8e 100644 --- a/src/nvim/api/vim.c +++ b/src/nvim/api/vim.c @@ -2604,166 +2604,135 @@ Array nvim__inspect_cell(Integer grid, Integer row, Integer col, Error *err) return ret; } -/// Set attrs in nvim__buf_set_lua_hl callbacks -/// -/// TODO(bfredl): This is rather pedestrian. The final -/// interface should probably be derived from a reformed -/// bufhl/virttext interface with full support for multi-line -/// ranges etc -void nvim__put_attr(Integer line, Integer col, Dictionary opts, Error *err) - FUNC_API_LUA_ONLY -{ - if (!lua_attr_active) { - return; - } - int line2 = -1, hl_id = 0; - colnr_T col2 = 0; - VirtText virt_text = KV_INITIAL_VALUE; - for (size_t i = 0; i < opts.size; i++) { - String k = opts.items[i].key; - Object *v = &opts.items[i].value; - if (strequal("end_line", k.data)) { - if (v->type != kObjectTypeInteger) { - api_set_error(err, kErrorTypeValidation, - "end_line is not an integer"); - goto error; - } - if (v->data.integer < 0) { - api_set_error(err, kErrorTypeValidation, - "end_line value outside range"); - goto error; - } - - line2 = (int)v->data.integer; - } else if (strequal("end_col", k.data)) { - if (v->type != kObjectTypeInteger) { - api_set_error(err, kErrorTypeValidation, - "end_col is not an integer"); - goto error; - } - if (v->data.integer < 0 || v->data.integer > MAXCOL) { - api_set_error(err, kErrorTypeValidation, - "end_col value outside range"); - goto error; - } - - col2 = (colnr_T)v->data.integer; - } else if (strequal("hl_group", k.data)) { - String hl_group; - switch (v->type) { - case kObjectTypeString: - hl_group = v->data.string; - hl_id = syn_check_group( - (char_u *)(hl_group.data), - (int)hl_group.size); - break; - case kObjectTypeInteger: - hl_id = (int)v->data.integer; - break; - default: - api_set_error(err, kErrorTypeValidation, - "hl_group is not valid."); - goto error; - } - } else if (strequal("virt_text", k.data)) { - if (v->type != kObjectTypeArray) { - api_set_error(err, kErrorTypeValidation, - "virt_text is not an Array"); - goto error; - } - virt_text = parse_virt_text(v->data.array, err); - if (ERROR_SET(err)) { - goto error; - } - } else { - api_set_error(err, kErrorTypeValidation, "unexpected key: %s", k.data); - goto error; - } - } - if (col2 && line2 < 0) { - line2 = (int)line; - } - - int attr = hl_id ? syn_id2attr((int)hl_id) : 0; - if (attr == 0 && !kv_size(virt_text)) { - return; - } - - VirtText *v = xmalloc(sizeof(*v)); - *v = virt_text; // LeakSanitizer be sad - decorations_add_luahl_attr(attr, (int)line, (colnr_T)col, - (int)line2, (colnr_T)col2, v); -error: - return; -} - void nvim__screenshot(String path) FUNC_API_FAST { ui_call_screenshot(path); } -static void clear_luahl(bool force) +static DecorationProvider *get_provider(NS ns_id, bool force) { - if (luahl_active || force) { - api_free_luaref(luahl_start); - api_free_luaref(luahl_win); - api_free_luaref(luahl_line); - api_free_luaref(luahl_end); + ssize_t i; + for (i = 0; i < (ssize_t)kv_size(decoration_providers); i++) { + DecorationProvider *item = &kv_A(decoration_providers, i); + if (item->ns_id == ns_id) { + return item; + } else if (item->ns_id > ns_id) { + break; + } } - luahl_start = LUA_NOREF; - luahl_win = LUA_NOREF; - luahl_line = LUA_NOREF; - luahl_end = LUA_NOREF; - luahl_active = false; -} -/// Unstabilized interface for defining syntax hl in lua. -/// -/// This is not yet safe for general use, lua callbacks will need to -/// be restricted, like textlock and probably other stuff. -/// -/// The API on_line/nvim__put_attr is quite raw and not intended to be the -/// final shape. Ideally this should operate on chunks larger than a single -/// line to reduce interpreter overhead, and generate annotation objects -/// (bufhl/virttext) on the fly but using the same representation. -void nvim__set_luahl(DictionaryOf(LuaRef) opts, Error *err) - FUNC_API_LUA_ONLY -{ - redraw_later(NOT_VALID); - clear_luahl(false); + if (!force) { + return NULL; + } + + for (ssize_t j = (ssize_t)kv_size(decoration_providers)-1; j >= i; j++) { + // allocates if needed: + (void)kv_a(decoration_providers, (size_t)j+1); + kv_A(decoration_providers, (size_t)j+1) = kv_A(decoration_providers, j); + } + DecorationProvider *item = &kv_a(decoration_providers, (size_t)i); + *item = DECORATION_PROVIDER_INIT(ns_id); + + return item; +} + +static void clear_provider(DecorationProvider *p) +{ + NLUA_CLEAR_REF(p->redraw_start); + NLUA_CLEAR_REF(p->redraw_buf); + NLUA_CLEAR_REF(p->redraw_win); + NLUA_CLEAR_REF(p->redraw_line); + NLUA_CLEAR_REF(p->redraw_end); + p->active = false; +} + +/// Set or change decoration provider for a namespace +/// +/// This is a very general purpose interface for having lua callbacks +/// being triggered during the redraw code. +/// +/// The expected usage is to set extmarks for the currently +/// redrawn buffer. |nvim_buf_set_extmark| can be called to add marks +/// on a per-window or per-lines basis. Use the `ephemeral` key to only +/// use the mark for the current screen redraw (the callback will be called +/// again for the next redraw ). +/// +/// Note: this function should not be called often. Rather, the callbacks +/// themselves can be used to throttle unneeded callbacks. the `on_start` +/// callback can return `false` to disable the provider until the next redraw. +/// Similarily, return `false` in `on_win` will skip the `on_lines` calls +/// for that window (but any extmarks set in `on_win` will still be used). +/// A plugin managing multiple sources of decorations should ideally only set +/// one provider, and merge the sources internally. You can use multiple `ns_id` +/// for the extmarks set/modified inside the callback anyway. +/// +/// Note: doing anything other than setting extmarks is considered experimental. +/// Doing things like changing options are not expliticly forbidden, but is +/// likely to have unexpected consequences (such as 100% CPU consumption). +/// doing `vim.rpcnotify` should be OK, but `vim.rpcrequest` is quite dubious +/// for the moment. +/// +/// @param ns_id Namespace id from |nvim_create_namespace()| +/// @param opts Callbacks invoked during redraw: +/// - on_start: called first on each screen redraw +/// ["start", tick] +/// - on_buf: called for each buffer being redrawn (before window +/// callbacks) +/// ["buf", bufnr, tick] +/// - on_win: called when starting to redraw a specific window. +/// ["win", winid, bufnr, topline, botline_guess] +/// - on_line: called for each buffer line being redrawn. (The +/// interation with fold lines is subject to change) +/// ["win", winid, bufnr, row] +/// - on_end: called at the end of a redraw cycle +/// ["end", tick] +void nvim_set_decoration_provider(Integer ns_id, DictionaryOf(LuaRef) opts, + Error *err) + FUNC_API_SINCE(7) FUNC_API_LUA_ONLY +{ + DecorationProvider *p = get_provider((NS)ns_id, true); + clear_provider(p); + + // regardless of what happens, it seems good idea to redraw + redraw_later(NOT_VALID); // TODO(bfredl): too soon? + + struct { + const char *name; + LuaRef *dest; + } cbs[] = { + { "on_start", &p->redraw_start }, + { "on_buf", &p->redraw_buf }, + { "on_win", &p->redraw_win }, + { "on_line", &p->redraw_line }, + { "on_end", &p->redraw_end }, + { NULL, NULL }, + }; for (size_t i = 0; i < opts.size; i++) { String k = opts.items[i].key; Object *v = &opts.items[i].value; - if (strequal("on_start", k.data)) { - if (v->type != kObjectTypeLuaRef) { - api_set_error(err, kErrorTypeValidation, "callback is not a function"); - goto error; - } - luahl_start = v->data.luaref; - v->data.luaref = LUA_NOREF; - } else if (strequal("on_win", k.data)) { - if (v->type != kObjectTypeLuaRef) { - api_set_error(err, kErrorTypeValidation, "callback is not a function"); - goto error; - } - luahl_win = v->data.luaref; - v->data.luaref = LUA_NOREF; - } else if (strequal("on_line", k.data)) { - if (v->type != kObjectTypeLuaRef) { - api_set_error(err, kErrorTypeValidation, "callback is not a function"); - goto error; + size_t j; + for (j = 0; cbs[j].name; j++) { + if (strequal(cbs[j].name, k.data)) { + if (v->type != kObjectTypeLuaRef) { + api_set_error(err, kErrorTypeValidation, + "%s is not a function", cbs[j].name); + goto error; + } + *(cbs[j].dest) = v->data.luaref; + v->data.luaref = LUA_NOREF; + break; } - luahl_line = v->data.luaref; - v->data.luaref = LUA_NOREF; - } else { + } + if (!cbs[j].name) { api_set_error(err, kErrorTypeValidation, "unexpected key: %s", k.data); goto error; } } - luahl_active = true; + + p->active = true; return; error: - clear_luahl(true); + clear_provider(p); } diff --git a/src/nvim/buffer.c b/src/nvim/buffer.c index ec633dcc26..0fda66105f 100644 --- a/src/nvim/buffer.c +++ b/src/nvim/buffer.c @@ -5397,18 +5397,12 @@ bool buf_hide(const buf_T *const buf) char_u *buf_spname(buf_T *buf) { if (bt_quickfix(buf)) { - win_T *win; - tabpage_T *tp; - - /* - * For location list window, w_llist_ref points to the location list. - * For quickfix window, w_llist_ref is NULL. - */ - if (find_win_for_buf(buf, &win, &tp) && win->w_llist_ref != NULL) { - return (char_u *)_(msg_loclist); - } else { + // Differentiate between the quickfix and location list buffers using + // the buffer number stored in the global quickfix stack. + if (buf->b_fnum == qf_stack_get_bufnr()) { return (char_u *)_(msg_qflist); } + return (char_u *)_(msg_loclist); } // There is no _file_ when 'buftype' is "nofile", b_sfname // contains the name as specified by the user. diff --git a/src/nvim/buffer_defs.h b/src/nvim/buffer_defs.h index ea968d9592..1223f2bdab 100644 --- a/src/nvim/buffer_defs.h +++ b/src/nvim/buffer_defs.h @@ -91,6 +91,7 @@ typedef struct { #define BF_READERR 0x40 // got errors while reading the file #define BF_DUMMY 0x80 // dummy buffer, only used internally #define BF_PRESERVED 0x100 // ":preserve" was used +#define BF_SYN_SET 0x200 // 'syntax' option was set // Mask to check for flags that prevent normal writing #define BF_WRITE_MASK (BF_NOTEDITED + BF_NEW + BF_READERR) @@ -544,6 +545,9 @@ struct file_buffer { long b_mod_xlines; // number of extra buffer lines inserted; // negative when lines were deleted wininfo_T *b_wininfo; // list of last used info for each window + int b_mod_tick_syn; // last display tick syntax was updated + int b_mod_tick_deco; // last display tick decoration providers + // where invoked long b_mtime; // last change time of original file long b_mtime_read; // last change time when reading diff --git a/src/nvim/edit.c b/src/nvim/edit.c index 1e149da1dc..de2346a9d8 100644 --- a/src/nvim/edit.c +++ b/src/nvim/edit.c @@ -1254,14 +1254,6 @@ check_pum: normalchar: // Insert a normal character. - if (mod_mask == MOD_MASK_ALT || mod_mask == MOD_MASK_META) { - // Unmapped ALT/META chord behaves like ESC+c. #8213 - stuffcharReadbuff(ESC); - stuffcharReadbuff(s->c); - u_sync(false); - break; - } - if (!p_paste) { // Trigger InsertCharPre. char_u *str = do_insert_char_pre(s->c); diff --git a/src/nvim/eval.c b/src/nvim/eval.c index 24192dfefa..a2490be355 100644 --- a/src/nvim/eval.c +++ b/src/nvim/eval.c @@ -3802,8 +3802,9 @@ static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string) */ for (;; ) { op = **arg; - if (op != '*' && op != '/' && op != '%') + if (op != '*' && op != '/' && op != '%') { break; + } if (evaluate) { if (rettv->v_type == VAR_FLOAT) { @@ -3905,6 +3906,7 @@ static int eval6(char_u **arg, typval_T *rettv, int evaluate, int want_string) // (expression) nested expression // [expr, expr] List // {key: val, key: val} Dictionary +// #{key: val, key: val} Dictionary with literal keys // // Also handle: // ! in front logical NOT @@ -4012,11 +4014,21 @@ static int eval7( case '[': ret = get_list_tv(arg, rettv, evaluate); break; + // Dictionary: #{key: val, key: val} + case '#': + if ((*arg)[1] == '{') { + (*arg)++; + ret = dict_get_tv(arg, rettv, evaluate, true); + } else { + ret = NOTDONE; + } + break; + // Lambda: {arg, arg -> expr} - // Dictionary: {key: val, key: val} + // Dictionary: {'key': val, 'key': val} case '{': ret = get_lambda_tv(arg, rettv, evaluate); if (ret == NOTDONE) { - ret = dict_get_tv(arg, rettv, evaluate); + ret = dict_get_tv(arg, rettv, evaluate, false); } break; @@ -5347,11 +5359,31 @@ static inline bool set_ref_dict(dict_T *dict, int copyID) return false; } -/* - * Allocate a variable for a Dictionary and fill it from "*arg". - * Return OK or FAIL. Returns NOTDONE for {expr}. - */ -static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate) + +// Get the key for *{key: val} into "tv" and advance "arg". +// Return FAIL when there is no valid key. +static int get_literal_key(char_u **arg, typval_T *tv) + FUNC_ATTR_NONNULL_ALL +{ + char_u *p; + + if (!ASCII_ISALNUM(**arg) && **arg != '_' && **arg != '-') { + return FAIL; + } + for (p = *arg; ASCII_ISALNUM(*p) || *p == '_' || *p == '-'; p++) { + } + tv->v_type = VAR_STRING; + tv->vval.v_string = vim_strnsave(*arg, (int)(p - *arg)); + + *arg = skipwhite(p); + return OK; +} + +// Allocate a variable for a Dictionary and fill it from "*arg". +// "literal" is true for *{key: val} +// Return OK or FAIL. Returns NOTDONE for {expr}. +static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate, + bool literal) { dict_T *d = NULL; typval_T tvkey; @@ -5385,7 +5417,9 @@ static int dict_get_tv(char_u **arg, typval_T *rettv, int evaluate) *arg = skipwhite(*arg + 1); while (**arg != '}' && **arg != NUL) { - if (eval1(arg, &tvkey, evaluate) == FAIL) { // recursive! + if ((literal + ? get_literal_key(arg, &tvkey) + : eval1(arg, &tvkey, evaluate)) == FAIL) { // recursive! goto failret; } if (**arg != ':') { diff --git a/src/nvim/eval.lua b/src/nvim/eval.lua index 372c950825..11f6a350e4 100644 --- a/src/nvim/eval.lua +++ b/src/nvim/eval.lua @@ -371,7 +371,7 @@ return { tolower={args=1}, toupper={args=1}, tr={args=3}, - trim={args={1,2}}, + trim={args={1,3}}, trunc={args=1, func="float_op_wrapper", data="&trunc"}, type={args=1}, undofile={args=1}, diff --git a/src/nvim/eval/funcs.c b/src/nvim/eval/funcs.c index 83ad948a93..861743eb7d 100644 --- a/src/nvim/eval/funcs.c +++ b/src/nvim/eval/funcs.c @@ -7668,7 +7668,7 @@ static int searchpair_cmn(typval_T *argvars, pos_T *match_pos) } retval = do_searchpair( - (char_u *)spat, (char_u *)mpat, (char_u *)epat, dir, skip, + spat, mpat, epat, dir, skip, flags, match_pos, lnum_stop, time_limit); theend: @@ -7712,9 +7712,9 @@ static void f_searchpairpos(typval_T *argvars, typval_T *rettv, FunPtr fptr) */ long do_searchpair( - char_u *spat, // start pattern - char_u *mpat, // middle pattern - char_u *epat, // end pattern + const char *spat, // start pattern + const char *mpat, // middle pattern + const char *epat, // end pattern int dir, // BACKWARD or FORWARD const typval_T *skip, // skip expression int flags, // SP_SETPCMARK and other SP_ values @@ -7722,6 +7722,7 @@ do_searchpair( linenr_T lnum_stop, // stop at this line if not zero long time_limit // stop after this many msec ) + FUNC_ATTR_NONNULL_ARG(1, 2, 3) { char_u *save_cpo; char_u *pat, *pat2 = NULL, *pat3 = NULL; @@ -7736,8 +7737,6 @@ do_searchpair( bool use_skip = false; int options = SEARCH_KEEP; proftime_T tm; - size_t pat2_len; - size_t pat3_len; // Make 'cpoptions' empty, the 'l' flag should not be used here. save_cpo = p_cpo; @@ -7748,9 +7747,9 @@ do_searchpair( // Make two search patterns: start/end (pat2, for in nested pairs) and // start/middle/end (pat3, for the top pair). - pat2_len = STRLEN(spat) + STRLEN(epat) + 17; + const size_t pat2_len = strlen(spat) + strlen(epat) + 17; pat2 = xmalloc(pat2_len); - pat3_len = STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 25; + const size_t pat3_len = strlen(spat) + strlen(mpat) + strlen(epat) + 25; pat3 = xmalloc(pat3_len); snprintf((char *)pat2, pat2_len, "\\m\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat); if (*mpat == NUL) { @@ -10824,52 +10823,72 @@ static void f_trim(typval_T *argvars, typval_T *rettv, FunPtr fptr) const char_u *prev; const char_u *p; int c1; + int dir = 0; rettv->v_type = VAR_STRING; + rettv->vval.v_string = NULL; if (head == NULL) { - rettv->vval.v_string = NULL; return; } if (argvars[1].v_type == VAR_STRING) { mask = (const char_u *)tv_get_string_buf_chk(&argvars[1], buf2); + if (argvars[2].v_type != VAR_UNKNOWN) { + bool error = false; + // leading or trailing characters to trim + dir = (int)tv_get_number_chk(&argvars[2], &error); + if (error) { + return; + } + if (dir < 0 || dir > 2) { + emsgf(_(e_invarg2), tv_get_string(&argvars[2])); + return; + } + } } - while (*head != NUL) { - c1 = PTR2CHAR(head); - if (mask == NULL) { - if (c1 > ' ' && c1 != 0xa0) { - break; - } - } else { - for (p = mask; *p != NUL; MB_PTR_ADV(p)) { - if (c1 == PTR2CHAR(p)) { + if (dir == 0 || dir == 1) { + // Trim leading characters + while (*head != NUL) { + c1 = PTR2CHAR(head); + if (mask == NULL) { + if (c1 > ' ' && c1 != 0xa0) { + break; + } + } else { + for (p = mask; *p != NUL; MB_PTR_ADV(p)) { + if (c1 == PTR2CHAR(p)) { + break; + } + } + if (*p == NUL) { break; } } - if (*p == NUL) { - break; - } + MB_PTR_ADV(head); } - MB_PTR_ADV(head); } - for (tail = head + STRLEN(head); tail > head; tail = prev) { - prev = tail; - MB_PTR_BACK(head, prev); - c1 = PTR2CHAR(prev); - if (mask == NULL) { - if (c1 > ' ' && c1 != 0xa0) { - break; - } - } else { - for (p = mask; *p != NUL; MB_PTR_ADV(p)) { - if (c1 == PTR2CHAR(p)) { + tail = head + STRLEN(head); + if (dir == 0 || dir == 2) { + // Trim trailing characters + for (; tail > head; tail = prev) { + prev = tail; + MB_PTR_BACK(head, prev); + c1 = PTR2CHAR(prev); + if (mask == NULL) { + if (c1 > ' ' && c1 != 0xa0) { + break; + } + } else { + for (p = mask; *p != NUL; MB_PTR_ADV(p)) { + if (c1 == PTR2CHAR(p)) { + break; + } + } + if (*p == NUL) { break; } - } - if (*p == NUL) { - break; } } } diff --git a/src/nvim/ex_cmds.c b/src/nvim/ex_cmds.c index 9be6adcd61..bb4e92efc0 100644 --- a/src/nvim/ex_cmds.c +++ b/src/nvim/ex_cmds.c @@ -2497,8 +2497,12 @@ int do_ecmd( new_name = NULL; } set_bufref(&bufref, buf); - if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur) { - // Save all the text, so that the reload can be undone. + + // If the buffer was used before, store the current contents so that + // the reload can be undone. Do not do this if the (empty) buffer is + // being re-used for another file. + if (!(curbuf->b_flags & BF_NEVERLOADED) + && (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)) { // Sync first so that this is a separate undo-able action. u_sync(false); if (u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, true) diff --git a/src/nvim/ex_cmds.lua b/src/nvim/ex_cmds.lua index a01f92df27..d62b00fee1 100644 --- a/src/nvim/ex_cmds.lua +++ b/src/nvim/ex_cmds.lua @@ -337,7 +337,7 @@ return { }, { command='caddexpr', - flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, TRLBAR), + flags=bit.bor(NEEDARG, WORD1, NOTRLCOM), addr_type=ADDR_LINES, func='ex_cexpr', }, @@ -409,7 +409,7 @@ return { }, { command='cexpr', - flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, TRLBAR, BANG), + flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, BANG), addr_type=ADDR_LINES, func='ex_cexpr', }, @@ -447,7 +447,7 @@ return { }, { command='cgetexpr', - flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, TRLBAR), + flags=bit.bor(NEEDARG, WORD1, NOTRLCOM), addr_type=ADDR_LINES, func='ex_cexpr', }, @@ -1299,7 +1299,7 @@ return { }, { command='laddexpr', - flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, TRLBAR), + flags=bit.bor(NEEDARG, WORD1, NOTRLCOM), addr_type=ADDR_LINES, func='ex_cexpr', }, @@ -1389,7 +1389,7 @@ return { }, { command='lexpr', - flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, TRLBAR, BANG), + flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, BANG), addr_type=ADDR_LINES, func='ex_cexpr', }, @@ -1427,7 +1427,7 @@ return { }, { command='lgetexpr', - flags=bit.bor(NEEDARG, WORD1, NOTRLCOM, TRLBAR), + flags=bit.bor(NEEDARG, WORD1, NOTRLCOM), addr_type=ADDR_LINES, func='ex_cexpr', }, diff --git a/src/nvim/ex_cmds2.c b/src/nvim/ex_cmds2.c index 3e169f7a4e..503fd8e0d0 100644 --- a/src/nvim/ex_cmds2.c +++ b/src/nvim/ex_cmds2.c @@ -2058,6 +2058,10 @@ void ex_listdo(exarg_T *eap) // Don't do syntax HL autocommands. Skipping the syntax file is a // great speed improvement. save_ei = au_event_disable(",Syntax"); + + FOR_ALL_BUFFERS(buf) { + buf->b_flags &= ~BF_SYN_SET; + } } if (eap->cmdidx == CMD_windo @@ -2252,9 +2256,32 @@ void ex_listdo(exarg_T *eap) } if (save_ei != NULL) { + buf_T *bnext; + aco_save_T aco; + au_event_restore(save_ei); - apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, - curbuf->b_fname, true, curbuf); + + for (buf_T *buf = firstbuf; buf != NULL; buf = bnext) { + bnext = buf->b_next; + if (buf->b_nwindows > 0 && (buf->b_flags & BF_SYN_SET)) { + buf->b_flags &= ~BF_SYN_SET; + + // buffer was opened while Syntax autocommands were disabled, + // need to trigger them now. + if (buf == curbuf) { + apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, + curbuf->b_fname, true, curbuf); + } else { + aucmd_prepbuf(&aco, buf); + apply_autocmds(EVENT_SYNTAX, buf->b_p_syn, + buf->b_fname, true, buf); + aucmd_restbuf(&aco); + } + + // start over, in case autocommands messed things up. + bnext = firstbuf; + } + } } } diff --git a/src/nvim/ex_docmd.c b/src/nvim/ex_docmd.c index ccaa0b0e52..71ac542323 100644 --- a/src/nvim/ex_docmd.c +++ b/src/nvim/ex_docmd.c @@ -2400,6 +2400,7 @@ int parse_cmd_address(exarg_T *eap, char_u **errormsg, bool silent) } break; case ADDR_TABS_RELATIVE: + case ADDR_OTHER: *errormsg = (char_u *)_(e_invrange); return FAIL; case ADDR_ARGUMENTS: @@ -5057,16 +5058,18 @@ fail: static struct { int expand; char *name; + char *shortname; } addr_type_complete[] = { - { ADDR_ARGUMENTS, "arguments" }, - { ADDR_LINES, "lines" }, - { ADDR_LOADED_BUFFERS, "loaded_buffers" }, - { ADDR_TABS, "tabs" }, - { ADDR_BUFFERS, "buffers" }, - { ADDR_WINDOWS, "windows" }, - { ADDR_QUICKFIX, "quickfix" }, - { -1, NULL } + { ADDR_ARGUMENTS, "arguments", "arg" }, + { ADDR_LINES, "lines", "line" }, + { ADDR_LOADED_BUFFERS, "loaded_buffers", "load" }, + { ADDR_TABS, "tabs", "tab" }, + { ADDR_BUFFERS, "buffers", "buf" }, + { ADDR_WINDOWS, "windows", "win" }, + { ADDR_QUICKFIX, "quickfix", "qf" }, + { ADDR_OTHER, "other", "?" }, + { -1, NULL, NULL } }; /* @@ -5151,7 +5154,7 @@ static void uc_list(char_u *name, size_t name_len) // Put out the title first time if (!found) { MSG_PUTS_TITLE(_("\n Name Args Address " - "Complete Definition")); + "Complete Definition")); } found = true; msg_putchar('\n'); @@ -5237,13 +5240,13 @@ static void uc_list(char_u *name, size_t name_len) do { IObuff[len++] = ' '; - } while (len < 9 - over); + } while (len < 8 - over); // Address Type for (j = 0; addr_type_complete[j].expand != -1; j++) { if (addr_type_complete[j].expand != ADDR_LINES && addr_type_complete[j].expand == cmd->uc_addr_type) { - STRCPY(IObuff + len, addr_type_complete[j].name); + STRCPY(IObuff + len, addr_type_complete[j].shortname); len += (int)STRLEN(IObuff + len); break; } @@ -5262,13 +5265,13 @@ static void uc_list(char_u *name, size_t name_len) do { IObuff[len++] = ' '; - } while (len < 24 - over); + } while (len < 25 - over); IObuff[len] = '\0'; msg_outtrans(IObuff); msg_outtrans_special(cmd->uc_rep, false, - name_len == 0 ? Columns - 46 : 0); + name_len == 0 ? Columns - 47 : 0); if (p_verbose > 0) { last_set_msg(cmd->uc_script_ctx); } @@ -6926,8 +6929,9 @@ void ex_splitview(exarg_T *eap) { win_T *old_curwin = curwin; char_u *fname = NULL; - - + const bool use_tab = eap->cmdidx == CMD_tabedit + || eap->cmdidx == CMD_tabfind + || eap->cmdidx == CMD_tabnew; /* A ":split" in the quickfix window works like ":new". Don't want two * quickfix windows. But it's OK when doing ":tab split". */ @@ -6949,9 +6953,7 @@ void ex_splitview(exarg_T *eap) /* * Either open new tab page or split the window. */ - if (eap->cmdidx == CMD_tabedit - || eap->cmdidx == CMD_tabfind - || eap->cmdidx == CMD_tabnew) { + if (use_tab) { if (win_new_tabpage(cmdmod.tab != 0 ? cmdmod.tab : eap->addr_count == 0 ? 0 : (int)eap->line2 + 1, eap->arg) != FAIL) { do_exedit(eap, old_curwin); @@ -7136,14 +7138,14 @@ static void ex_resize(exarg_T *eap) n = atol((char *)eap->arg); if (cmdmod.split & WSP_VERT) { if (*eap->arg == '-' || *eap->arg == '+') { - n += curwin->w_width; + n += wp->w_width; } else if (n == 0 && eap->arg[0] == NUL) { // default is very wide n = Columns; } win_setwidth_win(n, wp); } else { if (*eap->arg == '-' || *eap->arg == '+') { - n += curwin->w_height; + n += wp->w_height; } else if (n == 0 && eap->arg[0] == NUL) { // default is very high n = Rows-1; } diff --git a/src/nvim/extmark.h b/src/nvim/extmark.h index d394d4d806..101527ab4f 100644 --- a/src/nvim/extmark.h +++ b/src/nvim/extmark.h @@ -1,6 +1,7 @@ #ifndef NVIM_EXTMARK_H #define NVIM_EXTMARK_H +#include "nvim/pos.h" #include "nvim/buffer_defs.h" #include "nvim/extmark_defs.h" #include "nvim/marktree.h" @@ -98,6 +99,8 @@ typedef struct { VirtText *virt_text; } DecorationRedrawState; +EXTERN kvec_t(DecorationProvider) decoration_providers INIT(= KV_INITIAL_VALUE); +EXTERN win_T *redrawn_win INIT(= NULL); // used for ephemeral extmarks #ifdef INCLUDE_GENERATED_DECLARATIONS # include "extmark.h.generated.h" diff --git a/src/nvim/extmark_defs.h b/src/nvim/extmark_defs.h index 76804db848..f5ca0ebbb0 100644 --- a/src/nvim/extmark_defs.h +++ b/src/nvim/extmark_defs.h @@ -1,7 +1,7 @@ #ifndef NVIM_EXTMARK_DEFS_H #define NVIM_EXTMARK_DEFS_H -#include "nvim/pos.h" // for colnr_T +#include "nvim/types.h" #include "nvim/lib/kvec.h" typedef struct { @@ -42,4 +42,18 @@ typedef enum { kExtmarkUndoNoRedo, // Operation should be undoable, but not redoable } ExtmarkOp; +typedef struct { + NS ns_id; + bool active; + LuaRef redraw_start; + LuaRef redraw_buf; + LuaRef redraw_win; + LuaRef redraw_line; + LuaRef redraw_end; +} DecorationProvider; + +#define DECORATION_PROVIDER_INIT(ns_id) (DecorationProvider) \ + { ns_id, false, LUA_NOREF, LUA_NOREF, \ + LUA_NOREF, LUA_NOREF, LUA_NOREF } + #endif // NVIM_EXTMARK_DEFS_H diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c index ed8b72e2be..ad856b588a 100644 --- a/src/nvim/fileio.c +++ b/src/nvim/fileio.c @@ -350,6 +350,7 @@ readfile( char_u *old_b_fname; int using_b_ffname; int using_b_fname; + static char *msg_is_a_directory = N_("is a directory"); au_did_filetype = false; // reset before triggering any autocommands @@ -444,21 +445,31 @@ readfile( else msg_scroll = TRUE; /* don't overwrite previous file message */ - /* - * If the name is too long we might crash further on, quit here. - */ + // If the name is too long we might crash further on, quit here. if (fname != NULL && *fname != NUL) { - if (STRLEN(fname) >= MAXPATHL) { + size_t namelen = STRLEN(fname); + + // If the name is too long we might crash further on, quit here. + if (namelen >= MAXPATHL) { filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0); msg_end(); msg_scroll = msg_save; return FAIL; } + + // If the name ends in a path separator, we can't open it. Check here, + // because reading the file may actually work, but then creating the + // swap file may destroy it! Reported on MS-DOS and Win 95. + if (after_pathsep((const char *)fname, (const char *)(fname + namelen))) { + filemess(curbuf, fname, (char_u *)_(msg_is_a_directory), 0); + msg_end(); + msg_scroll = msg_save; + return FAIL; + } } if (!read_buffer && !read_stdin && !read_fifo) { perm = os_getperm((const char *)fname); -#ifdef UNIX // On Unix it is possible to read a directory, so we have to // check for it before os_open(). if (perm >= 0 && !S_ISREG(perm) // not a regular file ... @@ -474,7 +485,7 @@ readfile( # endif ) { if (S_ISDIR(perm)) { - filemess(curbuf, fname, (char_u *)_("is a directory"), 0); + filemess(curbuf, fname, (char_u *)_(msg_is_a_directory), 0); } else { filemess(curbuf, fname, (char_u *)_("is not a file"), 0); } @@ -482,7 +493,6 @@ readfile( msg_scroll = msg_save; return S_ISDIR(perm) ? NOTDONE : FAIL; } -#endif } /* Set default or forced 'fileformat' and 'binary'. */ @@ -541,13 +551,6 @@ readfile( if (fd < 0) { // cannot open at all msg_scroll = msg_save; -#ifndef UNIX - // On non-unix systems we can't open a directory, check here. - if (os_isdir(fname)) { - filemess(curbuf, sfname, (char_u *)_("is a directory"), 0); - curbuf->b_p_ro = true; // must use "w!" now - } else { -#endif if (!newfile) { return FAIL; } @@ -605,9 +608,6 @@ readfile( return FAIL; } -#ifndef UNIX - } -#endif /* * Only set the 'ro' flag for readonly files the first time they are @@ -3593,7 +3593,7 @@ restore_backup: * the backup file our 'original' file. */ if (*p_pm && dobackup) { - char *org = modname((char *)fname, (char *)p_pm, FALSE); + char *const org = modname((char *)fname, (char *)p_pm, false); if (backup != NULL) { /* diff --git a/src/nvim/generators/gen_ex_cmds.lua b/src/nvim/generators/gen_ex_cmds.lua index 075d8ba9cc..849c82f50e 100644 --- a/src/nvim/generators/gen_ex_cmds.lua +++ b/src/nvim/generators/gen_ex_cmds.lua @@ -24,8 +24,6 @@ local defsfile = io.open(defsfname, 'w') local defs = require('ex_cmds') -local first = true - local byte_a = string.byte('a') local byte_z = string.byte('z') local a_to_z = byte_z - byte_a + 1 @@ -41,8 +39,7 @@ static const uint16_t cmdidxs1[%u] = { -- fit in a byte. local cmdidxs2_out = string.format([[ static const char_u cmdidxs2[%u][%u] = { -/* a b c d e f g h i j k l m n o p q r s t u v w x y z */ - + /* a b c d e f g h i j k l m n o p q r s t u v w x y z */ ]], a_to_z, a_to_z) enumfile:write([[ @@ -50,10 +47,8 @@ typedef enum CMD_index { ]]) defsfile:write(string.format([[ static const int command_count = %u; -]], #defs)) -defsfile:write(string.format([[ static CommandDefinition cmdnames[%u] = { -]], #defs)) +]], #defs, #defs)) local cmds, cmdidxs1, cmdidxs2 = {}, {}, {} for _, cmd in ipairs(defs) do local enumname = cmd.enum or ('CMD_' .. cmd.command) @@ -61,11 +56,6 @@ for _, cmd in ipairs(defs) do if byte_a <= byte_cmd and byte_cmd <= byte_z then table.insert(cmds, cmd.command) end - if first then - first = false - else - defsfile:write(',\n') - end enumfile:write(' ' .. enumname .. ',\n') defsfile:write(string.format([[ [%s] = { @@ -73,7 +63,8 @@ for _, cmd in ipairs(defs) do .cmd_func = (ex_func_T)&%s, .cmd_argt = %uL, .cmd_addr_type = %i - }]], enumname, cmd.command, cmd.func, cmd.flags, cmd.addr_type)) + }, +]], enumname, cmd.command, cmd.func, cmd.flags, cmd.addr_type)) end for i = #cmds, 1, -1 do local cmd = cmds[i] @@ -104,15 +95,14 @@ for i = byte_a, byte_z do end cmdidxs2_out = cmdidxs2_out .. ' },\n' end -defsfile:write([[ - -}; -]]) enumfile:write([[ CMD_SIZE, CMD_USER = -1, CMD_USER_BUF = -2 } cmdidx_T; ]]) -defsfile:write(cmdidxs1_out .. '};\n') -defsfile:write(cmdidxs2_out .. '};\n') +defsfile:write(string.format([[ +}; +%s}; +%s}; +]], cmdidxs1_out, cmdidxs2_out)) diff --git a/src/nvim/getchar.c b/src/nvim/getchar.c index ecb3931b82..cbd9582f8b 100644 --- a/src/nvim/getchar.c +++ b/src/nvim/getchar.c @@ -1528,6 +1528,17 @@ int vgetc(void) c = utf_ptr2char(buf); } + // If mappings are enabled (i.e., not Ctrl-v) and the user directly typed + // something with a meta- or alt- modifier that was not mapped, interpret + // <M-x> as <Esc>x rather than as an unbound meta keypress. #8213 + if (!no_mapping && KeyTyped + && (mod_mask == MOD_MASK_ALT || mod_mask == MOD_MASK_META)) { + mod_mask = 0; + stuffcharReadbuff(c); + u_sync(false); + c = ESC; + } + break; } } diff --git a/src/nvim/globals.h b/src/nvim/globals.h index ddb69fc567..2db8689a56 100644 --- a/src/nvim/globals.h +++ b/src/nvim/globals.h @@ -125,8 +125,6 @@ typedef off_t off_T; EXTERN int mod_mask INIT(= 0x0); // current key modifiers -EXTERN bool lua_attr_active INIT(= false); - // Cmdline_row is the row where the command line starts, just below the // last window. // When the cmdline gets longer than the available space the screen gets @@ -405,12 +403,6 @@ EXTERN int sys_menu INIT(= false); // ('lines' and 'rows') must not be changed. EXTERN int updating_screen INIT(= 0); -EXTERN bool luahl_active INIT(= false); -EXTERN LuaRef luahl_start INIT(= LUA_NOREF); -EXTERN LuaRef luahl_win INIT(= LUA_NOREF); -EXTERN LuaRef luahl_line INIT(= LUA_NOREF); -EXTERN LuaRef luahl_end INIT(= LUA_NOREF); - // All windows are linked in a list. firstwin points to the first entry, // lastwin to the last entry (can be the same as firstwin) and curwin to the // currently active window. diff --git a/src/nvim/log.h b/src/nvim/log.h index d92b4629ed..f2e74df031 100644 --- a/src/nvim/log.h +++ b/src/nvim/log.h @@ -7,6 +7,16 @@ #include "auto/config.h" #include "nvim/macros.h" +// USDT probes. Example invokation: +// NVIM_PROBE(nvim_foo_bar, 1, string.data); +#if defined(HAVE_SYS_SDT_H) +#include <sys/sdt.h> // NOLINT +#define NVIM_PROBE(name, n, ...) STAP_PROBE##n(neovim, name, __VA_ARGS__) +#else +#define NVIM_PROBE(name, n, ...) +#endif + + #define DEBUG_LOG_LEVEL 0 #define INFO_LOG_LEVEL 1 #define WARN_LOG_LEVEL 2 diff --git a/src/nvim/lua/executor.c b/src/nvim/lua/executor.c index 7722f9cdc3..5c665920b5 100644 --- a/src/nvim/lua/executor.c +++ b/src/nvim/lua/executor.c @@ -299,45 +299,66 @@ static int nlua_wait(lua_State *lstate) return luaL_error(lstate, "timeout must be > 0"); } - // Check if condition can be called. - bool is_function = (lua_type(lstate, 2) == LUA_TFUNCTION); + int lua_top = lua_gettop(lstate); - // Check if condition is callable table - if (!is_function && luaL_getmetafield(lstate, 2, "__call") != 0) { - is_function = (lua_type(lstate, -1) == LUA_TFUNCTION); - lua_pop(lstate, 1); - } + // Check if condition can be called. + bool is_function = false; + if (lua_top >= 2 && !lua_isnil(lstate, 2)) { + is_function = (lua_type(lstate, 2) == LUA_TFUNCTION); + + // Check if condition is callable table + if (!is_function && luaL_getmetafield(lstate, 2, "__call") != 0) { + is_function = (lua_type(lstate, -1) == LUA_TFUNCTION); + lua_pop(lstate, 1); + } - if (!is_function) { - lua_pushliteral(lstate, "vim.wait: condition must be a function"); - return lua_error(lstate); + if (!is_function) { + lua_pushliteral( + lstate, + "vim.wait: if passed, condition must be a function"); + return lua_error(lstate); + } } intptr_t interval = 200; - if (lua_gettop(lstate) >= 3) { + if (lua_top >= 3 && !lua_isnil(lstate, 3)) { interval = luaL_checkinteger(lstate, 3); if (interval < 0) { return luaL_error(lstate, "interval must be > 0"); } } + bool fast_only = false; + if (lua_top >= 4) { + fast_only = lua_toboolean(lstate, 4); + } + + MultiQueue *loop_events = fast_only || in_fast_callback > 0 + ? main_loop.fast_events : main_loop.events; + TimeWatcher *tw = xmalloc(sizeof(TimeWatcher)); // Start dummy timer. time_watcher_init(&main_loop, tw, NULL); - tw->events = main_loop.events; + tw->events = loop_events; tw->blockable = true; - time_watcher_start(tw, dummy_timer_due_cb, - (uint64_t)interval, (uint64_t)interval); + time_watcher_start( + tw, + dummy_timer_due_cb, + (uint64_t)interval, + (uint64_t)interval); int pcall_status = 0; bool callback_result = false; LOOP_PROCESS_EVENTS_UNTIL( &main_loop, - main_loop.events, + loop_events, (int)timeout, - nlua_wait_condition(lstate, &pcall_status, &callback_result) || got_int); + is_function ? nlua_wait_condition( + lstate, + &pcall_status, + &callback_result) : false || got_int); // Stop dummy timer time_watcher_stop(tw); diff --git a/src/nvim/lua/executor.h b/src/nvim/lua/executor.h index 6599b44584..1d7a15d9aa 100644 --- a/src/nvim/lua/executor.h +++ b/src/nvim/lua/executor.h @@ -24,6 +24,15 @@ EXTERN LuaRef nlua_empty_dict_ref INIT(= LUA_NOREF); memcpy(&err_->msg[0], s, sizeof(s)); \ } while (0) +#define NLUA_CLEAR_REF(x) \ + do { \ + /* Take the address to avoid double evaluation. #1375 */ \ + if ((x) != LUA_NOREF) { \ + api_free_luaref(x); \ + (x) = LUA_NOREF; \ + } \ + } while (0) + #ifdef INCLUDE_GENERATED_DECLARATIONS # include "lua/executor.h.generated.h" #endif diff --git a/src/nvim/lua/treesitter.c b/src/nvim/lua/treesitter.c index 44e743e911..5258352e72 100644 --- a/src/nvim/lua/treesitter.c +++ b/src/nvim/lua/treesitter.c @@ -43,6 +43,7 @@ static struct luaL_Reg parser_meta[] = { { "edit", parser_edit }, { "tree", parser_tree }, { "set_included_ranges", parser_set_ranges }, + { "included_ranges", parser_get_ranges }, { NULL, NULL } }; @@ -174,6 +175,14 @@ int tslua_add_language(lua_State *L) return luaL_error(L, "Failed to load parser: internal error"); } + uint32_t lang_version = ts_language_version(lang); + if (lang_version < TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION) { + return luaL_error( + L, + "ABI version mismatch : expected %" PRIu32 ", found %" PRIu32, + TREE_SITTER_MIN_COMPATIBLE_LANGUAGE_VERSION, lang_version); + } + pmap_put(cstr_t)(langs, xstrdup(lang_name), lang); lua_pushboolean(L, true); @@ -306,6 +315,26 @@ static const char *input_cb(void *payload, uint32_t byte_index, #undef BUFSIZE } +static void push_ranges(lua_State *L, + const TSRange *ranges, + const unsigned int length) +{ + lua_createtable(L, length, 0); + for (size_t i = 0; i < length; i++) { + lua_createtable(L, 4, 0); + lua_pushinteger(L, ranges[i].start_point.row); + lua_rawseti(L, -2, 1); + lua_pushinteger(L, ranges[i].start_point.column); + lua_rawseti(L, -2, 2); + lua_pushinteger(L, ranges[i].end_point.row); + lua_rawseti(L, -2, 3); + lua_pushinteger(L, ranges[i].end_point.column); + lua_rawseti(L, -2, 4); + + lua_rawseti(L, -2, i+1); + } +} + static int parser_parse(lua_State *L) { TSLua_parser *p = parser_check(L); @@ -355,20 +384,8 @@ static int parser_parse(lua_State *L) tslua_push_tree(L, p->tree); - lua_createtable(L, n_ranges, 0); - for (size_t i = 0; i < n_ranges; i++) { - lua_createtable(L, 4, 0); - lua_pushinteger(L, changed[i].start_point.row); - lua_rawseti(L, -2, 1); - lua_pushinteger(L, changed[i].start_point.column); - lua_rawseti(L, -2, 2); - lua_pushinteger(L, changed[i].end_point.row); - lua_rawseti(L, -2, 3); - lua_pushinteger(L, changed[i].end_point.column); - lua_rawseti(L, -2, 4); + push_ranges(L, changed, n_ranges); - lua_rawseti(L, -2, i+1); - } xfree(changed); return 2; } @@ -466,6 +483,21 @@ static int parser_set_ranges(lua_State *L) return 0; } +static int parser_get_ranges(lua_State *L) +{ + TSLua_parser *p = parser_check(L); + if (!p || !p->parser) { + return 0; + } + + unsigned int len; + const TSRange *ranges = ts_parser_included_ranges(p->parser, &len); + + push_ranges(L, ranges, len); + + return 1; +} + // Tree methods diff --git a/src/nvim/map.c b/src/nvim/map.c index 0c6bad7cb6..ca8ea76333 100644 --- a/src/nvim/map.c +++ b/src/nvim/map.c @@ -183,7 +183,6 @@ MAP_IMPL(uint64_t, ssize_t, SSIZE_INITIALIZER) MAP_IMPL(uint64_t, uint64_t, DEFAULT_INITIALIZER) #define EXTMARK_NS_INITIALIZER { 0, 0 } MAP_IMPL(uint64_t, ExtmarkNs, EXTMARK_NS_INITIALIZER) -#define KVEC_INITIALIZER { .size = 0, .capacity = 0, .items = NULL } #define EXTMARK_ITEM_INITIALIZER { 0, 0, NULL } MAP_IMPL(uint64_t, ExtmarkItem, EXTMARK_ITEM_INITIALIZER) MAP_IMPL(handle_T, ptr_t, DEFAULT_INITIALIZER) diff --git a/src/nvim/marktree.h b/src/nvim/marktree.h index 0c73e75b2e..8a1c564a6d 100644 --- a/src/nvim/marktree.h +++ b/src/nvim/marktree.h @@ -2,6 +2,7 @@ #define NVIM_MARKTREE_H #include <stdint.h> +#include "nvim/pos.h" #include "nvim/map.h" #include "nvim/garray.h" diff --git a/src/nvim/memline.c b/src/nvim/memline.c index 2a75f13cc2..57ed0d6588 100644 --- a/src/nvim/memline.c +++ b/src/nvim/memline.c @@ -1360,7 +1360,7 @@ recover_names ( * Try finding a swap file by simply adding ".swp" to the file name. */ if (*dirp == NUL && file_count + num_files == 0 && fname != NULL) { - char_u *swapname = (char_u *)modname((char *)fname_res, ".swp", TRUE); + char_u *swapname = (char_u *)modname((char *)fname_res, ".swp", true); if (swapname != NULL) { if (os_path_exists(swapname)) { files = xmalloc(sizeof(char_u *)); @@ -1638,10 +1638,11 @@ static int recov_file_names(char_u **names, char_u *path, int prepend_dot) // May also add the file name with a dot prepended, for swap file in same // dir as original file. if (prepend_dot) { - names[num_names] = (char_u *)modname((char *)path, ".sw?", TRUE); - if (names[num_names] == NULL) + names[num_names] = (char_u *)modname((char *)path, ".sw?", true); + if (names[num_names] == NULL) { return num_names; - ++num_names; + } + num_names++; } // Form the normal swap file name pattern by appending ".sw?". @@ -2422,17 +2423,17 @@ int ml_replace(linenr_T lnum, char_u *line, bool copy) return ml_replace_buf(curbuf, lnum, line, copy); } -/* - * Replace line lnum, with buffering, in current buffer. - * - * If "copy" is TRUE, make a copy of the line, otherwise the line has been - * copied to allocated memory already. - * - * Check: The caller of this function should probably also call - * changed_lines(), unless update_screen(NOT_VALID) is used. - * - * return FAIL for failure, OK otherwise - */ +// Replace line "lnum", with buffering, in current buffer. +// +// If "copy" is true, make a copy of the line, otherwise the line has been +// copied to allocated memory already. +// If "copy" is false the "line" may be freed to add text properties! +// Do not use it after calling ml_replace(). +// +// Check: The caller of this function should probably also call +// changed_lines(), unless update_screen(NOT_VALID) is used. +// +// return FAIL for failure, OK otherwise int ml_replace_buf(buf_T *buf, linenr_T lnum, char_u *line, bool copy) { if (line == NULL) /* just checking... */ @@ -3193,6 +3194,12 @@ char_u *makeswapname(char_u *fname, char_u *ffname, buf_T *buf, char_u *dir_name char_u *fname_res = fname; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; + + // Expand symlink in the file name, so that we put the swap file with the + // actual file instead of with the symlink. + if (resolve_symlink(fname, fname_buf) == OK) { + fname_res = fname_buf; + } #endif int len = (int)STRLEN(dir_name); @@ -3201,20 +3208,14 @@ char_u *makeswapname(char_u *fname, char_u *ffname, buf_T *buf, char_u *dir_name && len > 1 && s[-1] == s[-2]) { // Ends with '//', Use Full path r = NULL; - if ((s = (char_u *)make_percent_swname((char *)dir_name, (char *)fname)) != NULL) { - r = (char_u *)modname((char *)s, ".swp", FALSE); + s = (char_u *)make_percent_swname((char *)dir_name, (char *)fname_res); + if (s != NULL) { + r = (char_u *)modname((char *)s, ".swp", false); xfree(s); } return r; } -#ifdef HAVE_READLINK - /* Expand symlink in the file name, so that we put the swap file with the - * actual file instead of with the symlink. */ - if (resolve_symlink(fname, fname_buf) == OK) - fname_res = fname_buf; -#endif - // Prepend a '.' to the swap file name for the current directory. r = (char_u *)modname((char *)fname_res, ".swp", dir_name[0] == '.' && dir_name[1] == NUL); diff --git a/src/nvim/misc1.c b/src/nvim/misc1.c index 6dafbafb3e..1cd9ff2c4d 100644 --- a/src/nvim/misc1.c +++ b/src/nvim/misc1.c @@ -983,7 +983,7 @@ void preserve_exit(void) FOR_ALL_BUFFERS(buf) { if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL) { - mch_errmsg((uint8_t *)"Vim: preserving files...\n"); + mch_errmsg("Vim: preserving files...\r\n"); ui_flush(); ml_sync_all(false, false, true); // preserve all swap files break; @@ -992,7 +992,7 @@ void preserve_exit(void) ml_close_all(false); // close all memfiles, without deleting - mch_errmsg("Vim: Finished.\n"); + mch_errmsg("Vim: Finished.\r\n"); getout(1); } diff --git a/src/nvim/move.c b/src/nvim/move.c index 8a8a639a52..e2a304efa5 100644 --- a/src/nvim/move.c +++ b/src/nvim/move.c @@ -641,7 +641,7 @@ void validate_virtcol_win(win_T *wp) /* * Validate curwin->w_cline_height only. */ -static void validate_cheight(void) +void validate_cheight(void) { check_cursor_moved(curwin); if (!(curwin->w_valid & VALID_CHEIGHT)) { @@ -943,6 +943,9 @@ void curs_columns( redraw_later(SOME_VALID); } + // now w_leftcol is valid, avoid check_cursor_moved() thinking otherwise + curwin->w_valid_leftcol = curwin->w_leftcol; + curwin->w_valid |= VALID_WCOL|VALID_WROW|VALID_VIRTCOL; } diff --git a/src/nvim/option.c b/src/nvim/option.c index 6ae9378236..f9b76750ba 100644 --- a/src/nvim/option.c +++ b/src/nvim/option.c @@ -3438,6 +3438,7 @@ ambw_end: // recursively, to avoid endless recurrence. apply_autocmds(EVENT_SYNTAX, curbuf->b_p_syn, curbuf->b_fname, value_changed || syn_recursive == 1, curbuf); + curbuf->b_flags |= BF_SYN_SET; syn_recursive--; } else if (varp == &(curbuf->b_p_ft)) { // 'filetype' is set, trigger the FileType autocommand diff --git a/src/nvim/os/signal.c b/src/nvim/os/signal.c index bfe230b521..bc774b8ebc 100644 --- a/src/nvim/os/signal.c +++ b/src/nvim/os/signal.c @@ -161,8 +161,8 @@ static void deadly_signal(int signum) WLOG("got signal %d (%s)", signum, signal_name(signum)); - snprintf((char *)IObuff, sizeof(IObuff), "Vim: Caught deadly signal '%s'\n", - signal_name(signum)); + snprintf((char *)IObuff, sizeof(IObuff), "Vim: Caught deadly signal '%s'\r\n", + signal_name(signum)); // Preserve files and exit. preserve_exit(); diff --git a/src/nvim/popupmnu.c b/src/nvim/popupmnu.c index c712762bdf..3beada5bc9 100644 --- a/src/nvim/popupmnu.c +++ b/src/nvim/popupmnu.c @@ -226,6 +226,7 @@ void pum_display(pumitem_T *array, int size, int selected, bool array_changed, pum_above = false; // Leave two lines of context if possible + validate_cheight(); if (curwin->w_cline_row + curwin->w_cline_height - curwin->w_wrow >= 3) { context_lines = 3; } else { diff --git a/src/nvim/quickfix.c b/src/nvim/quickfix.c index 0c9902aaec..4d3d0f5fdf 100644 --- a/src/nvim/quickfix.c +++ b/src/nvim/quickfix.c @@ -73,6 +73,7 @@ struct qfline_S { // There is a stack of error lists. #define LISTCOUNT 10 #define INVALID_QFIDX (-1) +#define INVALID_QFBUFNR (0) /// Quickfix list type. typedef enum @@ -123,6 +124,7 @@ struct qf_info_S { int qf_curlist; // current error list qf_list_T qf_lists[LISTCOUNT]; qfltype_T qfl_type; // type of list + int qf_bufnr; // quickfix window buffer number }; static qf_info_T ql_info; // global quickfix list @@ -239,7 +241,10 @@ static char_u *e_no_more_items = (char_u *)N_("E553: No more items"); static char_u *qf_last_bufname = NULL; static bufref_T qf_last_bufref = { NULL, 0, 0 }; -static char *e_loc_list_changed = N_("E926: Current location list was changed"); +static char *e_current_quickfix_list_was_changed = + N_("E925: Current quickfix list was changed"); +static char *e_current_location_list_was_changed = + N_("E926: Current location list was changed"); // Counter to prevent autocmds from freeing up location lists when they are // still being used. @@ -808,7 +813,7 @@ retry: } break; } - if (STRLEN(IObuff) < IOSIZE - 1 || IObuff[IOSIZE - 1] == '\n') { + if (STRLEN(IObuff) < IOSIZE - 1 || IObuff[IOSIZE - 2] == '\n') { break; } } @@ -1089,6 +1094,7 @@ qf_init_ext( ) FUNC_ATTR_NONNULL_ARG(1) { + qf_list_T *qfl; qfstate_T state = { 0 }; qffields_T fields = { 0 }; qfline_T *old_last = NULL; @@ -1112,15 +1118,16 @@ qf_init_ext( // make place for a new list qf_new_list(qi, qf_title); qf_idx = qi->qf_curlist; + qfl = qf_get_list(qi, qf_idx); } else { // Adding to existing list, use last entry. adding = true; - if (!qf_list_empty(qf_get_list(qi, qf_idx) )) { - old_last = qi->qf_lists[qf_idx].qf_last; + qfl = qf_get_list(qi, qf_idx); + if (!qf_list_empty(qfl)) { + old_last = qfl->qf_last; } } - qf_list_T *qfl = qf_get_list(qi, qf_idx); // Use the local value of 'errorformat' if it's set. if (errorformat == p_efm && tv == NULL && buf && *buf->b_p_efm != NUL) { @@ -1691,6 +1698,28 @@ static void locstack_queue_delreq(qf_info_T *qi) qf_delq_head = q; } +// Return the global quickfix stack window buffer number. +int qf_stack_get_bufnr(void) +{ + return ql_info.qf_bufnr; +} + +// Wipe the quickfix window buffer (if present) for the specified +// quickfix/location list. +static void wipe_qf_buffer(qf_info_T *qi) + FUNC_ATTR_NONNULL_ALL +{ + if (qi->qf_bufnr != INVALID_QFBUFNR) { + buf_T *const qfbuf = buflist_findnr(qi->qf_bufnr); + if (qfbuf != NULL && qfbuf->b_nwindows == 0) { + // If the quickfix buffer is not loaded in any window, then + // wipe the buffer. + close_buffer(NULL, qfbuf, DOBUF_WIPE, false); + qi->qf_bufnr = INVALID_QFBUFNR; + } + } +} + /// Free a location list stack static void ll_free_all(qf_info_T **pqi) { @@ -1710,6 +1739,9 @@ static void ll_free_all(qf_info_T **pqi) if (quickfix_busy > 0) { locstack_queue_delreq(qi); } else { + // If the quickfix window buffer is loaded, then wipe it + wipe_qf_buffer(qi); + for (i = 0; i < qi->qf_listcount; i++) { qf_free(qf_get_list(qi, i)); } @@ -1772,7 +1804,7 @@ static void decr_quickfix_busy(void) void check_quickfix_busy(void) { if (quickfix_busy != 0) { - EMSGN("quickfix_busy not zero on exit: %ld", (long)quickfix_busy); + EMSGN("quickfix_busy not zero on exit: %" PRId64, (int64_t)quickfix_busy); # ifdef ABORT_ON_INTERNAL_ERROR abort(); # endif @@ -1869,6 +1901,7 @@ static qf_info_T *qf_alloc_stack(qfltype_T qfltype) qf_info_T *qi = xcalloc(1, sizeof(qf_info_T)); qi->qf_refcount++; qi->qfl_type = qfltype; + qi->qf_bufnr = INVALID_QFBUFNR; return qi; } @@ -2350,25 +2383,27 @@ static qfline_T *get_prev_valid_entry(qf_list_T *qfl, qfline_T *qf_ptr, /// dir == FORWARD or FORWARD_FILE: next valid entry /// dir == BACKWARD or BACKWARD_FILE: previous valid entry static qfline_T *get_nth_valid_entry(qf_list_T *qfl, int errornr, - qfline_T *qf_ptr, int *qf_index, int dir) + int dir, int *new_qfidx) { + qfline_T *qf_ptr = qfl->qf_ptr; + int qf_idx = qfl->qf_index; qfline_T *prev_qf_ptr; int prev_index; char_u *err = e_no_more_items; while (errornr--) { prev_qf_ptr = qf_ptr; - prev_index = *qf_index; + prev_index = qf_idx; if (dir == FORWARD || dir == FORWARD_FILE) { - qf_ptr = get_next_valid_entry(qfl, qf_ptr, qf_index, dir); + qf_ptr = get_next_valid_entry(qfl, qf_ptr, &qf_idx, dir); } else { - qf_ptr = get_prev_valid_entry(qfl, qf_ptr, qf_index, dir); + qf_ptr = get_prev_valid_entry(qfl, qf_ptr, &qf_idx, dir); } if (qf_ptr == NULL) { qf_ptr = prev_qf_ptr; - *qf_index = prev_index; + qf_idx = prev_index; if (err != NULL) { EMSG(_(err)); return NULL; @@ -2379,14 +2414,16 @@ static qfline_T *get_nth_valid_entry(qf_list_T *qfl, int errornr, err = NULL; } + *new_qfidx = qf_idx; return qf_ptr; } -/// Get n'th (errornr) quickfix entry -static qfline_T *get_nth_entry(qf_list_T *qfl, int errornr, qfline_T *qf_ptr, - int *cur_qfidx) +/// Get n'th (errornr) quickfix entry from the current entry in the quickfix +/// list 'qfl'. Returns a pointer to the new entry and the index in 'new_qfidx' +static qfline_T *get_nth_entry(qf_list_T *qfl, int errornr, int *new_qfidx) { - int qf_idx = *cur_qfidx; + qfline_T *qf_ptr = qfl->qf_ptr; + int qf_idx = qfl->qf_index;; // New error number is less than the current error number while (errornr < qf_idx && qf_idx > 1 && qf_ptr->qf_prev != NULL) { @@ -2402,10 +2439,31 @@ static qfline_T *get_nth_entry(qf_list_T *qfl, int errornr, qfline_T *qf_ptr, qf_ptr = qf_ptr->qf_next; } - *cur_qfidx = qf_idx; + *new_qfidx = qf_idx; return qf_ptr; } +/// Get a entry specied by 'errornr' and 'dir' from the current +/// quickfix/location list. 'errornr' specifies the index of the entry and 'dir' +/// specifies the direction (FORWARD/BACKWARD/FORWARD_FILE/BACKWARD_FILE). +/// Returns a pointer to the entry and the index of the new entry is stored in +/// 'new_qfidx'. +static qfline_T * qf_get_entry(qf_list_T *qfl, int errornr, + int dir, int *new_qfidx) +{ + qfline_T *qf_ptr = qfl->qf_ptr; + int qfidx = qfl->qf_index; + + if (dir != 0) { // next/prev valid entry + qf_ptr = get_nth_valid_entry(qfl, errornr, dir, &qfidx); + } else if (errornr != 0) { // go to specified number + qf_ptr = get_nth_entry(qfl, errornr, &qfidx); + } + + *new_qfidx = qfidx; + return qf_ptr; +} + // Find a window displaying a Vim help file. static win_T *qf_find_help_win(void) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT @@ -2425,12 +2483,13 @@ static void win_set_loclist(win_T *wp, qf_info_T *qi) qi->qf_refcount++; } -/// Find a help window or open one. -static int jump_to_help_window(qf_info_T *qi, int *opened_window) +/// Find a help window or open one. If 'newwin' is true, then open a new help +/// window. +static int jump_to_help_window(qf_info_T *qi, bool newwin, int *opened_window) { win_T *wp = NULL; - if (cmdmod.tab != 0) { + if (cmdmod.tab != 0 || newwin) { wp = NULL; } else { wp = qf_find_help_win(); @@ -2448,8 +2507,10 @@ static int jump_to_help_window(qf_info_T *qi, int *opened_window) flags |= WSP_TOP; } - if (IS_LL_STACK(qi)) { - flags |= WSP_NEWLOC; // don't copy the location list + // If the user asks to open a new window, then copy the location list. + // Otherwise, don't copy the location list. + if (IS_LL_STACK(qi) && !newwin) { + flags |= WSP_NEWLOC; } if (win_split(0, flags) == FAIL) { @@ -2462,8 +2523,10 @@ static int jump_to_help_window(qf_info_T *qi, int *opened_window) win_setheight((int)p_hh); } - if (IS_LL_STACK(qi)) { // not a quickfix list - // The new window should use the supplied location list + // When using location list, the new window should use the supplied + // location list. If the user asks to open a new window, then the new + // window will get a copy of the location list. + if (IS_LL_STACK(qi) && !newwin) { win_set_loclist(curwin, qi); } } @@ -2475,7 +2538,8 @@ static int jump_to_help_window(qf_info_T *qi, int *opened_window) return OK; } -// Find a non-quickfix window using the given location list. +// Find a non-quickfix window in the current tabpage using the given location +// list stack. // Returns NULL if a matching window is not found. static win_T *qf_find_win_with_loclist(const qf_info_T *ll) FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT @@ -2624,14 +2688,19 @@ static void qf_goto_win_with_qfl_file(int qf_fnum) // Find a suitable window for opening a file (qf_fnum) from the // quickfix/location list and jump to it. If the file is already opened in a -// window, jump to it. Otherwise open a new window to display the file. This is -// called from either a quickfix or a location list window. -static int qf_jump_to_usable_window(int qf_fnum, int *opened_window) +// window, jump to it. Otherwise open a new window to display the file. If +// 'newwin' is true, then always open a new window. This is called from either +// a quickfix or a location list window. +static int qf_jump_to_usable_window(int qf_fnum, bool newwin, + int *opened_window) { win_T *usable_win_ptr = NULL; bool usable_win = false; - qf_info_T *ll_ref = curwin->w_llist_ref; + // If opening a new window, then don't use the location list referred by + // the current window. Otherwise two windows will refer to the same + // location list. + qf_info_T *ll_ref = newwin ? NULL : curwin->w_llist_ref; if (ll_ref != NULL) { // Find a non-quickfix window with this location list usable_win_ptr = qf_find_win_with_loclist(ll_ref); @@ -2656,7 +2725,7 @@ static int qf_jump_to_usable_window(int qf_fnum, int *opened_window) // If there is only one window and it is the quickfix window, create a // new one above the quickfix window. - if ((ONE_WINDOW && bt_quickfix(curbuf)) || !usable_win) { + if ((ONE_WINDOW && bt_quickfix(curbuf)) || !usable_win || newwin) { if (qf_open_new_file_win(ll_ref) != OK) { return FAIL; } @@ -2674,52 +2743,52 @@ static int qf_jump_to_usable_window(int qf_fnum, int *opened_window) /// Edit the selected file or help file. static int qf_jump_edit_buffer(qf_info_T *qi, qfline_T *qf_ptr, int forceit, - win_T *oldwin, int *opened_window, int *abort) + win_T *oldwin, int *opened_window) { qf_list_T *qfl = qf_get_curlist(qi); + long old_changetick = qfl->qf_changedtick; + int old_qf_curlist = qi->qf_curlist; qfltype_T qfl_type = qfl->qfl_type; int retval = OK; + unsigned save_qfid = qfl->qf_id; if (qf_ptr->qf_type == 1) { // Open help file (do_ecmd() will set b_help flag, readfile() will // set b_p_ro flag). if (!can_abandon(curbuf, forceit)) { no_write_message(); - retval = FAIL; + return FAIL; } else { retval = do_ecmd(qf_ptr->qf_fnum, NULL, NULL, NULL, (linenr_T)1, ECMD_HIDE + ECMD_SET_HELP, oldwin == curwin ? curwin : NULL); } } else { - unsigned save_qfid = qfl->qf_id; - retval = buflist_getfile(qf_ptr->qf_fnum, (linenr_T)1, GETF_SETMARK | GETF_SWITCH, forceit); + } + // If a location list, check whether the associated window is still + // present. + if (qfl_type == QFLT_LOCATION && !win_valid_any_tab(oldwin)) { + EMSG(_("E924: Current window was closed")); + *opened_window = false; + return NOTDONE; + } - if (qfl_type == QFLT_LOCATION) { - // Location list. Check whether the associated window is still - // present and the list is still valid. - if (!win_valid_any_tab(oldwin)) { - EMSG(_("E924: Current window was closed")); - *abort = true; - *opened_window = false; - } else if (!qflist_valid(oldwin, save_qfid)) { - EMSG(_(e_loc_list_changed)); - *abort = true; - } - } else if (!is_qf_entry_present(qfl, qf_ptr)) { - if (qfl_type == QFLT_QUICKFIX) { - EMSG(_("E925: Current quickfix was changed")); - } else { - EMSG(_(e_loc_list_changed)); - } - *abort = true; - } + if (qfl_type == QFLT_QUICKFIX && !qflist_valid(NULL, save_qfid)) { + EMSG(_(e_current_quickfix_list_was_changed)); + return NOTDONE; + } - if (*abort) { - retval = FAIL; + if (old_qf_curlist != qi->qf_curlist + || old_changetick != qfl->qf_changedtick + || !is_qf_entry_present(qfl, qf_ptr)) { + if (qfl_type == QFLT_QUICKFIX) { + EMSG(_(e_current_quickfix_list_was_changed)); + } else { + EMSG(_(e_current_location_list_was_changed)); } + return NOTDONE; } return retval; @@ -2794,22 +2863,133 @@ static void qf_jump_print_msg(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, msg_scroll = (int)i; } -/// jump to a quickfix line -/// if dir == FORWARD go "errornr" valid entries forward -/// if dir == BACKWARD go "errornr" valid entries backward -/// if dir == FORWARD_FILE go "errornr" valid entries files backward -/// if dir == BACKWARD_FILE go "errornr" valid entries files backward -/// else if "errornr" is zero, redisplay the same line -/// else go to entry "errornr" +/// Find a usable window for opening a file from the quickfix/location list. If +/// a window is not found then open a new window. If 'newwin' is true, then open +/// a new window. +/// Returns OK if successfully jumped or opened a window. Returns FAIL if not +/// able to jump/open a window. Returns NOTDONE if a file is not associated +/// with the entry. +static int qf_jump_open_window(qf_info_T *qi, qfline_T *qf_ptr, bool newwin, + int *opened_window) +{ + qf_list_T *qfl = qf_get_curlist(qi); + long old_changetick = qfl->qf_changedtick; + int old_qf_curlist = qi->qf_curlist; + qfltype_T qfl_type = qfl->qfl_type; + + // For ":helpgrep" find a help window or open one. + if (qf_ptr->qf_type == 1 && (!bt_help(curwin->w_buffer) || cmdmod.tab != 0)) { + if (jump_to_help_window(qi, newwin, opened_window) == FAIL) { + return FAIL; + } + } + if (old_qf_curlist != qi->qf_curlist + || old_changetick != qfl->qf_changedtick + || !is_qf_entry_present(qfl, qf_ptr)) { + if (qfl_type == QFLT_QUICKFIX) { + EMSG(_(e_current_quickfix_list_was_changed)); + } else { + EMSG(_(e_current_location_list_was_changed)); + } + return FAIL; + } + + // If currently in the quickfix window, find another window to show the + // file in. + if (bt_quickfix(curbuf) && !*opened_window) { + // If there is no file specified, we don't know where to go. + // But do advance, otherwise ":cn" gets stuck. + if (qf_ptr->qf_fnum == 0) { + return NOTDONE; + } + + if (qf_jump_to_usable_window(qf_ptr->qf_fnum, newwin, opened_window) + == FAIL) { + return FAIL; + } + } + if (old_qf_curlist != qi->qf_curlist + || old_changetick != qfl->qf_changedtick + || !is_qf_entry_present(qfl, qf_ptr)) { + if (qfl_type == QFLT_QUICKFIX) { + EMSG(_(e_current_quickfix_list_was_changed)); + } else { + EMSG(_(e_current_location_list_was_changed)); + } + return FAIL; + } + + return OK; +} + +/// Edit a selected file from the quickfix/location list and jump to a +/// particular line/column, adjust the folds and display a message about the +/// jump. +/// Returns OK on success and FAIL on failing to open the file/buffer. Returns +/// NOTDONE if the quickfix/location list is freed by an autocmd when opening +/// the file. +static int qf_jump_to_buffer(qf_info_T *qi, int qf_index, qfline_T *qf_ptr, + int forceit, win_T *oldwin, int *opened_window, + int openfold, int print_message) +{ + buf_T *old_curbuf; + linenr_T old_lnum; + int retval = OK; + + // If there is a file name, read the wanted file if needed, and check + // autowrite etc. + old_curbuf = curbuf; + old_lnum = curwin->w_cursor.lnum; + + if (qf_ptr->qf_fnum != 0) { + retval = qf_jump_edit_buffer(qi, qf_ptr, forceit, oldwin, + opened_window); + if (retval != OK) { + return retval; + } + } + + // When not switched to another buffer, still need to set pc mark + if (curbuf == old_curbuf) { + setpcmark(); + } + + qf_jump_goto_line(qf_ptr->qf_lnum, qf_ptr->qf_col, qf_ptr->qf_viscol, + qf_ptr->qf_pattern); + + if ((fdo_flags & FDO_QUICKFIX) && openfold) { + foldOpenCursor(); + } + if (print_message) { + qf_jump_print_msg(qi, qf_index, qf_ptr, old_curbuf, old_lnum); + } + + return retval; +} + +/// Jump to a quickfix line and try to use an existing window. void qf_jump(qf_info_T *qi, int dir, int errornr, int forceit) { + qf_jump_newwin(qi, dir, errornr, forceit, false); +} + +// Jump to a quickfix line. +// If dir == 0 go to entry "errornr". +// If dir == FORWARD go "errornr" valid entries forward. +// If dir == BACKWARD go "errornr" valid entries backward. +// If dir == FORWARD_FILE go "errornr" valid entries files backward. +// If dir == BACKWARD_FILE go "errornr" valid entries files backward +// else if "errornr" is zero, redisplay the same line +// If 'forceit' is true, then can discard changes to the current buffer. +// If 'newwin' is true, then open the file in a new window. +static void qf_jump_newwin(qf_info_T *qi, int dir, int errornr, int forceit, + bool newwin) +{ qf_list_T *qfl; qfline_T *qf_ptr; qfline_T *old_qf_ptr; int qf_index; int old_qf_index; - buf_T *old_curbuf; - linenr_T old_lnum; char_u *old_swb = p_swb; unsigned old_swb_flags = swb_flags; int opened_window = false; @@ -2832,15 +3012,12 @@ void qf_jump(qf_info_T *qi, int dir, int errornr, int forceit) old_qf_ptr = qf_ptr; qf_index = qfl->qf_index; old_qf_index = qf_index; - if (dir != 0) { // next/prev valid entry - qf_ptr = get_nth_valid_entry(qfl, errornr, qf_ptr, &qf_index, dir); - if (qf_ptr == NULL) { - qf_ptr = old_qf_ptr; - qf_index = old_qf_index; - goto theend; // The horror... the horror... - } - } else if (errornr != 0) { // go to specified number - qf_ptr = get_nth_entry(qfl, errornr, qf_ptr, &qf_index); + + qf_ptr = qf_get_entry(qfl, errornr, dir, &qf_index); + if (qf_ptr == NULL) { + qf_ptr = old_qf_ptr; + qf_index = old_qf_index; + goto theend; } qfl->qf_index = qf_index; @@ -2850,58 +3027,23 @@ void qf_jump(qf_info_T *qi, int dir, int errornr, int forceit) print_message = false; } - // For ":helpgrep" find a help window or open one. - if (qf_ptr->qf_type == 1 && (!bt_help(curwin->w_buffer) || cmdmod.tab != 0)) { - if (jump_to_help_window(qi, &opened_window) == FAIL) { - goto theend; - } + retval = qf_jump_open_window(qi, qf_ptr, newwin, &opened_window); + if (retval == FAIL) { + goto failed; } - - // If currently in the quickfix window, find another window to show the - // file in. - if (bt_quickfix(curbuf) && !opened_window) { - // If there is no file specified, we don't know where to go. - // But do advance, otherwise ":cn" gets stuck. - if (qf_ptr->qf_fnum == 0) { - goto theend; - } - if (qf_jump_to_usable_window(qf_ptr->qf_fnum, &opened_window) == FAIL) { - goto failed; - } + if (retval == NOTDONE) { + goto theend; } - // If there is a file name, - // read the wanted file if needed, and check autowrite etc. - old_curbuf = curbuf; - old_lnum = curwin->w_cursor.lnum; - - if (qf_ptr->qf_fnum != 0) { - int abort = false; - retval = qf_jump_edit_buffer(qi, qf_ptr, forceit, oldwin, &opened_window, - &abort); - if (abort) { - qi = NULL; - qf_ptr = NULL; - } + retval = qf_jump_to_buffer(qi, qf_index, qf_ptr, forceit, oldwin, + &opened_window, old_KeyTyped, print_message); + if (retval == NOTDONE) { + // Quickfix/location list is freed by an autocmd + qi = NULL; + qf_ptr = NULL; } - if (retval == OK) { - // When not switched to another buffer, still need to set pc mark - if (curbuf == old_curbuf) { - setpcmark(); - } - - if (qf_ptr != NULL) { - qf_jump_goto_line(qf_ptr->qf_lnum, qf_ptr->qf_col, qf_ptr->qf_viscol, - qf_ptr->qf_pattern); - } - - if ((fdo_flags & FDO_QUICKFIX) && old_KeyTyped) - foldOpenCursor(); - if (print_message) { - qf_jump_print_msg(qi, qf_index, qf_ptr, old_curbuf, old_lnum); - } - } else { + if (retval != OK) { if (opened_window) { win_close(curwin, true); // Close opened window } @@ -3187,7 +3329,7 @@ void qf_history(exarg_T *eap) qf_info_T *qi = qf_cmd_get_stack(eap, false); int i; - if (qf_stack_empty(qi) || qf_list_empty(qf_get_curlist(qi))) { + if (qf_stack_empty(qi)) { MSG(_("No entries")); } else { for (i = 0; i < qi->qf_listcount; i++) { @@ -3355,14 +3497,9 @@ void qf_view_result(bool split) } if (split) { - char cmd[32]; - - snprintf(cmd, sizeof(cmd), "split +%" PRId64 "%s", - (int64_t)curwin->w_cursor.lnum, - IS_LL_WINDOW(curwin) ? "ll" : "cc"); - if (do_cmdline_cmd(cmd) == OK) { - do_cmdline_cmd("clearjumps"); - } + // Open the selected entry in a new window + qf_jump_newwin(qi, 0, (int)curwin->w_cursor.lnum, false, true); + do_cmdline_cmd("clearjumps"); return; } @@ -3393,7 +3530,7 @@ void ex_cwindow(exarg_T *eap) // it if we have errors; otherwise, leave it closed. if (qf_stack_empty(qi) || qfl->qf_nonevalid - || qf_list_empty(qf_get_curlist(qi))) { + || qf_list_empty(qfl)) { if (win != NULL) { ex_cclose(eap); } @@ -3446,10 +3583,23 @@ static int qf_goto_cwindow(const qf_info_T *qi, bool resize, int sz, return OK; } +// Set options for the buffer in the quickfix or location list window. +static void qf_set_cwindow_options(void) +{ + // switch off 'swapfile' + set_option_value("swf", 0L, NULL, OPT_LOCAL); + set_option_value("bt", 0L, "quickfix", OPT_LOCAL); + set_option_value("bh", 0L, "hide", OPT_LOCAL); + RESET_BINDING(curwin); + curwin->w_p_diff = false; + set_option_value("fdm", 0L, "manual", OPT_LOCAL); +} + // Open a new quickfix or location list window, load the quickfix buffer and // set the appropriate options for the window. // Returns FAIL if the window could not be opened. -static int qf_open_new_cwindow(const qf_info_T *qi, int height) +static int qf_open_new_cwindow(qf_info_T *qi, int height) + FUNC_ATTR_NONNULL_ALL { win_T *oldwin = curwin; const tabpage_T *const prevtab = curtab; @@ -3493,13 +3643,15 @@ static int qf_open_new_cwindow(const qf_info_T *qi, int height) // Create a new quickfix buffer (void)do_ecmd(0, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE, oldwin); - // switch off 'swapfile' - set_option_value("swf", 0L, NULL, OPT_LOCAL); - set_option_value("bt", 0L, "quickfix", OPT_LOCAL); - set_option_value("bh", 0L, "wipe", OPT_LOCAL); - RESET_BINDING(curwin); - curwin->w_p_diff = false; - set_option_value("fdm", 0L, "manual", OPT_LOCAL); + // save the number of the new buffer + qi->qf_bufnr = curbuf->b_fnum; + } + + // Set the options for the quickfix buffer/window (if not already done) + // Do this even if the quickfix buffer was already present, as an autocmd + // might have previously deleted (:bdelete) the quickfix buffer. + if (curbuf->b_p_bt[0] != 'q') { + qf_set_cwindow_options(); } // Only set the height when still in the same tab page and there is no @@ -3688,9 +3840,18 @@ static win_T *qf_find_win(const qf_info_T *qi) // Find a quickfix buffer. // Searches in windows opened in all the tabs. -static buf_T *qf_find_buf(const qf_info_T *qi) - FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT +static buf_T *qf_find_buf(qf_info_T *qi) + FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT { + if (qi->qf_bufnr != INVALID_QFBUFNR) { + buf_T *const qfbuf = buflist_findnr(qi->qf_bufnr); + if (qfbuf != NULL) { + return qfbuf; + } + // buffer is no longer present + qi->qf_bufnr = INVALID_QFBUFNR; + } + FOR_ALL_TAB_WINDOWS(tp, win) { if (is_qf_win(win, qi)) { return win->w_buffer; @@ -4814,7 +4975,7 @@ static bool vgr_qflist_valid(win_T *wp, qf_info_T *qi, unsigned qfid, if (!qflist_valid(wp, qfid)) { if (wp != NULL) { // An autocmd has freed the location list - EMSG(_(e_loc_list_changed)); + EMSG(_(e_current_location_list_was_changed)); return false; } else { // Quickfix list is not found, create a new one. @@ -4832,7 +4993,7 @@ static bool vgr_qflist_valid(win_T *wp, qf_info_T *qi, unsigned qfid, /// Search for a pattern in all the lines in a buffer and add the matching lines /// to a quickfix list. -static bool vgr_match_buflines(qf_info_T *qi, char_u *fname, buf_T *buf, +static bool vgr_match_buflines(qf_list_T *qfl, char_u *fname, buf_T *buf, regmmatch_T *regmatch, long *tomatch, int duplicate_name, int flags) FUNC_ATTR_NONNULL_ARG(1, 3, 4, 5) @@ -4846,7 +5007,7 @@ static bool vgr_match_buflines(qf_info_T *qi, char_u *fname, buf_T *buf, // Pass the buffer number so that it gets used even for a // dummy buffer, unless duplicate_name is set, then the // buffer will be wiped out below. - if (qf_add_entry(qf_get_curlist(qi), + if (qf_add_entry(qfl, NULL, // dir fname, NULL, @@ -4907,6 +5068,20 @@ static void vgr_jump_to_match(qf_info_T *qi, int forceit, int *redraw_for_dummy, } } +// Return true if "buf" had an existing swap file, the current swap file does +// not end in ".swp". +static bool existing_swapfile(const buf_T *buf) + FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT +{ + if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL) { + const char_u *const fname = buf->b_ml.ml_mfp->mf_fname; + const size_t len = STRLEN(fname); + + return fname[len - 1] != 'p' || fname[len - 2] != 'w'; + } + return false; +} + // ":vimgrep {pattern} file(s)" // ":vimgrepadd {pattern} file(s)" // ":lvimgrep {pattern} file(s)" @@ -5039,7 +5214,8 @@ void ex_vimgrep(exarg_T *eap) } else { // Try for a match in all lines of the buffer. // For ":1vimgrep" look for first match only. - found_match = vgr_match_buflines(qi, fname, buf, ®match, &tomatch, + found_match = vgr_match_buflines(qf_get_curlist(qi), + fname, buf, ®match, &tomatch, duplicate_name, flags); if (using_dummy) { @@ -5063,7 +5239,9 @@ void ex_vimgrep(exarg_T *eap) if (!found_match) { wipe_dummy_buffer(buf, dirname_start); buf = NULL; - } else if (buf != first_match_buf || (flags & VGR_NOJUMP)) { + } else if (buf != first_match_buf + || (flags & VGR_NOJUMP) + || existing_swapfile(buf)) { unload_dummy_buffer(buf, dirname_start); // Keeping the buffer, remove the dummy flag. buf->b_flags &= ~BF_DUMMY; @@ -5418,7 +5596,8 @@ enum { QF_GETLIST_SIZE = 0x80, QF_GETLIST_TICK = 0x100, QF_GETLIST_FILEWINID = 0x200, - QF_GETLIST_ALL = 0x3FF, + QF_GETLIST_QFBUFNR = 0x400, + QF_GETLIST_ALL = 0x7FF, }; /// Parse text from 'di' and return the quickfix list items. @@ -5473,6 +5652,15 @@ static int qf_winid(qf_info_T *qi) return 0; } +// Returns the number of the buffer displayed in the quickfix/location list +// window. If there is no buffer associated with the list, then returns 0. +static int qf_getprop_qfbufnr(const qf_info_T *qi, dict_T *retdict) + FUNC_ATTR_NONNULL_ARG(2) +{ + return tv_dict_add_nr(retdict, S_LEN("qfbufnr"), + (qi == NULL) ? 0 : qi->qf_bufnr); +} + /// Convert the keys in 'what' to quickfix list property flags. static int qf_getprop_keys2flags(const dict_T *what, bool loclist) FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT @@ -5516,6 +5704,9 @@ static int qf_getprop_keys2flags(const dict_T *what, bool loclist) if (loclist && tv_dict_find(what, S_LEN("filewinid")) != NULL) { flags |= QF_GETLIST_FILEWINID; } + if (tv_dict_find(what, S_LEN("qfbufnr")) != NULL) { + flags |= QF_GETLIST_QFBUFNR; + } return flags; } @@ -5607,6 +5798,9 @@ static int qf_getprop_defaults(qf_info_T *qi, if ((status == OK) && locstack && (flags & QF_GETLIST_FILEWINID)) { status = tv_dict_add_nr(retdict, S_LEN("filewinid"), 0); } + if ((status == OK) && (flags & QF_GETLIST_QFBUFNR)) { + status = qf_getprop_qfbufnr(qi, retdict); + } return status; } @@ -5741,6 +5935,9 @@ int qf_get_properties(win_T *wp, dict_T *what, dict_T *retdict) if ((status == OK) && (wp != NULL) && (flags & QF_GETLIST_FILEWINID)) { status = qf_getprop_filewinid(wp, qi, retdict); } + if ((status == OK) && (flags & QF_GETLIST_QFBUFNR)) { + status = qf_getprop_qfbufnr(qi, retdict); + } return status; } @@ -6029,6 +6226,49 @@ static int qf_setprop_context(qf_list_T *qfl, dictitem_T *di) return OK; } +// Set the current index in the specified quickfix list +static int qf_setprop_curidx(qf_info_T *qi, qf_list_T *qfl, + const dictitem_T *di) + FUNC_ATTR_NONNULL_ALL +{ + int newidx; + + // If the specified index is '$', then use the last entry + if (di->di_tv.v_type == VAR_STRING + && di->di_tv.vval.v_string != NULL + && STRCMP(di->di_tv.vval.v_string, "$") == 0) { + newidx = qfl->qf_count; + } else { + // Otherwise use the specified index + bool denote = false; + newidx = (int)tv_get_number_chk(&di->di_tv, &denote); + if (denote) { + return FAIL; + } + } + + if (newidx < 1) { // sanity check + return FAIL; + } + if (newidx > qfl->qf_count) { + newidx = qfl->qf_count; + } + const int old_qfidx = qfl->qf_index; + qfline_T *const qf_ptr = get_nth_entry(qfl, newidx, &newidx); + if (qf_ptr == NULL) { + return FAIL; + } + qfl->qf_ptr = qf_ptr; + qfl->qf_index = newidx; + + // If the current list is modified and it is displayed in the quickfix + // window, then Update it. + if (qi->qf_lists[qi->qf_curlist].qf_id == qfl->qf_id) { + qf_win_pos_update(qi, old_qfidx); + } + return OK; +} + /// Set quickfix/location list properties (title, items, context). /// Also used to add items from parsing a list of lines. /// Used by the setqflist() and setloclist() Vim script functions. @@ -6064,6 +6304,9 @@ static int qf_set_properties(qf_info_T *qi, const dict_T *what, int action, if ((di = tv_dict_find(what, S_LEN("context"))) != NULL) { retval = qf_setprop_context(qfl, di); } + if ((di = tv_dict_find(what, S_LEN("idx"))) != NULL) { + retval = qf_setprop_curidx(qi, qfl, di); + } if (retval == OK) { qf_list_changed(qfl); @@ -6072,19 +6315,6 @@ static int qf_set_properties(qf_info_T *qi, const dict_T *what, int action, return retval; } -/// Find the non-location list window with the specified location list stack in -/// the current tabpage. -static win_T * find_win_with_ll(qf_info_T *qi) -{ - FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { - if ((wp->w_llist == qi) && !bt_quickfix(wp->w_buffer)) { - return wp; - } - } - - return NULL; -} - // Free the entire quickfix/location list stack. // If the quickfix/location list window is open, then clear it. static void qf_free_stack(win_T *wp, qf_info_T *qi) @@ -6099,12 +6329,10 @@ static void qf_free_stack(win_T *wp, qf_info_T *qi) qf_update_buffer(qi, NULL); } - win_T *llwin = NULL; - win_T *orig_wp = wp; if (wp != NULL && IS_LL_WINDOW(wp)) { // If in the location list window, then use the non-location list // window with this location list (if present) - llwin = find_win_with_ll(qi); + win_T *const llwin = qf_find_win_with_loclist(qi); if (llwin != NULL) { wp = llwin; } @@ -6115,16 +6343,17 @@ static void qf_free_stack(win_T *wp, qf_info_T *qi) // quickfix list qi->qf_curlist = 0; qi->qf_listcount = 0; - } else if (IS_LL_WINDOW(orig_wp)) { + } else if (qfwin != NULL) { // If the location list window is open, then create a new empty location // list qf_info_T *new_ll = qf_alloc_stack(QFLT_LOCATION); + new_ll->qf_bufnr = qfwin->w_buffer->b_fnum; // first free the list reference in the location list window - ll_free_all(&orig_wp->w_llist_ref); + ll_free_all(&qfwin->w_llist_ref); - orig_wp->w_llist_ref = new_ll; - if (llwin != NULL) { + qfwin->w_llist_ref = new_ll; + if (wp != qfwin) { win_set_loclist(wp, new_ll); } } @@ -6149,6 +6378,12 @@ int set_errorlist(win_T *wp, list_T *list, int action, char_u *title, return OK; } + // A dict argument cannot be specified with a non-empty list argument + if (list != NULL && tv_list_len(list) != 0 && what != NULL) { + EMSG2(_(e_invarg2), _("cannot have both a list and a \"what\" argument")); + return FAIL; + } + incr_quickfix_busy(); if (what != NULL) { @@ -6377,7 +6612,7 @@ void ex_cexpr(exarg_T *eap) // Evaluate the expression. When the result is a string or a list we can // use it to fill the errorlist. typval_T tv; - if (eval0(eap->arg, &tv, NULL, true) != FAIL) { + if (eval0(eap->arg, &tv, &eap->nextcmd, true) != FAIL) { if ((tv.v_type == VAR_STRING && tv.vval.v_string != NULL) || tv.v_type == VAR_LIST) { incr_quickfix_busy(); @@ -6448,7 +6683,7 @@ static qf_info_T *hgr_get_ll(bool *new_ll) // Search for a pattern in a help file. static void hgr_search_file( - qf_info_T *qi, + qf_list_T *qfl, char_u *fname, regmatch_T *p_regmatch) FUNC_ATTR_NONNULL_ARG(1, 3) @@ -6470,7 +6705,7 @@ static void hgr_search_file( line[--l] = NUL; } - if (qf_add_entry(qf_get_curlist(qi), + if (qf_add_entry(qfl, NULL, // dir fname, NULL, @@ -6503,7 +6738,7 @@ static void hgr_search_file( // Search for a pattern in all the help files in the doc directory under // the given directory. static void hgr_search_files_in_dir( - qf_info_T *qi, + qf_list_T *qfl, char_u *dirname, regmatch_T *p_regmatch, const char_u *lang) @@ -6528,7 +6763,7 @@ static void hgr_search_files_in_dir( continue; } - hgr_search_file(qi, fnames[fi], p_regmatch); + hgr_search_file(qfl, fnames[fi], p_regmatch); } FreeWild(fcount, fnames); } @@ -6538,7 +6773,7 @@ static void hgr_search_files_in_dir( // and add the matches to a quickfix list. // 'lang' is the language specifier. If supplied, then only matches in the // specified language are found. -static void hgr_search_in_rtp(qf_info_T *qi, regmatch_T *p_regmatch, +static void hgr_search_in_rtp(qf_list_T *qfl, regmatch_T *p_regmatch, const char_u *lang) FUNC_ATTR_NONNULL_ARG(1, 2) { @@ -6547,7 +6782,7 @@ static void hgr_search_in_rtp(qf_info_T *qi, regmatch_T *p_regmatch, while (*p != NUL && !got_int) { copy_option_part(&p, NameBuff, MAXPATHL, ","); - hgr_search_files_in_dir(qi, NameBuff, p_regmatch, lang); + hgr_search_files_in_dir(qfl, NameBuff, p_regmatch, lang); } } @@ -6589,12 +6824,12 @@ void ex_helpgrep(exarg_T *eap) if (regmatch.regprog != NULL) { // Create a new quickfix list. qf_new_list(qi, qf_cmdtitle(*eap->cmdlinep)); + qf_list_T *const qfl = qf_get_curlist(qi); - hgr_search_in_rtp(qi, ®match, lang); + hgr_search_in_rtp(qfl, ®match, lang); vim_regfree(regmatch.regprog); - qf_list_T *qfl = qf_get_curlist(qi); qfl->qf_nonevalid = false; qfl->qf_ptr = qfl->qf_start; qfl->qf_index = 1; diff --git a/src/nvim/screen.c b/src/nvim/screen.c index 3503348049..1191886888 100644 --- a/src/nvim/screen.c +++ b/src/nvim/screen.c @@ -119,10 +119,12 @@ #include "nvim/api/private/helpers.h" #include "nvim/api/vim.h" #include "nvim/lua/executor.h" +#include "nvim/lib/kvec.h" #define MB_FILLER_CHAR '<' /* character used when a double-width character * doesn't fit. */ +typedef kvec_withinit_t(DecorationProvider *, 4) Providers; // temporary buffer for rendering a single screenline, so it can be // compared with previous contents to calculate smallest delta. @@ -156,13 +158,43 @@ static bool msg_grid_invalid = false; static bool resizing = false; -static bool do_luahl_line = false; #ifdef INCLUDE_GENERATED_DECLARATIONS # include "screen.c.generated.h" #endif #define SEARCH_HL_PRIORITY 0 +static char * provider_first_error = NULL; + +static bool provider_invoke(NS ns_id, const char *name, LuaRef ref, + Array args, bool default_true) +{ + Error err = ERROR_INIT; + + textlock++; + Object ret = nlua_call_ref(ref, name, args, true, &err); + textlock--; + + if (!ERROR_SET(&err) + && api_is_truthy(ret, "provider %s retval", default_true, &err)) { + return true; + } + + if (ERROR_SET(&err)) { + const char *ns_name = describe_ns(ns_id); + ELOG("error in provider %s:%s: %s", ns_name, name, err.msg); + bool verbose_errs = true; // TODO(bfredl): + if (verbose_errs && provider_first_error == NULL) { + static char errbuf[IOSIZE]; + snprintf(errbuf, sizeof errbuf, "%s: %s", ns_name, err.msg); + provider_first_error = xstrdup(errbuf); + } + } + + api_free_object(ret); + return false; +} + /* * Redraw the current window later, with update_screen(type). * Set must_redraw only if not already set to a higher value. @@ -446,6 +478,29 @@ int update_screen(int type) ui_comp_set_screen_valid(true); + Providers providers; + kvi_init(providers); + for (size_t i = 0; i < kv_size(decoration_providers); i++) { + DecorationProvider *p = &kv_A(decoration_providers, i); + if (!p->active) { + continue; + } + + bool active; + if (p->redraw_start != LUA_NOREF) { + FIXED_TEMP_ARRAY(args, 2); + args.items[0] = INTEGER_OBJ(display_tick); + args.items[1] = INTEGER_OBJ(type); + active = provider_invoke(p->ns_id, "start", p->redraw_start, args, true); + } else { + active = true; + } + + if (active) { + kvi_push(providers, p); + } + } + if (clear_cmdline) /* going to clear cmdline (done below) */ check_for_delay(FALSE); @@ -494,30 +549,24 @@ int update_screen(int type) FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { update_window_hl(wp, type >= NOT_VALID); - if (wp->w_buffer->b_mod_set) { - win_T *wwp; - - // Check if we already did this buffer. - for (wwp = firstwin; wwp != wp; wwp = wwp->w_next) { - if (wwp->w_buffer == wp->w_buffer) { - break; - } - } - if (wwp == wp && syntax_present(wp)) { - syn_stack_apply_changes(wp->w_buffer); - } - - buf_T *buf = wp->w_buffer; - if (luahl_active && luahl_start != LUA_NOREF) { - Error err = ERROR_INIT; - FIXED_TEMP_ARRAY(args, 2); - args.items[0] = BUFFER_OBJ(buf->handle); - args.items[1] = INTEGER_OBJ(display_tick); - nlua_call_ref(luahl_start, "start", args, false, &err); - if (ERROR_SET(&err)) { - ELOG("error in luahl start: %s", err.msg); - api_clear_error(&err); + buf_T *buf = wp->w_buffer; + if (buf->b_mod_set) { + if (buf->b_mod_tick_syn < display_tick + && syntax_present(wp)) { + syn_stack_apply_changes(buf); + buf->b_mod_tick_syn = display_tick; + } + + if (buf->b_mod_tick_deco < display_tick) { + for (size_t i = 0; i < kv_size(providers); i++) { + DecorationProvider *p = kv_A(providers, i); + if (p && p->redraw_buf != LUA_NOREF) { + FIXED_TEMP_ARRAY(args, 1); + args.items[0] = BUFFER_OBJ(buf->handle); + provider_invoke(p->ns_id, "buf", p->redraw_buf, args, true); + } } + buf->b_mod_tick_deco = display_tick; } } } @@ -531,6 +580,8 @@ int update_screen(int type) FOR_ALL_WINDOWS_IN_TAB(wp, curtab) { + redrawn_win = wp; + if (wp->w_redr_type == CLEAR && wp->w_floating && wp->w_grid.chars) { grid_invalidate(&wp->w_grid); wp->w_redr_type = NOT_VALID; @@ -541,13 +592,15 @@ int update_screen(int type) did_one = TRUE; start_search_hl(); } - win_update(wp); + win_update(wp, &providers); } /* redraw status line after the window to minimize cursor movement */ if (wp->w_redr_status) { win_redr_status(wp); } + + redrawn_win = NULL; } end_search_hl(); @@ -578,6 +631,21 @@ int update_screen(int type) maybe_intro_message(); did_intro = TRUE; + for (size_t i = 0; i < kv_size(providers); i++) { + DecorationProvider *p = kv_A(providers, i); + if (!p->active) { + continue; + } + + if (p->redraw_end != LUA_NOREF) { + FIXED_TEMP_ARRAY(args, 1); + args.items[0] = INTEGER_OBJ(display_tick); + provider_invoke(p->ns_id, "end", p->redraw_end, args, true); + } + } + kvi_destroy(providers); + + // either cmdline is cleared, not drawn or mode is last drawn cmdline_was_last_drawn = false; return OK; @@ -635,15 +703,15 @@ bool win_cursorline_standout(const win_T *wp) } static DecorationRedrawState decorations; -bool decorations_active = false; -void decorations_add_luahl_attr(int attr_id, - int start_row, int start_col, - int end_row, int end_col, VirtText *virt_text) +void decorations_add_ephemeral(int attr_id, + int start_row, int start_col, + int end_row, int end_col, VirtText *virt_text) { kv_push(decorations.active, ((HlRange){ start_row, start_col, - end_row, end_col, attr_id, virt_text, true })); + end_row, end_col, + attr_id, virt_text, virt_text != NULL })); } /* @@ -673,7 +741,7 @@ void decorations_add_luahl_attr(int attr_id, * mid: from mid_start to mid_end (update inversion or changed text) * bot: from bot_start to last row (when scrolled up) */ -static void win_update(win_T *wp) +static void win_update(win_T *wp, Providers *providers) { buf_T *buf = wp->w_buffer; int type; @@ -698,8 +766,10 @@ static void win_update(win_T *wp) int didline = FALSE; /* if TRUE, we finished the last line */ int i; long j; - static int recursive = FALSE; /* being called recursively */ - int old_botline = wp->w_botline; + static bool recursive = false; // being called recursively + const linenr_T old_botline = wp->w_botline; + const int old_wrow = wp->w_wrow; + const int old_wcol = wp->w_wcol; // Remember what happened to the previous line. #define DID_NONE 1 // didn't update a line #define DID_LINE 2 // updated a normal line @@ -899,11 +969,12 @@ static void win_update(win_T *wp) || type == INVERTED || type == INVERTED_ALL) && !wp->w_botfill && !wp->w_old_botfill ) { - if (mod_top != 0 && wp->w_topline == mod_top) { - /* - * w_topline is the first changed line, the scrolling will be done - * further down. - */ + if (mod_top != 0 + && wp->w_topline == mod_top + && (!wp->w_lines[0].wl_valid + || wp->w_topline <= wp->w_lines[0].wl_lnum)) { + // w_topline is the first changed line and window is not scrolled, + // the scrolling from changed lines will be done further down. } else if (wp->w_lines[0].wl_valid && (wp->w_topline < wp->w_lines[0].wl_lnum || (wp->w_topline == wp->w_lines[0].wl_lnum @@ -1236,33 +1307,27 @@ static void win_update(win_T *wp) srow = 0; lnum = wp->w_topline; // first line shown in window - decorations_active = decorations_redraw_reset(buf, &decorations); + decorations_redraw_reset(buf, &decorations); - do_luahl_line = false; + Providers line_providers; + kvi_init(line_providers); - if (luahl_win != LUA_NOREF) { - Error err = ERROR_INIT; - FIXED_TEMP_ARRAY(args, 4); - linenr_T knownmax = ((wp->w_valid & VALID_BOTLINE) - ? wp->w_botline - : (wp->w_topline + wp->w_height_inner)); - args.items[0] = WINDOW_OBJ(wp->handle); - args.items[1] = BUFFER_OBJ(buf->handle); - // TODO(bfredl): we are not using this, but should be first drawn line? - args.items[2] = INTEGER_OBJ(wp->w_topline-1); - args.items[3] = INTEGER_OBJ(knownmax); - // TODO(bfredl): we could allow this callback to change mod_top, mod_bot. - // For now the "start" callback is expected to use nvim__buf_redraw_range. - Object ret = nlua_call_ref(luahl_win, "win", args, true, &err); + linenr_T knownmax = ((wp->w_valid & VALID_BOTLINE) + ? wp->w_botline + : (wp->w_topline + wp->w_height_inner)); - if (!ERROR_SET(&err) && api_is_truthy(ret, "luahl_window retval", &err)) { - do_luahl_line = true; - decorations_active = true; - } - - if (ERROR_SET(&err)) { - ELOG("error in luahl window: %s", err.msg); - api_clear_error(&err); + for (size_t k = 0; k < kv_size(*providers); k++) { + DecorationProvider *p = kv_A(*providers, k); + if (p && p->redraw_win != LUA_NOREF) { + FIXED_TEMP_ARRAY(args, 4); + args.items[0] = WINDOW_OBJ(wp->handle); + args.items[1] = BUFFER_OBJ(buf->handle); + // TODO(bfredl): we are not using this, but should be first drawn line? + args.items[2] = INTEGER_OBJ(wp->w_topline-1); + args.items[3] = INTEGER_OBJ(knownmax); + if (provider_invoke(p->ns_id, "win", p->redraw_win, args, true)) { + kvi_push(line_providers, p); + } } } @@ -1480,7 +1545,7 @@ static void win_update(win_T *wp) // Display one line row = win_line(wp, lnum, srow, foldinfo.fi_lines ? srow : wp->w_grid.Rows, - mod_top == 0, false, foldinfo); + mod_top == 0, false, foldinfo, &line_providers); wp->w_lines[idx].wl_folded = foldinfo.fi_lines != 0; wp->w_lines[idx].wl_lastlnum = lnum; @@ -1516,7 +1581,8 @@ static void win_update(win_T *wp) // 'relativenumber' set: The text doesn't need to be drawn, but // the number column nearly always does. foldinfo_T info = fold_info(wp, lnum); - (void)win_line(wp, lnum, srow, wp->w_grid.Rows, true, true, info); + (void)win_line(wp, lnum, srow, wp->w_grid.Rows, true, true, + info, &line_providers); } // This line does not need to be drawn, advance to the next one. @@ -1612,6 +1678,8 @@ static void win_update(win_T *wp) HLF_EOB); } + kvi_destroy(line_providers); + if (wp->w_redr_type >= REDRAW_TOP) { draw_vsep_win(wp, 0); } @@ -1638,18 +1706,51 @@ static void win_update(win_T *wp) wp->w_valid |= VALID_BOTLINE; wp->w_viewport_invalid = true; if (wp == curwin && wp->w_botline != old_botline && !recursive) { - recursive = TRUE; + const linenr_T old_topline = wp->w_topline; + const int new_wcol = wp->w_wcol; + recursive = true; curwin->w_valid &= ~VALID_TOPLINE; - update_topline(); /* may invalidate w_botline again */ - if (must_redraw != 0) { - /* Don't update for changes in buffer again. */ + update_topline(); // may invalidate w_botline again + + if (old_wcol != new_wcol + && (wp->w_valid & (VALID_WCOL|VALID_WROW)) + != (VALID_WCOL|VALID_WROW)) { + // A win_line() call applied a fix to screen cursor column to + // accomodate concealment of cursor line, but in this call to + // update_topline() the cursor's row or column got invalidated. + // If they are left invalid, setcursor() will recompute them + // but there won't be any further win_line() call to re-fix the + // column and the cursor will end up misplaced. So we call + // cursor validation now and reapply the fix again (or call + // win_line() to do it for us). + validate_cursor(); + if (wp->w_wcol == old_wcol + && wp->w_wrow == old_wrow + && old_topline == wp->w_topline) { + wp->w_wcol = new_wcol; + } else { + redrawWinline(wp, wp->w_cursor.lnum); + } + } + // New redraw either due to updated topline or due to wcol fix. + if (wp->w_redr_type != 0) { + // Don't update for changes in buffer again. i = curbuf->b_mod_set; curbuf->b_mod_set = false; - win_update(curwin); - must_redraw = 0; + j = curbuf->b_mod_xlines; + curbuf->b_mod_xlines = 0; + win_update(curwin, providers); curbuf->b_mod_set = i; + curbuf->b_mod_xlines = j; } - recursive = FALSE; + // Other windows might have w_redr_type raised in update_topline(). + must_redraw = 0; + FOR_ALL_WINDOWS_IN_TAB(wwp, curtab) { + if (wwp->w_redr_type > must_redraw) { + must_redraw = wwp->w_redr_type; + } + } + recursive = false; } } @@ -1883,28 +1984,23 @@ fill_foldcolumn( return MAX(char_counter + (fdc-i), (size_t)fdc); } - /// Display line "lnum" of window 'wp' on the screen. -/// Start at row "startrow", stop when "endrow" is reached. /// wp->w_virtcol needs to be valid. /// -/// @param lnum line to display -/// @param endrow stop drawing once reaching this row -/// @param nochange not updating for changed text -/// @param number_only only update the number column -/// @param foldinfo fold info for this line +/// @param lnum line to display +/// @param startrow first row relative to window grid +/// @param endrow last grid row to be redrawn +/// @param nochange not updating for changed text +/// @param number_only only update the number column +/// @param foldinfo fold info for this line +/// @param[in, out] providers decoration providers active this line +/// items will be disables if they cause errors +/// or explicitly return `false`. /// -/// @return the number of last row the line occupies. -static int -win_line ( - win_T *wp, - linenr_T lnum, - int startrow, - int endrow, - bool nochange, - bool number_only, - foldinfo_T foldinfo -) +/// @return the number of last row the line occupies. +static int win_line(win_T *wp, linenr_T lnum, int startrow, int endrow, + bool nochange, bool number_only, foldinfo_T foldinfo, + Providers *providers) { int c = 0; // init for GCC long vcol = 0; // virtual column (for tabs) @@ -2048,7 +2144,7 @@ win_line ( row = startrow; - char *luatext = NULL; + char *err_text = NULL; buf_T *buf = wp->w_buffer; @@ -2073,30 +2169,33 @@ win_line ( } } - if (decorations_active) { - if (do_luahl_line && luahl_line != LUA_NOREF) { - Error err = ERROR_INIT; + has_decorations = decorations_redraw_line(wp->w_buffer, lnum-1, + &decorations); + + for (size_t k = 0; k < kv_size(*providers); k++) { + DecorationProvider *p = kv_A(*providers, k); + if (p && p->redraw_line != LUA_NOREF) { FIXED_TEMP_ARRAY(args, 3); args.items[0] = WINDOW_OBJ(wp->handle); args.items[1] = BUFFER_OBJ(buf->handle); args.items[2] = INTEGER_OBJ(lnum-1); - lua_attr_active = true; - extra_check = true; - nlua_call_ref(luahl_line, "line", args, false, &err); - lua_attr_active = false; - - if (ERROR_SET(&err)) { - ELOG("error in luahl line: %s", err.msg); - luatext = err.msg; - do_virttext = true; + if (provider_invoke(p->ns_id, "line", p->redraw_line, args, true)) { + has_decorations = true; + } else { + // return 'false' or error: skip rest of this window + kv_A(*providers, k) = NULL; } } + } - has_decorations = decorations_redraw_line(wp->w_buffer, lnum-1, - &decorations); - if (has_decorations) { - extra_check = true; - } + if (has_decorations) { + extra_check = true; + } + + if (provider_first_error) { + err_text = provider_first_error; + provider_first_error = NULL; + do_virttext = true; } // Check for columns to display for 'colorcolumn'. @@ -3689,7 +3788,7 @@ win_line ( } // At end of the text line or just after the last character. - if (c == NUL) { + if (c == NUL && eol_hl_off == 0) { long prevcol = (long)(ptr - line) - 1; // we're not really at that column when skipping some text @@ -3799,8 +3898,10 @@ win_line ( draw_color_col = advance_color_col(VCOL_HLC, &color_cols); VirtText virt_text = KV_INITIAL_VALUE; - if (luatext) { - kv_push(virt_text, ((VirtTextChunk){ .text = luatext, .hl_id = 0 })); + if (err_text) { + int hl_err = syn_check_group((char_u *)S_LEN("ErrorMsg")); + kv_push(virt_text, ((VirtTextChunk){ .text = err_text, + .hl_id = hl_err })); do_virttext = true; } else if (has_decorations) { VirtText *vp = decorations_redraw_virt_text(wp->w_buffer, &decorations); @@ -4220,7 +4321,7 @@ win_line ( } xfree(p_extra_free); - xfree(luatext); + xfree(err_text); return row; } diff --git a/src/nvim/search.c b/src/nvim/search.c index ea2107c5c7..9458e6333f 100644 --- a/src/nvim/search.c +++ b/src/nvim/search.c @@ -3436,7 +3436,6 @@ current_tagblock( pos_T start_pos; pos_T end_pos; pos_T old_start, old_end; - char_u *spat, *epat; char_u *p; char_u *cp; int len; @@ -3490,9 +3489,9 @@ again: */ for (long n = 0; n < count; n++) { if (do_searchpair( - (char_u *)"<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", - (char_u *)"", - (char_u *)"</[^>]*>", BACKWARD, NULL, 0, + "<[^ \t>/!]\\+\\%(\\_s\\_[^>]\\{-}[^/]>\\|$\\|\\_s\\=>\\)", + "", + "</[^>]*>", BACKWARD, NULL, 0, NULL, (linenr_T)0, 0L) <= 0) { curwin->w_cursor = old_pos; goto theend; @@ -3514,12 +3513,15 @@ again: curwin->w_cursor = old_pos; goto theend; } - spat = xmalloc(len + 31); - epat = xmalloc(len + 9); - sprintf((char *)spat, "<%.*s\\>\\%%(\\s\\_[^>]\\{-}[^/]>\\|>\\)\\c", len, p); - sprintf((char *)epat, "</%.*s>\\c", len, p); - - const int r = do_searchpair(spat, (char_u *)"", epat, FORWARD, NULL, + const size_t spat_len = len + 39; + char *const spat = xmalloc(spat_len); + const size_t epat_len = len + 9; + char *const epat = xmalloc(epat_len); + snprintf(spat, spat_len, + "<%.*s\\>\\%%(\\_s\\_[^>]\\{-}\\_[^/]>\\|\\_s\\?>\\)\\c", len, p); + snprintf(epat, epat_len, "</%.*s>\\c", len, p); + + const int r = do_searchpair(spat, "", epat, FORWARD, NULL, 0, NULL, (linenr_T)0, 0L); xfree(spat); @@ -4097,7 +4099,7 @@ abort_search: int current_search( long count, - int forward // true for forward, false for backward + bool forward // true for forward, false for backward ) { bool old_p_ws = p_ws; @@ -4112,6 +4114,11 @@ current_search( pos_T pos; // position after the pattern int result; // result of various function calls + // When searching forward and the cursor is at the start of the Visual + // area, skip the first search backward, otherwise it doesn't move. + const bool skip_first_backward = forward && VIsual_active + && lt(curwin->w_cursor, VIsual); + orig_pos = pos = curwin->w_cursor; if (VIsual_active) { // Searching further will extend the match. @@ -4129,13 +4136,20 @@ current_search( return FAIL; // pattern not found } - /* - * The trick is to first search backwards and then search forward again, - * so that a match at the current cursor position will be correctly - * captured. - */ + // The trick is to first search backwards and then search forward again, + // so that a match at the current cursor position will be correctly + // captured. When "forward" is false do it the other way around. for (int i = 0; i < 2; i++) { - int dir = forward ? i : !i; + int dir; + if (forward) { + if (i == 0 && skip_first_backward) { + continue; + } + dir = i; + } else { + dir = !i; + } + int flags = 0; if (!dir && !zero_width) { @@ -4182,11 +4196,17 @@ current_search( VIsual = start_pos; } - // put cursor on last character of match + // put the cursor after the match curwin->w_cursor = end_pos; if (lt(VIsual, end_pos) && forward) { - dec_cursor(); - } else if (VIsual_active && lt(curwin->w_cursor, VIsual)) { + if (skip_first_backward) { + // put the cursor on the start of the match + curwin->w_cursor = pos; + } else { + // put the cursor on last character of match + dec_cursor(); + } + } else if (VIsual_active && lt(curwin->w_cursor, VIsual) && forward) { curwin->w_cursor = pos; // put the cursor on the start of the match } VIsual_active = true; diff --git a/src/nvim/spell.c b/src/nvim/spell.c index f036d7fe04..1984a357c3 100644 --- a/src/nvim/spell.c +++ b/src/nvim/spell.c @@ -396,8 +396,7 @@ size_t spell_check( mi.mi_word = ptr; mi.mi_fend = ptr; if (spell_iswordp(mi.mi_fend, wp)) { - int prev_upper; - int this_upper; + bool this_upper = false; // init for gcc if (use_camel_case) { c = PTR2CHAR(mi.mi_fend); @@ -407,7 +406,7 @@ size_t spell_check( do { MB_PTR_ADV(mi.mi_fend); if (use_camel_case) { - prev_upper = this_upper; + const bool prev_upper = this_upper; c = PTR2CHAR(mi.mi_fend); this_upper = SPELL_ISUPPER(c); camel_case = !prev_upper && this_upper; diff --git a/src/nvim/testdir/check.vim b/src/nvim/testdir/check.vim index e0ebe8fd49..7f6b7dcfec 100644 --- a/src/nvim/testdir/check.vim +++ b/src/nvim/testdir/check.vim @@ -25,6 +25,14 @@ func CheckFunction(name) endif endfunc +" Command to check for the presence of python. Argument should have been +" obtained with PythonProg() +func CheckPython(name) + if a:name == '' + throw 'Skipped: python command not available' + endif +endfunc + " Command to check for running on MS-Windows command CheckMSWindows call CheckMSWindows() func CheckMSWindows() @@ -73,3 +81,19 @@ func CheckNotGui() throw 'Skipped: only works in the terminal' endif endfunc + +" Command to check that the current language is English +command CheckEnglish call CheckEnglish() +func CheckEnglish() + if v:lang != "C" && v:lang !~ '^[Ee]n' + throw 'Skipped: only works in English language environment' + endif +endfunc + +" Command to check for NOT running on MS-Windows +command CheckNotMSWindows call CheckNotMSWindows() +func CheckNotMSWindows() + if has('win32') + throw 'Skipped: does not work on MS-Windows' + endif +endfunc diff --git a/src/nvim/testdir/runtest.vim b/src/nvim/testdir/runtest.vim index 765ba2cbb6..b02514143c 100644 --- a/src/nvim/testdir/runtest.vim +++ b/src/nvim/testdir/runtest.vim @@ -78,6 +78,9 @@ set encoding=utf-8 let s:test_script_fname = expand('%') au! SwapExists * call HandleSwapExists() func HandleSwapExists() + if exists('g:ignoreSwapExists') + return + endif " Ignore finding a swap file for the test script (the user might be " editing it and do ":make test_name") and the output file. " Report finding another swap file and chose 'q' to avoid getting stuck. diff --git a/src/nvim/testdir/shared.vim b/src/nvim/testdir/shared.vim index 0d32f4d875..4f1ddcd7b9 100644 --- a/src/nvim/testdir/shared.vim +++ b/src/nvim/testdir/shared.vim @@ -56,6 +56,9 @@ endfunc " Run "cmd". Returns the job if using a job. func RunCommand(cmd) + " Running an external command can occasionally be slow or fail. + let g:test_is_flaky = 1 + let job = 0 if has('job') let job = job_start(a:cmd, {"stoponexit": "hup"}) @@ -294,6 +297,13 @@ func GetVimCommandClean() return cmd endfunc +" Get the command to run Vim, with --clean, and force to run in terminal so it +" won't start a new GUI. +func GetVimCommandCleanTerm() + " Add -v to have gvim run in the terminal (if possible) + return GetVimCommandClean() .. ' -v ' +endfunc + " Run Vim, using the "vimcmd" file and "-u NORC". " "before" is a list of Vim commands to be executed before loading plugins. " "after" is a list of Vim commands to be executed after loading plugins. diff --git a/src/nvim/testdir/test_alot.vim b/src/nvim/testdir/test_alot.vim index 5668f45dea..7647475427 100644 --- a/src/nvim/testdir/test_alot.vim +++ b/src/nvim/testdir/test_alot.vim @@ -13,7 +13,6 @@ source test_ex_undo.vim source test_ex_z.vim source test_execute_func.vim source test_expand_func.vim -source test_expr.vim source test_feedkeys.vim source test_filter_cmd.vim source test_filter_map.vim @@ -50,6 +49,7 @@ source test_tagjump.vim source test_taglist.vim source test_true_false.vim source test_unlet.vim +source test_version.vim source test_virtualedit.vim source test_window_cmd.vim source test_wnext.vim diff --git a/src/nvim/testdir/test_display.vim b/src/nvim/testdir/test_display.vim index 429253a863..e853b046dc 100644 --- a/src/nvim/testdir/test_display.vim +++ b/src/nvim/testdir/test_display.vim @@ -184,3 +184,40 @@ func Test_scroll_CursorLineNr_update() call StopVimInTerminal(buf) call delete(filename) endfunc + +" Test for scrolling that modifies buffer during visual block +func Test_visual_block_scroll() + " See test/functional/legacy/visual_mode_spec.lua + CheckScreendump + + let lines =<< trim END + source $VIMRUNTIME/plugin/matchparen.vim + set scrolloff=1 + call setline(1, ['a', 'b', 'c', 'd', 'e', '', '{', '}', '{', 'f', 'g', '}']) + call cursor(5, 1) + END + + let filename = 'Xvisualblockmodifiedscroll' + call writefile(lines, filename) + + let buf = RunVimInTerminal('-S '.filename, #{rows: 7}) + call term_sendkeys(buf, "V\<C-D>\<C-D>") + + call VerifyScreenDump(buf, 'Test_display_visual_block_scroll', {}) + + call StopVimInTerminal(buf) + call delete(filename) +endfunc + +func Test_display_scroll_at_topline() + " See test/functional/legacy/display_spec.lua + CheckScreendump + + let buf = RunVimInTerminal('', #{cols: 20}) + call term_sendkeys(buf, ":call setline(1, repeat('a', 21))\<CR>") + call term_wait(buf) + call term_sendkeys(buf, "O\<Esc>") + call VerifyScreenDump(buf, 'Test_display_scroll_at_topline', #{rows: 4}) + + call StopVimInTerminal(buf) +endfunc diff --git a/src/nvim/testdir/test_edit.vim b/src/nvim/testdir/test_edit.vim index 7f456ffbce..caebc341e0 100644 --- a/src/nvim/testdir/test_edit.vim +++ b/src/nvim/testdir/test_edit.vim @@ -1534,3 +1534,48 @@ func Test_edit_noesckeys() bwipe! " set esckeys endfunc + +" Test for editing a directory +func Test_edit_is_a_directory() + CheckEnglish + let dirname = getcwd() . "/Xdir" + call mkdir(dirname, 'p') + + new + redir => msg + exe 'edit' dirname + redir END + call assert_match("is a directory$", split(msg, "\n")[0]) + bwipe! + + let dirname .= '/' + + new + redir => msg + exe 'edit' dirname + redir END + call assert_match("is a directory$", split(msg, "\n")[0]) + bwipe! + + call delete(dirname, 'rf') +endfunc + +func Test_edit_browse() + " in the GUI this opens a file picker, we only test the terminal behavior + CheckNotGui + + " ":browse xxx" checks for the FileExplorer augroup and assumes editing "." + " works then. + augroup FileExplorer + au! + augroup END + + " When the USE_FNAME_CASE is defined this used to cause a crash. + browse enew + bwipe! + + browse split + bwipe! +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_functions.vim b/src/nvim/testdir/test_functions.vim index 8fa70a5313..00f0126582 100644 --- a/src/nvim/testdir/test_functions.vim +++ b/src/nvim/testdir/test_functions.vim @@ -1083,6 +1083,12 @@ func Test_trim() call assert_equal("", trim("", "")) call assert_equal("a", trim("a", "")) call assert_equal("", trim("", "a")) + call assert_equal("vim", trim(" vim ", " ", 0)) + call assert_equal("vim ", trim(" vim ", " ", 1)) + call assert_equal(" vim", trim(" vim ", " ", 2)) + call assert_fails('call trim(" vim ", " ", [])', 'E745:') + call assert_fails('call trim(" vim ", " ", -1)', 'E475:') + call assert_fails('call trim(" vim ", " ", 3)', 'E475:') let chars = join(map(range(1, 0x20) + [0xa0], {n -> nr2char(n)}), '') call assert_equal("x", trim(chars . "x" . chars)) diff --git a/src/nvim/testdir/test_gn.vim b/src/nvim/testdir/test_gn.vim index d41675be0c..9acec51913 100644 --- a/src/nvim/testdir/test_gn.vim +++ b/src/nvim/testdir/test_gn.vim @@ -158,7 +158,32 @@ func Test_gn_command() set wrapscan&vim set belloff&vim -endfu +endfunc + +func Test_gN_repeat() + new + call setline(1, 'this list is a list with a list of a list.') + /list + normal $gNgNgNx + call assert_equal('list with a list of a list', @") + bwipe! +endfunc + +func Test_gN_then_gn() + new + + call setline(1, 'this list is a list with a list of a last.') + /l.st + normal $gNgNgnx + call assert_equal('last', @") + + call setline(1, 'this list is a list with a lust of a last.') + /l.st + normal $gNgNgNgnx + call assert_equal('lust of a last', @") + + bwipe! +endfunc func Test_gn_multi_line() new diff --git a/src/nvim/testdir/test_highlight.vim b/src/nvim/testdir/test_highlight.vim index 6aa187b17e..00e42733a7 100644 --- a/src/nvim/testdir/test_highlight.vim +++ b/src/nvim/testdir/test_highlight.vim @@ -596,9 +596,17 @@ endfunc " This test must come before the Test_cursorline test, as it appears this " defines the Normal highlighting group anyway. func Test_1_highlight_Normalgroup_exists() - " MS-Windows GUI sets the font - if !has('win32') || !has('gui_running') - let hlNormal = HighlightArgs('Normal') + let hlNormal = HighlightArgs('Normal') + if !has('gui_running') call assert_match('hi Normal\s*clear', hlNormal) + elseif has('gui_gtk2') || has('gui_gnome') || has('gui_gtk3') + " expect is DEFAULT_FONT of gui_gtk_x11.c + call assert_match('hi Normal\s*font=Monospace 10', hlNormal) + elseif has('gui_motif') || has('gui_athena') + " expect is DEFAULT_FONT of gui_x11.c + call assert_match('hi Normal\s*font=7x13', hlNormal) + elseif has('win32') + " expect any font + call assert_match('hi Normal\s*font=.*', hlNormal) endif endfunc diff --git a/src/nvim/testdir/test_ins_complete.vim b/src/nvim/testdir/test_ins_complete.vim index 1c275d5bd1..1339a9f25d 100644 --- a/src/nvim/testdir/test_ins_complete.vim +++ b/src/nvim/testdir/test_ins_complete.vim @@ -1,3 +1,5 @@ +source screendump.vim +source check.vim " Test for insert expansion func Test_ins_complete() @@ -338,3 +340,27 @@ func Test_compl_in_cmdwin() delcom GetInput set wildmenu& wildchar& endfunc + +func Test_pum_with_folds_two_tabs() + CheckScreendump + + let lines =<< trim END + set fdm=marker + call setline(1, ['" x {{{1', '" a some text']) + call setline(3, range(&lines)->map({_, val -> '" a' .. val})) + norm! zm + tab sp + call feedkeys('2Gzv', 'xt') + call feedkeys("0fa", 'xt') + END + + call writefile(lines, 'Xpumscript') + let buf = RunVimInTerminal('-S Xpumscript', #{rows: 10}) + call term_wait(buf, 100) + call term_sendkeys(buf, "a\<C-N>") + call VerifyScreenDump(buf, 'Test_pum_with_folds_two_tabs', {}) + + call term_sendkeys(buf, "\<Esc>") + call StopVimInTerminal(buf) + call delete('Xpumscript') +endfunc diff --git a/src/nvim/testdir/test_listdict.vim b/src/nvim/testdir/test_listdict.vim index bea62cb0ad..31a8b48d37 100644 --- a/src/nvim/testdir/test_listdict.vim +++ b/src/nvim/testdir/test_listdict.vim @@ -280,6 +280,14 @@ func Test_dict_func_remove_in_use() call assert_equal(expected, d.func(string(remove(d, 'func')))) endfunc +func Test_dict_literal_keys() + call assert_equal({'one': 1, 'two2': 2, '3three': 3, '44': 4}, #{one: 1, two2: 2, 3three: 3, 44: 4},) + + " why *{} cannot be used + let blue = 'blue' + call assert_equal('6', trim(execute('echo 2 *{blue: 3}.blue'))) +endfunc + " Nasty: deepcopy() dict that refers to itself (fails when noref used) func Test_dict_deepcopy() let d = {1:1, 2:2} diff --git a/src/nvim/testdir/test_mapping.vim b/src/nvim/testdir/test_mapping.vim index dd0da5db64..152afb4b9d 100644 --- a/src/nvim/testdir/test_mapping.vim +++ b/src/nvim/testdir/test_mapping.vim @@ -406,7 +406,7 @@ func Test_error_in_map_expr() [CODE] call writefile(lines, 'Xtest.vim') - let buf = term_start(GetVimCommandClean() .. ' -S Xtest.vim', {'term_rows': 8}) + let buf = term_start(GetVimCommandCleanTerm() .. ' -S Xtest.vim', {'term_rows': 8}) let job = term_getjob(buf) call WaitForAssert({-> assert_notequal('', term_getline(buf, 8))}) diff --git a/src/nvim/testdir/test_matchadd_conceal.vim b/src/nvim/testdir/test_matchadd_conceal.vim index b918525dbc..393e183ddb 100644 --- a/src/nvim/testdir/test_matchadd_conceal.vim +++ b/src/nvim/testdir/test_matchadd_conceal.vim @@ -1,9 +1,11 @@ " Test for matchadd() and conceal feature -if !has('conceal') - finish -endif + +source check.vim +CheckFeature conceal source shared.vim +source term_util.vim +source view_util.vim function! Test_simple_matchadd() new @@ -273,3 +275,70 @@ function! Test_matchadd_and_syn_conceal() call assert_notequal(screenattr(1, 11) , screenattr(1, 12)) call assert_equal(screenattr(1, 11) , screenattr(1, 32)) endfunction + +func Test_cursor_column_in_concealed_line_after_window_scroll() + CheckRunVimInTerminal + + " Test for issue #5012 fix. + " For a concealed line with cursor, there should be no window's cursor + " position invalidation during win_update() after scrolling attempt that is + " not successful and no real topline change happens. The invalidation would + " cause a window's cursor position recalc outside of win_line() where it's + " not possible to take conceal into account. + let lines =<< trim END + 3split + let m = matchadd('Conceal', '=') + setl conceallevel=2 concealcursor=nc + normal gg + "==expr== + END + call writefile(lines, 'Xcolesearch') + let buf = RunVimInTerminal('Xcolesearch', {}) + call term_wait(buf, 100) + + " Jump to something that is beyond the bottom of the window, + " so there's a scroll down. + call term_sendkeys(buf, ":so %\<CR>") + call term_wait(buf, 100) + call term_sendkeys(buf, "/expr\<CR>") + call term_wait(buf, 100) + + " Are the concealed parts of the current line really hidden? + let cursor_row = term_scrape(buf, '.')->map({_, e -> e.chars})->join('') + call assert_equal('"expr', cursor_row) + + " BugFix check: Is the window's cursor column properly updated for hidden + " parts of the current line? + call assert_equal(2, term_getcursor(buf)[1]) + + call StopVimInTerminal(buf) + call delete('Xcolesearch') +endfunc + +func Test_cursor_column_in_concealed_line_after_leftcol_change() + CheckRunVimInTerminal + + " Test for issue #5214 fix. + let lines =<< trim END + 0put = 'ab' .. repeat('-', &columns) .. 'c' + call matchadd('Conceal', '-') + set nowrap ss=0 cole=3 cocu=n + END + call writefile(lines, 'Xcurs-columns') + let buf = RunVimInTerminal('-S Xcurs-columns', {}) + + " Go to the end of the line (3 columns beyond the end of the screen). + " Horizontal scroll would center the cursor in the screen line, but conceal + " makes it go to screen column 1. + call term_sendkeys(buf, "$") + call term_wait(buf) + + " Are the concealed parts of the current line really hidden? + call WaitForAssert({-> assert_equal('c', term_getline(buf, '.'))}) + + " BugFix check: Is the window's cursor column properly updated for conceal? + call assert_equal(1, term_getcursor(buf)[1]) + + call StopVimInTerminal(buf) + call delete('Xcurs-columns') +endfunc diff --git a/src/nvim/testdir/test_perl.vim b/src/nvim/testdir/test_perl.vim index 2343f389fa..872194a804 100644 --- a/src/nvim/testdir/test_perl.vim +++ b/src/nvim/testdir/test_perl.vim @@ -4,6 +4,7 @@ if !has('perl') || has('win32') finish endif +" FIXME: RunTest don't see any error when Perl abort... perl $SIG{__WARN__} = sub { die "Unexpected warnings from perl: @_" }; func Test_change_buffer() @@ -23,11 +24,15 @@ func Test_evaluate_list() $l = VIM::Eval("l"); $curbuf->Append($curline, $l); EOF + normal j + .perldo s|\n|/|g + " call assert_equal('abc/def/', getline('$')) + call assert_equal('def', getline('$')) endfunc funct Test_VIM_Blob() call assert_equal('0z', perleval('VIM::Blob("")')) - "call assert_equal('0z31326162', 'VIM::Blob("12ab")'->perleval()) + call assert_equal('0z31326162', perleval('VIM::Blob("12ab")')) call assert_equal('0z00010203', perleval('VIM::Blob("\x00\x01\x02\x03")')) call assert_equal('0z8081FEFF', perleval('VIM::Blob("\x80\x81\xfe\xff")')) endfunc @@ -46,7 +51,6 @@ func Test_buffer_Append() new perl $curbuf->Append(1, '1') perl $curbuf->Append(2, '2', '3', '4') - call assert_equal(['', '1', '2', '3', '4'], getline(1, '$')) perl @l = ('5' ..'7') perl $curbuf->Append(0, @l) call assert_equal(['5', '6', '7', '', '1', '2', '3', '4'], getline(1, '$')) @@ -114,7 +118,7 @@ func Test_VIM_Windows() perl $curbuf->Append(0, $winnr, scalar(@winlist)) call assert_equal(['2', '2', ''], getline(1, '$')) - "" VIM::Windows() with window number argument. + " VIM::Windows() with window number argument. perl (VIM::Windows(VIM::Eval('winnr()')))[0]->Buffer()->Set(1, 'bar') call assert_equal('bar', getline(1)) bwipe! @@ -133,10 +137,20 @@ func Test_VIM_Buffers() bwipe! endfunc +func <SID>catch_peval(expr) + try + call perleval(a:expr) + catch + return v:exception + endtry + call assert_report('no exception for `perleval("'.a:expr.'")`') + return '' +endfunc + func Test_perleval() call assert_false(perleval('undef')) - "" scalar + " scalar call assert_equal(0, perleval('0')) call assert_equal(2, perleval('2')) call assert_equal(-2, perleval('-2')) @@ -146,9 +160,12 @@ func Test_perleval() call assert_equal(2, perleval('2.5')) end + " sandbox call assert_equal(2, perleval('2')) + call assert_equal('abc', perleval('"abc"')) + " call assert_equal("abc\ndef", perleval('"abc\0def"')) - "" ref + " ref call assert_equal([], perleval('[]')) call assert_equal(['word', 42, [42],{}], perleval('["word", 42, [42], {}]')) @@ -156,13 +173,19 @@ func Test_perleval() call assert_equal({'foo': 'bar'}, perleval('{foo => "bar"}')) perl our %h; our @a; - let a = perleval('[\%h, \%h, \@a, \@a]') - echo a + let a = perleval('[\(%h, %h, @a, @a)]') + " call assert_true((a[0] is a[1])) call assert_equal(a[0], a[1]) + " call assert_true((a[2] is a[3])) call assert_equal(a[2], a[3]) perl undef %h; undef @a; + " call assert_true(<SID>catch_peval('{"" , 0}') =~ 'Malformed key Dictionary') + " call assert_true(<SID>catch_peval('{"\0" , 0}') =~ 'Malformed key Dictionary') + " call assert_true(<SID>catch_peval('{"foo\0bar" , 0}') =~ 'Malformed key Dictionary') + call assert_equal('*VIM', perleval('"*VIM"')) + " call assert_true(perleval('\\0') =~ 'SCALAR(0x\x\+)') endfunc func Test_perldo() @@ -179,7 +202,7 @@ func Test_perldo() perldo VIM::DoCommand("%d_") bwipe! - "" Check switching to another buffer does not trigger ml_get error. + " Check switching to another buffer does not trigger ml_get error. new let wincount = winnr('$') call setline(1, ['one', 'two', 'three']) @@ -198,6 +221,69 @@ func Test_VIM_package() call assert_true(&et) endfunc +func Test_stdio() + throw 'skipped: TODO: ' + redir =>l:out + perl <<EOF + VIM::Msg("&VIM::Msg"); + print "STDOUT"; + print STDERR "STDERR"; +EOF + redir END + call assert_equal(['&VIM::Msg', 'STDOUT', 'STDERR'], split(l:out, "\n")) +endfunc + +" Run first to get a clean namespace +func Test_000_SvREFCNT() + throw 'skipped: TODO: ' + for i in range(8) + exec 'new X'.i + endfor + new t + perl <<--perl +#line 5 "Test_000_SvREFCNT()" + my ($b, $w); + + my $num = 0; + for ( 0 .. 100 ) { + if ( ++$num >= 8 ) { $num = 0 } + VIM::DoCommand("buffer X$num"); + $b = $curbuf; + } + + VIM::DoCommand("buffer t"); + + $b = $curbuf for 0 .. 100; + $w = $curwin for 0 .. 100; + () = VIM::Buffers for 0 .. 100; + () = VIM::Windows for 0 .. 100; + + VIM::DoCommand('bw! t'); + if (exists &Internals::SvREFCNT) { + my $cb = Internals::SvREFCNT($$b); + my $cw = Internals::SvREFCNT($$w); + VIM::Eval("assert_equal(2, $cb, 'T1')"); + VIM::Eval("assert_equal(2, $cw, 'T2')"); + my $strongref; + foreach ( VIM::Buffers, VIM::Windows ) { + VIM::DoCommand("%bw!"); + my $c = Internals::SvREFCNT($_); + VIM::Eval("assert_equal(2, $c, 'T3')"); + $c = Internals::SvREFCNT($$_); + next if $c == 2 && !$strongref++; + VIM::Eval("assert_equal(1, $c, 'T4')"); + } + $cb = Internals::SvREFCNT($$curbuf); + $cw = Internals::SvREFCNT($$curwin); + VIM::Eval("assert_equal(3, $cb, 'T5')"); + VIM::Eval("assert_equal(3, $cw, 'T6')"); + } + VIM::Eval("assert_false($$b)"); + VIM::Eval("assert_false($$w)"); +--perl + %bw! +endfunc + func Test_set_cursor() " Check that setting the cursor position works. new diff --git a/src/nvim/testdir/test_popup.vim b/src/nvim/testdir/test_popup.vim index bb0ed6e00c..fb464d95ea 100644 --- a/src/nvim/testdir/test_popup.vim +++ b/src/nvim/testdir/test_popup.vim @@ -2,6 +2,7 @@ source shared.vim source screendump.vim +source check.vim let g:months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] let g:setting = '' @@ -755,6 +756,52 @@ func Test_popup_and_previewwindow_dump() call delete('Xscript') endfunc +func Test_balloon_split() + CheckFunction balloon_split + + call assert_equal([ + \ 'tempname: 0x555555e380a0 "/home/mool/.viminfz.tmp"', + \ ], balloon_split( + \ 'tempname: 0x555555e380a0 "/home/mool/.viminfz.tmp"')) + call assert_equal([ + \ 'one two three four one two three four one two thre', + \ 'e four', + \ ], balloon_split( + \ 'one two three four one two three four one two three four')) + + eval 'struct = {one = 1, two = 2, three = 3}' + \ ->balloon_split() + \ ->assert_equal([ + \ 'struct = {', + \ ' one = 1,', + \ ' two = 2,', + \ ' three = 3}', + \ ]) + + call assert_equal([ + \ 'struct = {', + \ ' one = 1,', + \ ' nested = {', + \ ' n1 = "yes",', + \ ' n2 = "no"}', + \ ' two = 2}', + \ ], balloon_split( + \ 'struct = {one = 1, nested = {n1 = "yes", n2 = "no"} two = 2}')) + call assert_equal([ + \ 'struct = 0x234 {', + \ ' long = 2343 "\\"some long string that will be wr', + \ 'apped in two\\"",', + \ ' next = 123}', + \ ], balloon_split( + \ 'struct = 0x234 {long = 2343 "\\"some long string that will be wrapped in two\\"", next = 123}')) + call assert_equal([ + \ 'Some comment', + \ '', + \ 'typedef this that;', + \ ], balloon_split( + \ "Some comment\n\ntypedef this that;")) +endfunc + func Test_popup_position() if !CanRunVimInTerminal() return diff --git a/src/nvim/testdir/test_quickfix.vim b/src/nvim/testdir/test_quickfix.vim index fab5cb320f..d46233991c 100644 --- a/src/nvim/testdir/test_quickfix.vim +++ b/src/nvim/testdir/test_quickfix.vim @@ -1,8 +1,7 @@ " Test for the quickfix commands. -if !has('quickfix') - finish -endif +source check.vim +CheckFeature quickfix set encoding=utf-8 @@ -95,7 +94,7 @@ func XlistTests(cchar) " Populate the list and then try Xgetexpr ['non-error 1', 'Xtestfile1:1:3:Line1', \ 'non-error 2', 'Xtestfile2:2:2:Line2', - \ 'non-error 3', 'Xtestfile3:3:1:Line3'] + \ 'non-error| 3', 'Xtestfile3:3:1:Line3'] " List only valid entries let l = split(execute('Xlist', ''), "\n") @@ -107,7 +106,7 @@ func XlistTests(cchar) let l = split(execute('Xlist!', ''), "\n") call assert_equal([' 1: non-error 1', ' 2 Xtestfile1:1 col 3: Line1', \ ' 3: non-error 2', ' 4 Xtestfile2:2 col 2: Line2', - \ ' 5: non-error 3', ' 6 Xtestfile3:3 col 1: Line3'], l) + \ ' 5: non-error| 3', ' 6 Xtestfile3:3 col 1: Line3'], l) " List a range of errors let l = split(execute('Xlist 3,6', ''), "\n") @@ -507,7 +506,7 @@ func Xtest_browse(cchar) Xexpr "" call assert_equal(0, g:Xgetlist({'idx' : 0}).idx) call assert_equal(0, g:Xgetlist({'size' : 0}).size) - Xaddexpr ['foo', 'bar', 'baz', 'quux', 'shmoo'] + Xaddexpr ['foo', 'bar', 'baz', 'quux', 'sh|moo'] call assert_equal(5, g:Xgetlist({'size' : 0}).size) Xlast call assert_equal(5, g:Xgetlist({'idx' : 0}).idx) @@ -1284,6 +1283,30 @@ func Test_quickfix_was_changed_by_autocmd() call XquickfixChangedByAutocmd('l') endfunc +func Test_setloclist_in_autocommand() + call writefile(['test1', 'test2'], 'Xfile') + edit Xfile + let s:bufnr = bufnr() + call setloclist(1, + \ [{'bufnr' : s:bufnr, 'lnum' : 1, 'text' : 'test1'}, + \ {'bufnr' : s:bufnr, 'lnum' : 2, 'text' : 'test2'}]) + + augroup Test_LocList + au! + autocmd BufEnter * call setloclist(1, + \ [{'bufnr' : s:bufnr, 'lnum' : 1, 'text' : 'test1'}, + \ {'bufnr' : s:bufnr, 'lnum' : 2, 'text' : 'test2'}], 'r') + augroup END + + lopen + call assert_fails('exe "normal j\<CR>"', 'E926:') + + augroup Test_LocList + au! + augroup END + call delete('Xfile') +endfunc + func Test_caddbuffer_to_empty() helpgr quickfix call setqflist([], 'r') @@ -1597,6 +1620,24 @@ func Test_long_lines() call s:long_lines_tests('l') endfunc +func Test_cgetfile_on_long_lines() + " Problematic values if the line is longer than 4096 bytes. Then 1024 bytes + " are read at a time. + for len in [4078, 4079, 4080, 5102, 5103, 5104, 6126, 6127, 6128, 7150, 7151, 7152] + let lines = [ + \ '/tmp/file1:1:1:aaa', + \ '/tmp/file2:1:1:%s', + \ '/tmp/file3:1:1:bbb', + \ '/tmp/file4:1:1:ccc', + \ ] + let lines[1] = substitute(lines[1], '%s', repeat('x', len), '') + call writefile(lines, 'Xcqetfile.txt') + cgetfile Xcqetfile.txt + call assert_equal(4, getqflist(#{size: v:true}).size, 'with length ' .. len) + endfor + call delete('Xcqetfile.txt') +endfunc + func s:create_test_file(filename) let l = [] for i in range(1, 20) @@ -1874,6 +1915,13 @@ func HistoryTest(cchar) call g:Xsetlist([], 'f') let l = split(execute(a:cchar . 'hist'), "\n") call assert_equal('No entries', l[0]) + + " An empty list should still show the stack history + call g:Xsetlist([]) + let res = split(execute(a:cchar . 'hist'), "\n") + call assert_equal('> error list 1 of 1; 0 ' . common, res[0]) + + call g:Xsetlist([], 'f') endfunc func Test_history() @@ -2124,6 +2172,9 @@ func Xproperty_tests(cchar) call assert_equal(['Colors'], newl2.context) call assert_equal('Line10', newl2.items[0].text) call g:Xsetlist([], 'f') + + " Cannot specify both a non-empty list argument and a dict argument + call assert_fails("call g:Xsetlist([{}], ' ', {})", 'E475:') endfunc func Test_qf_property() @@ -2131,6 +2182,56 @@ func Test_qf_property() call Xproperty_tests('l') endfunc +" Test for setting the current index in the location/quickfix list +func Xtest_setqfidx(cchar) + call s:setup_commands(a:cchar) + + Xgetexpr "F1:10:1:Line1\nF2:20:2:Line2\nF3:30:3:Line3" + Xgetexpr "F4:10:1:Line1\nF5:20:2:Line2\nF6:30:3:Line3" + Xgetexpr "F7:10:1:Line1\nF8:20:2:Line2\nF9:30:3:Line3" + + call g:Xsetlist([], 'a', {'nr' : 3, 'idx' : 2}) + call g:Xsetlist([], 'a', {'nr' : 2, 'idx' : 2}) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 3}) + Xolder 2 + Xopen + call assert_equal(3, line('.')) + Xnewer + call assert_equal(2, line('.')) + Xnewer + call assert_equal(2, line('.')) + " Update the current index with the quickfix window open + wincmd w + call g:Xsetlist([], 'a', {'nr' : 3, 'idx' : 3}) + Xopen + call assert_equal(3, line('.')) + Xclose + + " Set the current index to the last entry + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : '$'}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + " A large value should set the index to the last index + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 1}) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 999}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + " Invalid index values + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : -1}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 0}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + call g:Xsetlist([], 'a', {'nr' : 1, 'idx' : 'xx'}) + call assert_equal(3, g:Xgetlist({'nr' : 1, 'idx' : 0}).idx) + call assert_fails("call g:Xsetlist([], 'a', {'nr':1, 'idx':[]})", 'E745:') + + call g:Xsetlist([], 'f') + new | only +endfunc + +func Test_setqfidx() + call Xtest_setqfidx('c') + call Xtest_setqfidx('l') +endfunc + " Tests for the QuickFixCmdPre/QuickFixCmdPost autocommands func QfAutoCmdHandler(loc, cmd) call add(g:acmds, a:loc . a:cmd) @@ -2466,6 +2567,41 @@ func Test_vimgrep_incsearch() set noincsearch endfunc +" Test vimgrep without swap file +func Test_vimgrep_without_swap_file() + let lines =<< trim [SCRIPT] + vimgrep grep test_c* + call writefile(['done'], 'Xresult') + qall! + [SCRIPT] + call writefile(lines, 'Xscript') + if RunVim([], [], '--clean -n -S Xscript Xscript') + call assert_equal(['done'], readfile('Xresult')) + endif + call delete('Xscript') + call delete('Xresult') +endfunc + +func Test_vimgrep_existing_swapfile() + call writefile(['match apple with apple'], 'Xapple') + call writefile(['swapfile'], '.Xapple.swp') + let g:foundSwap = 0 + let g:ignoreSwapExists = 1 + augroup grep + au SwapExists * let foundSwap = 1 | let v:swapchoice = 'e' + augroup END + vimgrep apple Xapple + call assert_equal(1, g:foundSwap) + call assert_match('.Xapple.swo', swapname('')) + + call delete('Xapple') + call delete('Xapple.swp') + augroup grep + au! SwapExists + augroup END + unlet g:ignoreSwapExists +endfunc + func XfreeTests(cchar) call s:setup_commands(a:cchar) @@ -3118,19 +3254,21 @@ func Xgetlist_empty_tests(cchar) call assert_equal(0, g:Xgetlist({'changedtick' : 0}).changedtick) if a:cchar == 'c' call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, - \ 'items' : [], 'nr' : 0, 'size' : 0, + \ 'items' : [], 'nr' : 0, 'size' : 0, 'qfbufnr' : 0, \ 'title' : '', 'winid' : 0, 'changedtick': 0}, \ g:Xgetlist({'all' : 0})) else call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, \ 'items' : [], 'nr' : 0, 'size' : 0, 'title' : '', - \ 'winid' : 0, 'changedtick': 0, 'filewinid' : 0}, + \ 'winid' : 0, 'changedtick': 0, 'filewinid' : 0, + \ 'qfbufnr' : 0}, \ g:Xgetlist({'all' : 0})) endif " Quickfix window with empty stack silent! Xopen let qfwinid = (a:cchar == 'c') ? win_getid() : 0 + let qfbufnr = (a:cchar == 'c') ? bufnr('') : 0 call assert_equal(qfwinid, g:Xgetlist({'winid' : 0}).winid) Xclose @@ -3162,11 +3300,12 @@ func Xgetlist_empty_tests(cchar) if a:cchar == 'c' call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, + \ 'qfbufnr' : qfbufnr, \ 'changedtick' : 0}, g:Xgetlist({'id' : qfid, 'all' : 0})) else call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, - \ 'changedtick' : 0, 'filewinid' : 0}, + \ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0}, \ g:Xgetlist({'id' : qfid, 'all' : 0})) endif @@ -3183,11 +3322,12 @@ func Xgetlist_empty_tests(cchar) if a:cchar == 'c' call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, - \ 'changedtick' : 0}, g:Xgetlist({'nr' : 5, 'all' : 0})) + \ 'changedtick' : 0, 'qfbufnr' : qfbufnr}, + \ g:Xgetlist({'nr' : 5, 'all' : 0})) else call assert_equal({'context' : '', 'id' : 0, 'idx' : 0, 'items' : [], \ 'nr' : 0, 'size' : 0, 'title' : '', 'winid' : 0, - \ 'changedtick' : 0, 'filewinid' : 0}, + \ 'changedtick' : 0, 'filewinid' : 0, 'qfbufnr' : 0}, \ g:Xgetlist({'nr' : 5, 'all' : 0})) endif endfunc @@ -3358,6 +3498,17 @@ func Test_lvimgrep_crash() augroup QF_Test au! augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setloclist(0, [], 'r') + augroup END + call assert_fails('lvimgrep Test_lvimgrep_crash *', 'E926:') + augroup QF_Test + au! + augroup END + enew | only endfunc @@ -3448,6 +3599,37 @@ func Test_lhelpgrep_autocmd() call assert_equal('help', &filetype) call assert_equal(1, getloclist(0, {'nr' : '$'}).nr) au! QuickFixCmdPost + + new | only + augroup QF_Test + au! + au BufEnter * call setqflist([], 'f') + augroup END + call assert_fails('helpgrep quickfix', 'E925:') + augroup QF_Test + au! BufEnter + augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setqflist([], 'r') + augroup END + call assert_fails('helpgrep quickfix', 'E925:') + augroup QF_Test + au! BufEnter + augroup END + + new | only + augroup QF_Test + au! + au BufEnter * call setloclist(0, [], 'r') + augroup END + call assert_fails('lhelpgrep quickfix', 'E926:') + augroup QF_Test + au! BufEnter + augroup END + new | only endfunc @@ -3785,6 +3967,52 @@ func Test_curswant() cclose | helpclose endfunc +" Test for opening a file from the quickfix window using CTRL-W <Enter> +" doesn't leave an empty buffer around. +func Test_splitview() + call s:create_test_file('Xtestfile1') + call s:create_test_file('Xtestfile2') + new | only + let last_bufnr = bufnr('Test_sv_1', 1) + let l = ['Xtestfile1:2:Line2', 'Xtestfile2:4:Line4'] + cgetexpr l + copen + let numbufs = len(getbufinfo()) + exe "normal \<C-W>\<CR>" + copen + exe "normal j\<C-W>\<CR>" + " Make sure new empty buffers are not created + call assert_equal(numbufs, len(getbufinfo())) + " Creating a new buffer should use the next available buffer number + call assert_equal(last_bufnr + 4, bufnr("Test_sv_2", 1)) + bwipe Test_sv_1 + bwipe Test_sv_2 + new | only + + " When split opening files from location list window, make sure that two + " windows doesn't refer to the same location list + lgetexpr l + let locid = getloclist(0, {'id' : 0}).id + lopen + exe "normal \<C-W>\<CR>" + call assert_notequal(locid, getloclist(0, {'id' : 0}).id) + call assert_equal(0, getloclist(0, {'winid' : 0}).winid) + new | only + + " When split opening files from a helpgrep location list window, a new help + " window should be opend with a copy of the location list. + lhelpgrep window + let locid = getloclist(0, {'id' : 0}).id + lwindow + exe "normal j\<C-W>\<CR>" + call assert_notequal(locid, getloclist(0, {'id' : 0}).id) + call assert_equal(0, getloclist(0, {'winid' : 0}).winid) + new | only + + call delete('Xtestfile1') + call delete('Xtestfile2') +endfunc + " Test for parsing entries using visual screen column func Test_viscol() enew @@ -3841,6 +4069,83 @@ func Test_viscol() call delete('Xfile1') endfunc +" Test for the quickfix window buffer +func Xqfbuf_test(cchar) + call s:setup_commands(a:cchar) + + " Quickfix buffer should be reused across closing and opening a quickfix + " window + Xexpr "F1:10:Line10" + Xopen + let qfbnum = bufnr('') + Xclose + " Even after the quickfix window is closed, the buffer should be loaded + call assert_true(bufloaded(qfbnum)) + call assert_true(qfbnum, g:Xgetlist({'qfbufnr' : 0}).qfbufnr) + Xopen + " Buffer should be reused when opening the window again + call assert_equal(qfbnum, bufnr('')) + Xclose + + if a:cchar == 'l' + %bwipe + " For a location list, when both the file window and the location list + " window for the list are closed, then the buffer should be freed. + new | only + lexpr "F1:10:Line10" + let wid = win_getid() + lopen + let qfbnum = bufnr('') + call assert_match(qfbnum . ' %a- "\[Location List]"', execute('ls')) + close + " When the location list window is closed, the buffer name should not + " change to 'Quickfix List' + call assert_match(qfbnum . 'u h- "\[Location List]"', execute('ls!')) + call assert_true(bufloaded(qfbnum)) + + " After deleting a location list buffer using ":bdelete", opening the + " location list window should mark the buffer as a location list buffer. + exe "bdelete " . qfbnum + lopen + call assert_equal("quickfix", &buftype) + call assert_equal(1, getwininfo(win_getid(winnr()))[0].loclist) + call assert_equal(wid, getloclist(0, {'filewinid' : 0}).filewinid) + call assert_false(&swapfile) + lclose + + " When the location list is cleared for the window, the buffer should be + " removed + call setloclist(0, [], 'f') + call assert_false(bufexists(qfbnum)) + call assert_equal(0, getloclist(0, {'qfbufnr' : 0}).qfbufnr) + + " When the location list is freed with the location list window open, the + " location list buffer should not be lost. It should be reused when the + " location list is again populated. + lexpr "F1:10:Line10" + lopen + let wid = win_getid() + let qfbnum = bufnr('') + wincmd p + call setloclist(0, [], 'f') + lexpr "F1:10:Line10" + lopen + call assert_equal(wid, win_getid()) + call assert_equal(qfbnum, bufnr('')) + lclose + + " When the window with the location list is closed, the buffer should be + " removed + new | only + call assert_false(bufexists(qfbnum)) + endif +endfunc + +func Test_qfbuf() + call Xqfbuf_test('c') + call Xqfbuf_test('l') +endfunc + " Test to make sure that an empty quickfix buffer is not reused for loading " a normal buffer. func Test_empty_qfbuf() @@ -4049,4 +4354,46 @@ func Test_qfcmd_abort() augroup END endfunc +" Test for using a file in one of the parent directories. +func Test_search_in_dirstack() + call mkdir('Xtestdir/a/b/c', 'p') + let save_cwd = getcwd() + call writefile(["X1_L1", "X1_L2"], 'Xtestdir/Xfile1') + call writefile(["X2_L1", "X2_L2"], 'Xtestdir/a/Xfile2') + call writefile(["X3_L1", "X3_L2"], 'Xtestdir/a/b/Xfile3') + call writefile(["X4_L1", "X4_L2"], 'Xtestdir/a/b/c/Xfile4') + + let lines = "Entering dir Xtestdir\n" . + \ "Entering dir a\n" . + \ "Entering dir b\n" . + \ "Xfile2:2:X2_L2\n" . + \ "Leaving dir a\n" . + \ "Xfile1:2:X1_L2\n" . + \ "Xfile3:1:X3_L1\n" . + \ "Entering dir c\n" . + \ "Xfile4:2:X4_L2\n" . + \ "Leaving dir c\n" + set efm=%DEntering\ dir\ %f,%XLeaving\ dir\ %f,%f:%l:%m + cexpr lines .. "Leaving dir Xtestdir|\n" | let next = 1 + call assert_equal(11, getqflist({'size' : 0}).size) + call assert_equal(4, getqflist({'idx' : 0}).idx) + call assert_equal('X2_L2', getline('.')) + call assert_equal(1, next) + cnext + call assert_equal(6, getqflist({'idx' : 0}).idx) + call assert_equal('X1_L2', getline('.')) + cnext + call assert_equal(7, getqflist({'idx' : 0}).idx) + call assert_equal(1, line('$')) + call assert_equal('', getline(1)) + cnext + call assert_equal(9, getqflist({'idx' : 0}).idx) + call assert_equal(1, line('$')) + call assert_equal('', getline(1)) + + set efm& + exe 'cd ' . save_cwd + call delete('Xtestdir', 'rf') +endfunc + " vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_ruby.vim b/src/nvim/testdir/test_ruby.vim index 64199570a9..77a42e0a8a 100644 --- a/src/nvim/testdir/test_ruby.vim +++ b/src/nvim/testdir/test_ruby.vim @@ -4,6 +4,13 @@ if !has('ruby') finish end +" Helper function as there is no builtin rubyeval() function similar +" to perleval, luaevel() or pyeval(). +func RubyEval(ruby_expr) + let s = split(execute('ruby print ' . a:ruby_expr), "\n") + return (len(s) == 0) ? '' : s[-1] +endfunc + func Test_ruby_change_buffer() call setline(line('$'), ['1 line 1']) ruby Vim.command("normal /^1\n") @@ -11,37 +18,6 @@ func Test_ruby_change_buffer() call assert_equal('1 changed line 1', getline('$')) endfunc -func Test_ruby_evaluate_list() - throw 'skipped: TODO: ' - call setline(line('$'), ['2 line 2']) - ruby Vim.command("normal /^2\n") - let l = ["abc", "def"] - ruby << EOF - curline = $curbuf.line_number - l = Vim.evaluate("l"); - $curbuf.append(curline, l.join("\n")) -EOF - normal j - .rubydo $_ = $_.gsub(/\n/, '/') - call assert_equal('abc/def', getline('$')) -endfunc - -func Test_ruby_evaluate_dict() - let d = {'a': 'foo', 'b': 123} - redir => l:out - ruby d = Vim.evaluate("d"); print d - redir END - call assert_equal(['{"a"=>"foo", "b"=>123}'], split(l:out, "\n")) -endfunc - -func Test_ruby_evaluate_special_var() - let l = [v:true, v:false, v:null] - redir => l:out - ruby d = Vim.evaluate("l"); print d - redir END - call assert_equal(['[true, false, nil]'], split(l:out, "\n")) -endfunc - func Test_rubydo() throw 'skipped: TODO: ' " Check deleting lines does not trigger ml_get error. @@ -56,8 +32,7 @@ func Test_rubydo() call setline(1, ['one', 'two', 'three']) rubydo Vim.command("new") call assert_equal(wincount + 1, winnr('$')) - bwipe! - bwipe! + %bwipe! endfunc func Test_rubyfile() @@ -75,8 +50,337 @@ func Test_set_cursor() normal gg rubydo $curwin.cursor = [1, 5] call assert_equal([1, 6], [line('.'), col('.')]) + call assert_equal('[1, 5]', RubyEval('$curwin.cursor')) " Check that movement after setting cursor position keeps current column. normal j call assert_equal([2, 6], [line('.'), col('.')]) + call assert_equal('[2, 5]', RubyEval('$curwin.cursor')) + + " call assert_fails('ruby $curwin.cursor = [1]', + " \ 'ArgumentError: array length must be 2') + bwipe! +endfunc + +" Test buffer.count and buffer.length (number of lines in buffer) +func Test_buffer_count() + new + call setline(1, ['one', 'two', 'three']) + call assert_equal('3', RubyEval('$curbuf.count')) + call assert_equal('3', RubyEval('$curbuf.length')) + bwipe! +endfunc + +" Test buffer.name (buffer name) +func Test_buffer_name() + new Xfoo + call assert_equal(expand('%:p'), RubyEval('$curbuf.name')) + bwipe + call assert_equal('', RubyEval('$curbuf.name')) +endfunc + +" Test buffer.number (number of the buffer). +func Test_buffer_number() + new + call assert_equal(string(bufnr('%')), RubyEval('$curbuf.number')) + new + call assert_equal(string(bufnr('%')), RubyEval('$curbuf.number')) + + %bwipe +endfunc + +" Test buffer.delete({n}) (delete line {n}) +func Test_buffer_delete() + new + call setline(1, ['one', 'two', 'three']) + ruby $curbuf.delete(2) + call assert_equal(['one', 'three'], getline(1, '$')) + + " call assert_fails('ruby $curbuf.delete(0)', 'IndexError: line number 0 out of range') + " call assert_fails('ruby $curbuf.delete(3)', 'IndexError: line number 3 out of range') + call assert_fails('ruby $curbuf.delete(3)', 'RuntimeError: Index out of bounds') + + bwipe! +endfunc + +" Test buffer.append({str}, str) (append line {str} after line {n}) +func Test_buffer_append() + new + ruby $curbuf.append(0, 'one') + ruby $curbuf.append(1, 'three') + ruby $curbuf.append(1, 'two') + ruby $curbuf.append(4, 'four') + + call assert_equal(['one', 'two', 'three', '', 'four'], getline(1, '$')) + + " call assert_fails('ruby $curbuf.append(-1, "x")', + " \ 'IndexError: line number -1 out of range') + call assert_fails('ruby $curbuf.append(-1, "x")', + \ 'ArgumentError: Index out of bounds') + call assert_fails('ruby $curbuf.append(6, "x")', + \ 'RuntimeError: Index out of bounds') + + bwipe! +endfunc + +" Test buffer.line (get or set the current line) +func Test_buffer_line() + new + call setline(1, ['one', 'two', 'three']) + 2 + call assert_equal('two', RubyEval('$curbuf.line')) + + ruby $curbuf.line = 'TWO' + call assert_equal(['one', 'TWO', 'three'], getline(1, '$')) + + bwipe! +endfunc + +" Test buffer.line_number (get current line number) +func Test_buffer_line_number() + new + call setline(1, ['one', 'two', 'three']) + 2 + call assert_equal('2', RubyEval('$curbuf.line_number')) + + bwipe! +endfunc + +func Test_buffer_get() + new + call setline(1, ['one', 'two']) + call assert_equal('one', RubyEval('$curbuf[1]')) + call assert_equal('two', RubyEval('$curbuf[2]')) + + " call assert_fails('ruby $curbuf[0]', + " \ 'IndexError: line number 0 out of range') + call assert_fails('ruby $curbuf[3]', + \ 'RuntimeError: Index out of bounds') + + bwipe! +endfunc + +func Test_buffer_set() + new + call setline(1, ['one', 'two']) + ruby $curbuf[2] = 'TWO' + ruby $curbuf[1] = 'ONE' + + " call assert_fails('ruby $curbuf[0] = "ZERO"', + " \ 'IndexError: line number 0 out of range') + " call assert_fails('ruby $curbuf[3] = "THREE"', + " \ 'IndexError: line number 3 out of range') + call assert_fails('ruby $curbuf[3] = "THREE"', + \ 'RuntimeError: Index out of bounds') + bwipe! +endfunc + +" Test window.width (get or set window height). +func Test_window_height() + new + + " Test setting window height + ruby $curwin.height = 2 + call assert_equal(2, winheight(0)) + + " Test getting window height + call assert_equal('2', RubyEval('$curwin.height')) + + bwipe +endfunc + +" Test window.width (get or set window width). +func Test_window_width() + vnew + + " Test setting window width + ruby $curwin.width = 2 + call assert_equal(2, winwidth(0)) + + " Test getting window width + call assert_equal('2', RubyEval('$curwin.width')) + + bwipe +endfunc + +" Test window.buffer (get buffer object of a window object). +func Test_window_buffer() + new Xfoo1 + new Xfoo2 + ruby $b2 = $curwin.buffer + ruby $w2 = $curwin + wincmd j + ruby $b1 = $curwin.buffer + ruby $w1 = $curwin + + " call assert_equal(RubyEval('$b1'), RubyEval('$w1.buffer')) + " call assert_equal(RubyEval('$b2'), RubyEval('$w2.buffer')) + call assert_equal(string(bufnr('Xfoo1')), RubyEval('$w1.buffer.number')) + call assert_equal(string(bufnr('Xfoo2')), RubyEval('$w2.buffer.number')) + + ruby $b1, $w1, $b2, $w2 = nil + %bwipe +endfunc + +" Test Vim::Window.current (get current window object) +func Test_Vim_window_current() + let cw = RubyEval('$curwin') + " call assert_equal(cw, RubyEval('Vim::Window.current')) + call assert_match('^#<Neovim::Window:0x\x\+>$', cw) +endfunc + +" Test Vim::Window.count (number of windows) +func Test_Vim_window_count() + new Xfoo1 + new Xfoo2 + split + call assert_equal('4', RubyEval('Vim::Window.count')) + %bwipe + call assert_equal('1', RubyEval('Vim::Window.count')) +endfunc + +" Test Vim::Window[n] (get window object of window n) +func Test_Vim_window_get() + new Xfoo1 + new Xfoo2 + call assert_match('Xfoo2$', RubyEval('Vim::Window[0].buffer.name')) + wincmd j + call assert_match('Xfoo1$', RubyEval('Vim::Window[1].buffer.name')) + wincmd j + call assert_equal('', RubyEval('Vim::Window[2].buffer.name')) + %bwipe +endfunc + +" Test Vim::Buffer.current (return the buffer object of current buffer) +func Test_Vim_buffer_current() + let cb = RubyEval('$curbuf') + " call assert_equal(cb, RubyEval('Vim::Buffer.current')) + call assert_match('^#<Neovim::Buffer:0x\x\+>$', cb) +endfunc + +" Test Vim::Buffer:.count (return the number of buffers) +func Test_Vim_buffer_count() + new Xfoo1 + new Xfoo2 + call assert_equal('3', RubyEval('Vim::Buffer.count')) + %bwipe + call assert_equal('1', RubyEval('Vim::Buffer.count')) +endfunc + +" Test Vim::buffer[n] (return the buffer object of buffer number n) +func Test_Vim_buffer_get() + new Xfoo1 + new Xfoo2 + + " Index of Vim::Buffer[n] goes from 0 to the number of buffers. + call assert_equal('', RubyEval('Vim::Buffer[0].name')) + call assert_match('Xfoo1$', RubyEval('Vim::Buffer[1].name')) + call assert_match('Xfoo2$', RubyEval('Vim::Buffer[2].name')) + call assert_fails('ruby print Vim::Buffer[3].name', + \ "NoMethodError: undefined method `name' for nil:NilClass") + %bwipe +endfunc + +" Test Vim::command({cmd}) (execute a Ex command)) +" Test Vim::command({cmd}) +func Test_Vim_command() + new + call setline(1, ['one', 'two', 'three', 'four']) + ruby Vim::command('2,3d') + call assert_equal(['one', 'four'], getline(1, '$')) + bwipe! +endfunc + +" Test Vim::set_option (set a vim option) +func Test_Vim_set_option() + call assert_equal(0, &number) + ruby Vim::set_option('number') + call assert_equal(1, &number) + ruby Vim::set_option('nonumber') + call assert_equal(0, &number) +endfunc + +func Test_Vim_evaluate() + call assert_equal('123', RubyEval('Vim::evaluate("123")')) + " Vim::evaluate("123").class gives Integer or Fixnum depending + " on versions of Ruby. + call assert_match('^Integer\|Fixnum$', RubyEval('Vim::evaluate("123").class')) + + call assert_equal('1.23', RubyEval('Vim::evaluate("1.23")')) + call assert_equal('Float', RubyEval('Vim::evaluate("1.23").class')) + + call assert_equal('foo', RubyEval('Vim::evaluate("\"foo\"")')) + call assert_equal('String', RubyEval('Vim::evaluate("\"foo\"").class')) + + call assert_equal('[1, 2]', RubyEval('Vim::evaluate("[1, 2]")')) + call assert_equal('Array', RubyEval('Vim::evaluate("[1, 2]").class')) + + call assert_equal('{"1"=>2}', RubyEval('Vim::evaluate("{1:2}")')) + call assert_equal('Hash', RubyEval('Vim::evaluate("{1:2}").class')) + + call assert_equal('', RubyEval('Vim::evaluate("v:null")')) + call assert_equal('NilClass', RubyEval('Vim::evaluate("v:null").class')) + + " call assert_equal('', RubyEval('Vim::evaluate("v:none")')) + " call assert_equal('NilClass', RubyEval('Vim::evaluate("v:none").class')) + + call assert_equal('true', RubyEval('Vim::evaluate("v:true")')) + call assert_equal('TrueClass', RubyEval('Vim::evaluate("v:true").class')) + call assert_equal('false', RubyEval('Vim::evaluate("v:false")')) + call assert_equal('FalseClass',RubyEval('Vim::evaluate("v:false").class')) +endfunc + +func Test_Vim_evaluate_list() + call setline(line('$'), ['2 line 2']) + ruby Vim.command("normal /^2\n") + let l = ["abc", "def"] + ruby << EOF + curline = $curbuf.line_number + l = Vim.evaluate("l"); + $curbuf.append(curline, l.join("|")) +EOF + normal j + .rubydo $_ = $_.gsub(/\|/, '/') + call assert_equal('abc/def', getline('$')) +endfunc + +func Test_Vim_evaluate_dict() + let d = {'a': 'foo', 'b': 123} + redir => l:out + ruby d = Vim.evaluate("d"); print d + redir END + call assert_equal(['{"a"=>"foo", "b"=>123}'], split(l:out, "\n")) +endfunc + +" Test Vim::message({msg}) (display message {msg}) +func Test_Vim_message() + throw 'skipped: TODO: ' + ruby Vim::message('A message') + let messages = split(execute('message'), "\n") + call assert_equal('A message', messages[-1]) +endfunc + +func Test_print() + ruby print "Hello World!" + let messages = split(execute('message'), "\n") + call assert_equal('Hello World!', messages[-1]) +endfunc + +func Test_p() + ruby p 'Just a test' + let messages = split(execute('message'), "\n") + call assert_equal('"Just a test"', messages[-1]) + + " Check return values of p method + + call assert_equal('123', RubyEval('p(123)')) + call assert_equal('[1, 2, 3]', RubyEval('p(1, 2, 3)')) + + " Avoid the "message maintainer" line. + let $LANG = '' + messages clear + call assert_equal('true', RubyEval('p() == nil')) + + let messages = split(execute('message'), "\n") + call assert_equal(0, len(messages)) endfunc diff --git a/src/nvim/testdir/test_swap.vim b/src/nvim/testdir/test_swap.vim index e072e9ed7f..f27920d20f 100644 --- a/src/nvim/testdir/test_swap.vim +++ b/src/nvim/testdir/test_swap.vim @@ -1,5 +1,7 @@ " Tests for the swap feature +source check.vim + func s:swapname() return trim(execute('swapname')) endfunc @@ -305,3 +307,61 @@ func Test_swap_recover_ext() augroup END augroup! test_swap_recover_ext endfunc + +" Test for selecting 'q' in the attention prompt +func Test_swap_prompt_splitwin() + CheckRunVimInTerminal + + call writefile(['foo bar'], 'Xfile1') + edit Xfile1 + preserve " should help to make sure the swap file exists + + let buf = RunVimInTerminal('', {'rows': 20}) + call term_sendkeys(buf, ":set nomore\n") + call term_sendkeys(buf, ":set noruler\n") + call term_sendkeys(buf, ":split Xfile1\n") + call term_wait(buf) + call WaitForAssert({-> assert_match('^\[O\]pen Read-Only, (E)dit anyway, (R)ecover, (Q)uit, (A)bort: $', term_getline(buf, 20))}) + call term_sendkeys(buf, "q") + call term_wait(buf) + call term_sendkeys(buf, ":\<CR>") + call WaitForAssert({-> assert_match('^:$', term_getline(buf, 20))}) + call term_sendkeys(buf, ":echomsg winnr('$')\<CR>") + call term_wait(buf) + call WaitForAssert({-> assert_match('^1$', term_getline(buf, 20))}) + call StopVimInTerminal(buf) + %bwipe! + call delete('Xfile1') +endfunc + +func Test_swap_symlink() + if !has("unix") + return + endif + + call writefile(['text'], 'Xtestfile') + silent !ln -s -f Xtestfile Xtestlink + + set dir=. + + " Test that swap file uses the name of the file when editing through a + " symbolic link (so that editing the file twice is detected) + edit Xtestlink + call assert_match('Xtestfile\.swp$', s:swapname()) + bwipe! + + call mkdir('Xswapdir') + exe 'set dir=' . getcwd() . '/Xswapdir//' + + " Check that this also works when 'directory' ends with '//' + edit Xtestlink + call assert_match('Xtestfile\.swp$', s:swapname()) + bwipe! + + set dir& + call delete('Xtestfile') + call delete('Xtestlink') + call delete('Xswapdir', 'rf') +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_syntax.vim b/src/nvim/testdir/test_syntax.vim index 2404f113d9..2617aa3945 100644 --- a/src/nvim/testdir/test_syntax.vim +++ b/src/nvim/testdir/test_syntax.vim @@ -475,6 +475,40 @@ func Test_bg_detection() hi Normal ctermbg=NONE endfunc +func Test_syntax_hangs() + if !has('reltime') || !has('float') || !has('syntax') + return + endif + + " This pattern takes a long time to match, it should timeout. + new + call setline(1, ['aaa', repeat('abc ', 1000), 'ccc']) + let start = reltime() + set nolazyredraw redrawtime=101 + syn match Error /\%#=1a*.*X\@<=b*/ + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed > 0.1) + call assert_true(elapsed < 1.0) + + " second time syntax HL is disabled + let start = reltime() + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed < 0.1) + + " after CTRL-L the timeout flag is reset + let start = reltime() + exe "normal \<C-L>" + redraw + let elapsed = reltimefloat(reltime(start)) + call assert_true(elapsed > 0.1) + call assert_true(elapsed < 1.0) + + set redrawtime& + bwipe! +endfunc + func Test_synstack_synIDtrans() new setfiletype c @@ -550,38 +584,42 @@ func Test_syn_wrong_z_one() bwipe! endfunc -func Test_syntax_hangs() - if !has('reltime') || !has('float') || !has('syntax') - return - endif +func Test_syntax_after_bufdo() + call writefile(['/* aaa comment */'], 'Xaaa.c') + call writefile(['/* bbb comment */'], 'Xbbb.c') + call writefile(['/* ccc comment */'], 'Xccc.c') + call writefile(['/* ddd comment */'], 'Xddd.c') + + let bnr = bufnr('%') + new Xaaa.c + badd Xbbb.c + badd Xccc.c + badd Xddd.c + exe "bwipe " . bnr + let l = [] + bufdo call add(l, bufnr('%')) + call assert_equal(4, len(l)) - " This pattern takes a long time to match, it should timeout. - new - call setline(1, ['aaa', repeat('abc ', 1000), 'ccc']) - let start = reltime() - set nolazyredraw redrawtime=101 - syn match Error /\%#=1a*.*X\@<=b*/ - redraw - let elapsed = reltimefloat(reltime(start)) - call assert_true(elapsed > 0.1) - call assert_true(elapsed < 1.0) - - " second time syntax HL is disabled - let start = reltime() - redraw - let elapsed = reltimefloat(reltime(start)) - call assert_true(elapsed < 0.1) - - " after CTRL-L the timeout flag is reset - let start = reltime() - exe "normal \<C-L>" - redraw - let elapsed = reltimefloat(reltime(start)) - call assert_true(elapsed > 0.1) - call assert_true(elapsed < 1.0) + syntax on - set redrawtime& - bwipe! + " This used to only enable syntax HL in the last buffer. + bufdo tab split + tabrewind + for tab in range(1, 4) + norm fm + call assert_equal(['cComment'], map(synstack(line("."), col(".")), 'synIDattr(v:val, "name")')) + tabnext + endfor + + bwipe! Xaaa.c + bwipe! Xbbb.c + bwipe! Xccc.c + bwipe! Xddd.c + syntax off + call delete('Xaaa.c') + call delete('Xbbb.c') + call delete('Xccc.c') + call delete('Xddd.c') endfunc func Test_syntax_foldlevel() diff --git a/src/nvim/testdir/test_textobjects.vim b/src/nvim/testdir/test_textobjects.vim index 7863317eb0..f70cc1f70a 100644 --- a/src/nvim/testdir/test_textobjects.vim +++ b/src/nvim/testdir/test_textobjects.vim @@ -152,6 +152,36 @@ func Test_string_html_objects() normal! dit call assert_equal('-<b></b>', getline('.')) + " copy the tag block from leading indentation before the start tag + let t = " <b>\ntext\n</b>" + $put =t + normal! 2kvaty + call assert_equal("<b>\ntext\n</b>", @") + + " copy the tag block from the end tag + let t = "<title>\nwelcome\n</title>" + $put =t + normal! $vaty + call assert_equal("<title>\nwelcome\n</title>", @") + + " copy the outer tag block from a tag without an end tag + let t = "<html>\n<title>welcome\n</html>" + $put =t + normal! k$vaty + call assert_equal("<html>\n<title>welcome\n</html>", @") + + " nested tag that has < in a different line from > + let t = "<div><div\n></div></div>" + $put =t + normal! k0vaty + call assert_equal("<div><div\n></div></div>", @") + + " nested tag with attribute that has < in a different line from > + let t = "<div><div\nattr=\"attr\"\n></div></div>" + $put =t + normal! 2k0vaty + call assert_equal("<div><div\nattr=\"attr\"\n></div></div>", @") + set quoteescape& enew! endfunc diff --git a/src/nvim/testdir/test_timers.vim b/src/nvim/testdir/test_timers.vim index c3b03fe1a5..13971a918d 100644 --- a/src/nvim/testdir/test_timers.vim +++ b/src/nvim/testdir/test_timers.vim @@ -355,7 +355,7 @@ func Test_error_in_timer_callback() [CODE] call writefile(lines, 'Xtest.vim') - let buf = term_start(GetVimCommandClean() .. ' -S Xtest.vim', {'term_rows': 8}) + let buf = term_start(GetVimCommandCleanTerm() .. ' -S Xtest.vim', {'term_rows': 8}) let job = term_getjob(buf) call WaitForAssert({-> assert_notequal('', term_getline(buf, 8))}) diff --git a/src/nvim/testdir/test_undo.vim b/src/nvim/testdir/test_undo.vim index adcdcb1cd9..3b66071d6d 100644 --- a/src/nvim/testdir/test_undo.vim +++ b/src/nvim/testdir/test_undo.vim @@ -364,6 +364,25 @@ func Test_wundo_errors() bwipe! endfunc +" Check that reading a truncted undo file doesn't hang. +func Test_undofile_truncated() + throw 'skipped: TODO: ' + new + call setline(1, 'hello') + set ul=100 + wundo Xundofile + let contents = readfile('Xundofile', 'B') + + " try several sizes + for size in range(20, 500, 33) + call writefile(contents[0:size], 'Xundofile') + call assert_fails('rundo Xundofile', 'E825:') + endfor + + bwipe! + call delete('Xundofile') +endfunc + func Test_rundo_errors() call assert_fails('rundo XfileDoesNotExist', 'E822:') @@ -373,6 +392,26 @@ func Test_rundo_errors() call delete('Xundofile') endfunc +func Test_undofile_next() + set undofile + new Xfoo.txt + execute "norm ix\<c-g>uy\<c-g>uz\<Esc>" + write + bwipe + + next Xfoo.txt + call assert_equal('xyz', getline(1)) + silent undo + call assert_equal('xy', getline(1)) + silent undo + call assert_equal('x', getline(1)) + bwipe! + + call delete('Xfoo.txt') + call delete('.Xfoo.txt.un~') + set undofile& +endfunc + " Test for undo working properly when executing commands from a register. " Also test this in an empty buffer. func Test_cmd_in_reg_undo() diff --git a/src/nvim/testdir/test_usercommands.vim b/src/nvim/testdir/test_usercommands.vim index fdd3a9abeb..0a89066a2b 100644 --- a/src/nvim/testdir/test_usercommands.vim +++ b/src/nvim/testdir/test_usercommands.vim @@ -276,7 +276,7 @@ func Test_CmdCompletion() call assert_equal('"com -nargs=* + 0 1 ?', @:) call feedkeys(":com -addr=\<C-A>\<C-B>\"\<CR>", 'tx') - call assert_equal('"com -addr=arguments buffers lines loaded_buffers quickfix tabs windows', @:) + call assert_equal('"com -addr=arguments buffers lines loaded_buffers other quickfix tabs windows', @:) call feedkeys(":com -complete=co\<C-A>\<C-B>\"\<CR>", 'tx') call assert_equal('"com -complete=color command compiler', @:) @@ -340,3 +340,202 @@ func Test_use_execute_in_completion() call assert_equal('"DoExec hi', @:) delcommand DoExec endfunc + +func Test_addr_all() + throw 'skipped: requires patch v8.1.0341 to pass' + command! -addr=lines DoSomething let g:a1 = <line1> | let g:a2 = <line2> + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(line('$'), g:a2) + + command! -addr=arguments DoSomething let g:a1 = <line1> | let g:a2 = <line2> + args one two three + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(3, g:a2) + + command! -addr=buffers DoSomething let g:a1 = <line1> | let g:a2 = <line2> + %DoSomething + for low in range(1, bufnr('$')) + if buflisted(low) + break + endif + endfor + call assert_equal(low, g:a1) + call assert_equal(bufnr('$'), g:a2) + + command! -addr=loaded_buffers DoSomething let g:a1 = <line1> | let g:a2 = <line2> + %DoSomething + for low in range(1, bufnr('$')) + if bufloaded(low) + break + endif + endfor + call assert_equal(low, g:a1) + for up in range(bufnr('$'), 1, -1) + if bufloaded(up) + break + endif + endfor + call assert_equal(up, g:a2) + + command! -addr=windows DoSomething let g:a1 = <line1> | let g:a2 = <line2> + new + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(winnr('$'), g:a2) + bwipe + + command! -addr=tabs DoSomething let g:a1 = <line1> | let g:a2 = <line2> + tabnew + %DoSomething + call assert_equal(1, g:a1) + call assert_equal(len(gettabinfo()), g:a2) + bwipe + + command! -addr=other DoSomething echo 'nothing' + DoSomething + call assert_fails('%DoSomething') + + delcommand DoSomething +endfunc + +func Test_command_list() + command! DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 :", + \ execute('command DoCmd')) + + " Test with various -range= and -count= argument values. + command! -range DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . :", + \ execute('command DoCmd')) + command! -range=% DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 % :", + \ execute('command! DoCmd')) + command! -range=2 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 2 :", + \ execute('command DoCmd')) + command! -count=2 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 2c :", + \ execute('command DoCmd')) + + " Test with various -addr= argument values. + command! -addr=lines DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . :", + \ execute('command DoCmd')) + command! -addr=arguments DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . arg :", + \ execute('command DoCmd')) + command! -addr=buffers DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . buf :", + \ execute('command DoCmd')) + command! -addr=loaded_buffers DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . load :", + \ execute('command DoCmd')) + command! -addr=windows DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . win :", + \ execute('command DoCmd')) + command! -addr=tabs DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . tab :", + \ execute('command DoCmd')) + command! -addr=other DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 . ? :", + \ execute('command DoCmd')) + + " Test with various -complete= argument values (non-exhaustive list) + command! -complete=arglist DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 arglist :", + \ execute('command DoCmd')) + command! -complete=augroup DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 augroup :", + \ execute('command DoCmd')) + command! -complete=custom,CustomComplete DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 custom :", + \ execute('command DoCmd')) + command! -complete=customlist,CustomComplete DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 customlist :", + \ execute('command DoCmd')) + + " Test with various -narg= argument values. + command! -nargs=0 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 :", + \ execute('command DoCmd')) + command! -nargs=1 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 1 :", + \ execute('command DoCmd')) + command! -nargs=* DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd * :", + \ execute('command DoCmd')) + command! -nargs=? DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd ? :", + \ execute('command DoCmd')) + command! -nargs=+ DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd + :", + \ execute('command DoCmd')) + + " Test with other arguments. + command! -bang DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n! DoCmd 0 :", + \ execute('command DoCmd')) + command! -bar DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n| DoCmd 0 :", + \ execute('command DoCmd')) + command! -register DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n\" DoCmd 0 :", + \ execute('command DoCmd')) + command! -buffer DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\nb DoCmd 0 :" + \ .. "\n\" DoCmd 0 :", + \ execute('command DoCmd')) + comclear + + " Test with many args. + command! -bang -bar -register -buffer -nargs=+ -complete=environment -addr=windows -count=3 DoCmd : + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n!\"b|DoCmd + 3c win environment :", + \ execute('command DoCmd')) + comclear + + " Test with special characters in command definition. + command! DoCmd :<cr><tab><c-d> + call assert_equal("\n Name Args Address Complete Definition" + \ .. "\n DoCmd 0 :<CR><Tab><C-D>", + \ execute('command DoCmd')) + + " Test output in verbose mode. + command! DoCmd : + call assert_match("^\n" + \ .. " Name Args Address Complete Definition\n" + \ .. " DoCmd 0 :\n" + \ .. "\tLast set from .*/test_usercommands.vim line \\d\\+$", + \ execute('verbose command DoCmd')) + + comclear + call assert_equal("\nNo user-defined commands found", execute(':command Xxx')) + call assert_equal("\nNo user-defined commands found", execute('command')) +endfunc diff --git a/src/nvim/testdir/test_version.vim b/src/nvim/testdir/test_version.vim new file mode 100644 index 0000000000..46cf34979f --- /dev/null +++ b/src/nvim/testdir/test_version.vim @@ -0,0 +1,12 @@ +" Test :version Ex command + +func Test_version() + " version should always return the same string. + let v1 = execute('version') + let v2 = execute('version') + call assert_equal(v1, v2) + + call assert_match("^\n\nNVIM v[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+.*", v1) +endfunc + +" vim: shiftwidth=2 sts=2 expandtab diff --git a/src/nvim/testdir/test_window_cmd.vim b/src/nvim/testdir/test_window_cmd.vim index 9f47ee2904..500e3ff088 100644 --- a/src/nvim/testdir/test_window_cmd.vim +++ b/src/nvim/testdir/test_window_cmd.vim @@ -879,6 +879,10 @@ func Test_window_resize() exe other_winnr .. 'resize 10' call assert_equal(10, winheight(other_winnr)) call assert_equal(&lines - 10 - 3, winheight(0)) + exe other_winnr .. 'resize +1' + exe other_winnr .. 'resize +1' + call assert_equal(12, winheight(other_winnr)) + call assert_equal(&lines - 10 - 3 -2, winheight(0)) %bwipe! endfunc diff --git a/src/nvim/types.h b/src/nvim/types.h index 91420c087f..a3d87f35ca 100644 --- a/src/nvim/types.h +++ b/src/nvim/types.h @@ -21,6 +21,8 @@ typedef int handle_T; // absent callback etc. typedef int LuaRef; +typedef uint64_t NS; + typedef struct expand expand_T; typedef enum { diff --git a/src/nvim/undo.c b/src/nvim/undo.c index 903e57732f..6c5a6cdb46 100644 --- a/src/nvim/undo.c +++ b/src/nvim/undo.c @@ -878,7 +878,12 @@ static u_header_T *unserialize_uhp(bufinfo_T *bi, for (;; ) { int len = undo_read_byte(bi); - if (len == 0 || len == EOF) { + if (len == EOF) { + corruption_error("truncated", file_name); + u_free_uhp(uhp); + return NULL; + } + if (len == 0) { break; } int what = undo_read_byte(bi); diff --git a/src/nvim/window.c b/src/nvim/window.c index e53570edd8..7d08336c25 100644 --- a/src/nvim/window.c +++ b/src/nvim/window.c @@ -2578,9 +2578,14 @@ int win_close(win_T *win, bool free_buf) return OK; } - /* Free independent synblock before the buffer is freed. */ - if (win->w_buffer != NULL) + // Free independent synblock before the buffer is freed. + if (win->w_buffer != NULL) { reset_synblock(win); + } + // When the quickfix/location list window is closed, unlist the buffer. + if (win->w_buffer != NULL && bt_quickfix(win->w_buffer)) { + win->w_buffer->b_p_bl = false; + } /* * Close the link to the buffer. |